cloudllm_mcp 0.2.1

Reusable MCP runtime, protocol types, and HTTP server/client primitives.
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
//! Tool protocol abstraction layer.
//!
//! This module provides a flexible abstraction for connecting agents to various tool protocols.
//! It supports multiple standards including MCP (Model Context Protocol), custom function calling,
//! Memory persistence, and allows users to implement their own tool communication mechanisms.
//!
//! # Architecture
//!
//! **Single Protocol** (traditional):
//! ```text
//! Agent → ToolRegistry → ToolProtocol → Single Tool Source
//! ```
//!
//! **Multi-Protocol** (new in 0.5.0):
//! ```text
//! Agent → ToolRegistry → [Protocol1, Protocol2, Protocol3]
//!         (routing map)     ↓          ↓          ↓
//!                        Local      YouTube    GitHub
//!                        Tools      Server     Server
//! ```
//!
//! # Key Components
//!
//! - **ToolProtocol trait**: Define how tools are executed, discovered, and described
//! - **ToolRegistry**: Single or multi-protocol tool aggregation with transparent routing
//! - **ToolMetadata**: Tool identity, description, parameters
//! - **ToolParameter**: Type-safe parameter definitions with validation
//! - **ToolResult**: Structured tool execution results
//! - **Tool**: Runtime tool instance bound to a protocol
//!
//! # Single Protocol Example
//!
//! ```rust,ignore
//! use std::sync::Arc;
//! use mcp::protocol::{ToolMetadata, ToolProtocol, ToolRegistry, ToolResult};
//!
//! struct MyProtocol;
//!
//! #[async_trait::async_trait]
//! impl ToolProtocol for MyProtocol {
//!     async fn execute(
//!         &self,
//!         _tool_name: &str,
//!         _parameters: serde_json::Value,
//!     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
//!         Ok(ToolResult::success(serde_json::json!({"ok": true})))
//!     }
//!     async fn list_tools(&self) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
//!         Ok(vec![ToolMetadata::new("demo", "Demo tool")])
//!     }
//!     async fn get_tool_metadata(&self, _: &str) -> Result<ToolMetadata, Box<dyn std::error::Error + Send + Sync>> {
//!         Ok(ToolMetadata::new("demo", "Demo tool"))
//!     }
//!     fn protocol_name(&self) -> &str { "demo" }
//! }
//!
//! # #[tokio::main]
//! # async fn main() {
//! let protocol = Arc::new(MyProtocol);
//! let mut registry = ToolRegistry::new(protocol);
//! let _ = registry.discover_tools_from_primary().await;
//! # }
//! ```
//!
//! # Multi-Protocol Example
//!
//! ```rust,ignore
//! use mcp::client::McpClientProtocol;
//! use mcp::protocol::ToolRegistry;
//!
//! # #[tokio::main]
//! # async fn main() {
//! let mut registry = ToolRegistry::empty();
//! let _ = registry
//!     .add_protocol("remote", std::sync::Arc::new(McpClientProtocol::new("http://localhost:8080".to_string())))
//!     .await;
//! # }
//! ```

use crate::resources::ResourceMetadata;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::sync::Arc;

/// Provider-agnostic tool definition suitable for LLM native tool calling.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    /// Tool name as it will appear in the API `tools` array.
    pub name: String,
    /// Human-readable description surfaced to the model.
    pub description: String,
    /// JSON Schema object describing accepted parameters.
    pub parameters_schema: serde_json::Value,
}

/// Represents the result of a tool execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// Whether the tool execution was successful
    pub success: bool,
    /// The output data from the tool
    pub output: serde_json::Value,
    /// Optional error message if execution failed
    pub error: Option<String>,
    /// Metadata about the execution (timing, cost, etc.)
    pub metadata: HashMap<String, serde_json::Value>,
}

impl ToolResult {
    /// Convenience constructor for successful tool execution.
    pub fn success(output: serde_json::Value) -> Self {
        Self {
            success: true,
            output,
            error: None,
            metadata: HashMap::new(),
        }
    }

    /// Convenience constructor for failed tool execution.
    pub fn failure(error: String) -> Self {
        Self {
            success: false,
            output: serde_json::Value::Null,
            error: Some(error),
            metadata: HashMap::new(),
        }
    }

    /// Attach protocol or application specific metadata to the result.
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }
}

/// Defines the type of a tool parameter
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ToolParameterType {
    /// UTF-8 string value.
    String,
    /// Floating-point number.
    Number,
    /// Integer number.
    Integer,
    /// Boolean value.
    Boolean,
    /// JSON array.
    Array,
    /// JSON object.
    Object,
}

/// Defines a parameter for a tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolParameter {
    /// Parameter name.
    pub name: String,
    /// Parameter value type.
    #[serde(rename = "type")]
    pub param_type: ToolParameterType,
    /// Human-readable description.
    pub description: Option<String>,
    /// Whether the caller must provide this parameter.
    pub required: bool,
    /// Optional default value.
    pub default: Option<serde_json::Value>,
    /// For array types, specifies the type of items
    pub items: Option<Box<ToolParameterType>>,
    /// For object types, specifies nested properties
    pub properties: Option<HashMap<String, ToolParameter>>,
}

impl ToolParameter {
    /// Define a new tool parameter with the provided name and type.
    pub fn new(name: impl Into<String>, param_type: ToolParameterType) -> Self {
        Self {
            name: name.into(),
            param_type,
            description: None,
            required: false,
            default: None,
            items: None,
            properties: None,
        }
    }

    /// Add a human readable description that will surface in generated schemas.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Mark the argument as required.
    pub fn required(mut self) -> Self {
        self.required = true;
        self
    }

    /// Provide a default value that will be used when the LLM omits the parameter.
    pub fn with_default(mut self, default: serde_json::Value) -> Self {
        self.default = Some(default);
        self
    }

    /// For array parameters, declare the type of the contained items.
    pub fn with_items(mut self, item_type: ToolParameterType) -> Self {
        self.items = Some(Box::new(item_type));
        self
    }

    /// For object parameters, describe the nested properties.
    pub fn with_properties(mut self, properties: HashMap<String, ToolParameter>) -> Self {
        self.properties = Some(properties);
        self
    }

    /// Converts this parameter to a JSON Schema snippet suitable for native tool-calling.
    ///
    /// The generated schema follows [JSON Schema draft-07] conventions accepted by all major
    /// providers (OpenAI, Anthropic, Grok, Gemini).
    ///
    /// | `ToolParameterType` | Schema produced |
    /// |---|---|
    /// | `String` | `{"type":"string"}` |
    /// | `Number` | `{"type":"number"}` |
    /// | `Integer` | `{"type":"integer"}` |
    /// | `Boolean` | `{"type":"boolean"}` |
    /// | `Array` | `{"type":"array","items":{...}}` |
    /// | `Object` | `{"type":"object","properties":{...},"required":[...]}` |
    ///
    /// # Example
    ///
    /// ```rust
    /// use mcp::{ToolParameter, ToolParameterType};
    ///
    /// let param = ToolParameter::new("query", ToolParameterType::String)
    ///     .with_description("Search query string")
    ///     .required();
    ///
    /// let schema = param.to_json_schema();
    /// assert_eq!(schema["type"], "string");
    /// assert_eq!(schema["description"], "Search query string");
    /// ```
    pub fn to_json_schema(&self) -> serde_json::Value {
        let mut schema = match &self.param_type {
            ToolParameterType::String => serde_json::json!({"type": "string"}),
            ToolParameterType::Number => serde_json::json!({"type": "number"}),
            ToolParameterType::Integer => serde_json::json!({"type": "integer"}),
            ToolParameterType::Boolean => serde_json::json!({"type": "boolean"}),
            ToolParameterType::Array => {
                let items_schema = self
                    .items
                    .as_ref()
                    .map(|t| param_type_to_schema(t))
                    .unwrap_or_else(|| serde_json::json!({}));
                serde_json::json!({"type": "array", "items": items_schema})
            }
            ToolParameterType::Object => {
                if let Some(props) = &self.properties {
                    let properties: serde_json::Map<String, serde_json::Value> = props
                        .iter()
                        .map(|(k, v)| (k.clone(), v.to_json_schema()))
                        .collect();
                    let required: Vec<&str> = props
                        .values()
                        .filter(|p| p.required)
                        .map(|p| p.name.as_str())
                        .collect();
                    serde_json::json!({
                        "type": "object",
                        "properties": properties,
                        "required": required
                    })
                } else {
                    serde_json::json!({"type": "object"})
                }
            }
        };

        // Attach description if present
        if let Some(desc) = &self.description {
            schema["description"] = serde_json::Value::String(desc.clone());
        }

        schema
    }
}

/// Convert a bare [`ToolParameterType`] to a minimal JSON Schema value (no description).
///
/// Used internally when building array `items` schemas.
fn param_type_to_schema(t: &ToolParameterType) -> serde_json::Value {
    match t {
        ToolParameterType::String => serde_json::json!({"type": "string"}),
        ToolParameterType::Number => serde_json::json!({"type": "number"}),
        ToolParameterType::Integer => serde_json::json!({"type": "integer"}),
        ToolParameterType::Boolean => serde_json::json!({"type": "boolean"}),
        ToolParameterType::Array => serde_json::json!({"type": "array"}),
        ToolParameterType::Object => serde_json::json!({"type": "object"}),
    }
}

/// Metadata about a tool
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolMetadata {
    /// Tool name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Parameter schema entries.
    pub parameters: Vec<ToolParameter>,
    /// Additional metadata specific to the protocol
    pub protocol_metadata: HashMap<String, serde_json::Value>,
}

impl ToolMetadata {
    /// Create metadata with the supplied identifier and description.
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            parameters: Vec::new(),
            protocol_metadata: HashMap::new(),
        }
    }

    /// Append a parameter definition to the tool metadata.
    pub fn with_parameter(mut self, param: ToolParameter) -> Self {
        self.parameters.push(param);
        self
    }

    /// Add protocol specific metadata (e.g. MCP capability flags).
    pub fn with_protocol_metadata(
        mut self,
        key: impl Into<String>,
        value: serde_json::Value,
    ) -> Self {
        self.protocol_metadata.insert(key.into(), value);
        self
    }

    /// Builds a [`ToolDefinition`] (JSON Schema) from this metadata.
    ///
    /// The resulting [`ToolDefinition`] is ready to be passed to
    /// [`ClientWrapper::send_message`](crate::client_wrapper::ClientWrapper::send_message)
    /// as part of the `tools` slice.  Parameters marked `required` are collected into the
    /// JSON Schema `"required"` array automatically.
    ///
    /// # Example
    ///
    /// ```rust
    /// use mcp::{ToolMetadata, ToolParameter, ToolParameterType};
    ///
    /// let meta = ToolMetadata::new("calculator", "Evaluates a math expression")
    ///     .with_parameter(
    ///         ToolParameter::new("expression", ToolParameterType::String)
    ///             .with_description("The expression to evaluate")
    ///             .required(),
    ///     );
    ///
    /// let def = meta.to_tool_definition();
    /// assert_eq!(def.name, "calculator");
    /// let schema = &def.parameters_schema;
    /// assert_eq!(schema["type"], "object");
    /// assert!(schema["properties"]["expression"].is_object());
    /// ```
    pub fn to_tool_definition(&self) -> ToolDefinition {
        let mut properties = serde_json::Map::new();
        let mut required: Vec<String> = Vec::new();

        for param in &self.parameters {
            properties.insert(param.name.clone(), param.to_json_schema());
            if param.required {
                required.push(param.name.clone());
            }
        }

        let parameters_schema = serde_json::json!({
            "type": "object",
            "properties": properties,
            "required": required
        });

        ToolDefinition {
            name: self.name.clone(),
            description: self.description.clone(),
            parameters_schema,
        }
    }
}

/// Trait for implementing tool execution protocols
#[async_trait]
pub trait ToolProtocol: Send + Sync {
    /// Execute a tool with the given parameters
    async fn execute(
        &self,
        tool_name: &str,
        parameters: serde_json::Value,
    ) -> Result<ToolResult, Box<dyn Error + Send + Sync>>;

    /// Get metadata about available tools
    async fn list_tools(&self) -> Result<Vec<ToolMetadata>, Box<dyn Error + Send + Sync>>;

    /// Get metadata about a specific tool
    async fn get_tool_metadata(
        &self,
        tool_name: &str,
    ) -> Result<ToolMetadata, Box<dyn Error + Send + Sync>>;

    /// Protocol identifier (e.g., "mcp", "custom", "openai-functions")
    fn protocol_name(&self) -> &str;

    /// Initialize/connect to the tool protocol
    async fn initialize(&mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
        Ok(())
    }

    /// Cleanup/disconnect from the tool protocol
    async fn shutdown(&mut self) -> Result<(), Box<dyn Error + Send + Sync>> {
        Ok(())
    }

    /// List available resources (MCP Resource support)
    ///
    /// Resources are application-provided contextual data that agents can read.
    /// This method is optional and defaults to returning an empty list.
    async fn list_resources(&self) -> Result<Vec<ResourceMetadata>, Box<dyn Error + Send + Sync>> {
        Ok(Vec::new())
    }

    /// Read the content of a resource by URI (MCP Resource support)
    ///
    /// This method is optional and defaults to returning NotFound.
    async fn read_resource(&self, uri: &str) -> Result<String, Box<dyn Error + Send + Sync>> {
        Err(format!("Resource not found: {}", uri).into())
    }

    /// Check if this protocol supports resources
    fn supports_resources(&self) -> bool {
        false
    }
}

/// Error types for tool operations
#[derive(Debug, Clone)]
pub enum ToolError {
    /// Requested tool is not registered in the current registry/protocol.
    NotFound(String),
    /// Tool execution completed with an application level failure.
    ExecutionFailed(String),
    /// The provided JSON parameters failed validation or deserialization.
    InvalidParameters(String),
    /// A lower level protocol/transport error occurred.
    ProtocolError(String),
}

impl fmt::Display for ToolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ToolError::NotFound(name) => write!(f, "Tool not found: {}", name),
            ToolError::ExecutionFailed(msg) => write!(f, "Tool execution failed: {}", msg),
            ToolError::InvalidParameters(msg) => write!(f, "Invalid parameters: {}", msg),
            ToolError::ProtocolError(msg) => write!(f, "Protocol error: {}", msg),
        }
    }
}

impl Error for ToolError {}

/// A tool that can be used by agents
pub struct Tool {
    /// Metadata describing the tool interface.
    metadata: ToolMetadata,
    /// Underlying protocol implementation that actually executes the tool.
    protocol: Arc<dyn ToolProtocol>,
}

impl Tool {
    /// Create a new tool bound to the supplied protocol implementation.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        protocol: Arc<dyn ToolProtocol>,
    ) -> Self {
        Self {
            metadata: ToolMetadata::new(name, description),
            protocol,
        }
    }

    /// Add a parameter definition to the tool builder.
    pub fn with_parameter(mut self, param: ToolParameter) -> Self {
        self.metadata.parameters.push(param);
        self
    }

    /// Attach protocol specific metadata to the tool builder.
    pub fn with_protocol_metadata(
        mut self,
        key: impl Into<String>,
        value: serde_json::Value,
    ) -> Self {
        self.metadata.protocol_metadata.insert(key.into(), value);
        self
    }

    /// Borrow the static metadata for the tool.
    pub fn metadata(&self) -> &ToolMetadata {
        &self.metadata
    }

    /// Execute the tool using the configured protocol.
    pub async fn execute(
        &self,
        parameters: serde_json::Value,
    ) -> Result<ToolResult, Box<dyn Error + Send + Sync>> {
        self.protocol.execute(&self.metadata.name, parameters).await
    }
}

/// Registry for managing tools available to agents
///
/// Supports single or multiple tool protocols, enabling agents to transparently
/// access tools from multiple sources (local functions, MCP servers, etc.)
///
/// # Single Protocol
///
/// ```ignore
/// use async_trait::async_trait;
/// use mcp::{ToolMetadata, ToolProtocol, ToolRegistry, ToolResult};
/// use std::sync::Arc;
///
/// struct DemoProtocol;
///
/// #[async_trait]
/// impl ToolProtocol for DemoProtocol {
///     async fn execute(
///         &self,
///         _tool_name: &str,
///         _parameters: serde_json::Value,
///     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(ToolResult::success(serde_json::json!({"ok": true})))
///     }
///
///     async fn list_tools(
///         &self,
///     ) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(vec![])
///     }
/// }
///
/// let protocol = Arc::new(DemoProtocol);
/// let registry = ToolRegistry::new(protocol);
/// ```
///
/// # Multiple Protocols
///
/// ```ignore
/// use async_trait::async_trait;
/// use mcp::{ToolMetadata, ToolProtocol, ToolRegistry, ToolResult};
/// use std::sync::Arc;
///
/// struct LocalProtocol;
/// struct RemoteProtocol;
///
/// #[async_trait]
/// impl ToolProtocol for LocalProtocol {
///     async fn execute(
///         &self,
///         _tool_name: &str,
///         _parameters: serde_json::Value,
///     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(ToolResult::success(serde_json::json!({"source": "local"})))
///     }
///
///     async fn list_tools(
///         &self,
///     ) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(vec![])
///     }
/// }
///
/// #[async_trait]
/// impl ToolProtocol for RemoteProtocol {
///     async fn execute(
///         &self,
///         _tool_name: &str,
///         _parameters: serde_json::Value,
///     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(ToolResult::success(serde_json::json!({"source": "remote"})))
///     }
///
///     async fn list_tools(
///         &self,
///     ) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
///         Ok(vec![])
///     }
/// }
///
/// # async {
/// let mut registry = ToolRegistry::empty();
///
/// // Add local tools
/// registry.add_protocol(
///     "local",
///     Arc::new(LocalProtocol)
/// ).await.ok();
///
/// // Add remote MCP server
/// registry.add_protocol(
///     "youtube",
///     Arc::new(RemoteProtocol)
/// ).await.ok();
///
/// // Agent transparently accesses both
/// # };
/// ```
pub struct ToolRegistry {
    /// All discovered tools from all protocols
    tools: HashMap<String, Tool>,
    /// Mapping of tool_name -> protocol_name for routing
    tool_to_protocol: HashMap<String, String>,
    /// All registered protocols
    protocols: HashMap<String, Arc<dyn ToolProtocol>>,
    /// Primary protocol (for backwards compatibility with single-protocol code)
    primary_protocol: Option<Arc<dyn ToolProtocol>>,
}

impl ToolRegistry {
    /// Build a registry powered by a single protocol implementation.
    ///
    /// This is the traditional single-protocol mode. Use `empty()` and `add_protocol()`
    /// for multi-protocol support.
    pub fn new(protocol: Arc<dyn ToolProtocol>) -> Self {
        Self {
            tools: HashMap::new(),
            tool_to_protocol: HashMap::new(),
            protocols: {
                let mut m = HashMap::new();
                m.insert("primary".to_string(), protocol.clone());
                m
            },
            primary_protocol: Some(protocol),
        }
    }

    /// Create an empty registry ready to accept multiple protocols.
    ///
    /// Use `add_protocol()` to register protocols.
    pub fn empty() -> Self {
        Self {
            tools: HashMap::new(),
            tool_to_protocol: HashMap::new(),
            protocols: HashMap::new(),
            primary_protocol: None,
        }
    }

    /// Register a protocol and discover its tools.
    ///
    /// # Arguments
    ///
    /// * `protocol_name` - Unique identifier for this protocol (e.g., "local", "youtube", "github")
    /// * `protocol` - The ToolProtocol implementation
    ///
    /// # Tool Discovery
    ///
    /// This method calls `protocol.list_tools()` to discover available tools
    /// and automatically registers them in the registry.
    ///
    /// # Conflicts
    ///
    /// If a tool with the same name already exists, it will be replaced.
    /// The new protocol's tool takes precedence.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use async_trait::async_trait;
    /// use mcp::{ToolMetadata, ToolProtocol, ToolRegistry, ToolResult};
    /// use std::sync::Arc;
    ///
    /// struct MemoryServerProtocol;
    ///
    /// #[async_trait]
    /// impl ToolProtocol for MemoryServerProtocol {
    ///     async fn execute(
    ///         &self,
    ///         _tool_name: &str,
    ///         _parameters: serde_json::Value,
    ///     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
    ///         Ok(ToolResult::success(serde_json::json!({"ok": true})))
    ///     }
    ///
    ///     async fn list_tools(
    ///         &self,
    ///     ) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
    ///         Ok(vec![])
    ///     }
    /// }
    ///
    /// # async {
    /// let mut registry = ToolRegistry::empty();
    /// registry.add_protocol(
    ///     "memory_server",
    ///     Arc::new(MemoryServerProtocol)
    /// ).await?;
    /// # Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
    /// # };
    /// ```
    pub async fn add_protocol(
        &mut self,
        protocol_name: &str,
        protocol: Arc<dyn ToolProtocol>,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        // Discover tools from this protocol
        let discovered_tools = protocol.list_tools().await?;

        // Register the protocol
        self.protocols
            .insert(protocol_name.to_string(), protocol.clone());

        // Register discovered tools
        for tool_meta in discovered_tools {
            let tool_name = tool_meta.name.clone();

            // Create a Tool that routes through this protocol
            let tool = Tool::new(
                tool_name.clone(),
                tool_meta.description.clone(),
                protocol.clone(),
            );

            // Copy over any additional parameters and metadata
            let mut tool = tool;
            for param in &tool_meta.parameters {
                tool = tool.with_parameter(param.clone());
            }
            for (key, value) in &tool_meta.protocol_metadata {
                tool = tool.with_protocol_metadata(key.clone(), value.clone());
            }

            // Register the tool and its routing
            self.tools.insert(tool_name.clone(), tool);
            self.tool_to_protocol
                .insert(tool_name, protocol_name.to_string());
        }

        Ok(())
    }

    /// Remove a protocol and all its tools from the registry.
    pub fn remove_protocol(&mut self, protocol_name: &str) {
        self.protocols.remove(protocol_name);

        // Collect tool names to remove
        let tools_to_remove: Vec<String> = self
            .tool_to_protocol
            .iter()
            .filter(|(_, pn)| *pn == protocol_name)
            .map(|(tn, _)| tn.clone())
            .collect();

        // Remove the tools
        for tool_name in tools_to_remove {
            self.tools.remove(&tool_name);
            self.tool_to_protocol.remove(&tool_name);
        }
    }

    /// Insert or replace a tool definition (for manual tool registration).
    pub fn add_tool(&mut self, tool: Tool) {
        self.tools.insert(tool.metadata.name.clone(), tool);
    }

    /// Remove a tool by name returning the owned entry if present.
    pub fn remove_tool(&mut self, name: &str) -> Option<Tool> {
        self.tool_to_protocol.remove(name);
        self.tools.remove(name)
    }

    /// Borrow a tool by name.
    pub fn get_tool(&self, name: &str) -> Option<&Tool> {
        self.tools.get(name)
    }

    /// List metadata for registered tools (iteration order follows the underlying map).
    pub fn list_tools(&self) -> Vec<&ToolMetadata> {
        self.tools.values().map(|t| &t.metadata).collect()
    }

    /// Discover tools from the primary protocol (for single-protocol registries).
    ///
    /// This is useful after registering tools with the protocol to populate the registry.
    /// For multi-protocol registries, use `add_protocol()` instead.
    pub async fn discover_tools_from_primary(
        &mut self,
    ) -> Result<(), Box<dyn Error + Send + Sync>> {
        if let Some(protocol) = &self.primary_protocol {
            let discovered_tools = protocol.list_tools().await?;
            for tool_meta in discovered_tools {
                let tool_name = tool_meta.name.clone();
                let tool = Tool::new(
                    tool_name.clone(),
                    tool_meta.description.clone(),
                    protocol.clone(),
                );

                // Copy over parameters and metadata
                let mut tool = tool;
                for param in &tool_meta.parameters {
                    tool = tool.with_parameter(param.clone());
                }
                for (key, value) in &tool_meta.protocol_metadata {
                    tool = tool.with_protocol_metadata(key.clone(), value.clone());
                }

                self.tools.insert(tool_name.clone(), tool);
                self.tool_to_protocol
                    .insert(tool_name, "primary".to_string());
            }
            Ok(())
        } else {
            Err("No primary protocol available".into())
        }
    }

    /// Get which protocol handles a specific tool.
    pub fn get_tool_protocol(&self, tool_name: &str) -> Option<&str> {
        self.tool_to_protocol.get(tool_name).map(|s| s.as_str())
    }

    /// Get all registered protocol names.
    pub fn list_protocols(&self) -> Vec<&str> {
        self.protocols.keys().map(|s| s.as_str()).collect()
    }

    /// Execute a named tool with serialized parameters.
    pub async fn execute_tool(
        &self,
        tool_name: &str,
        parameters: serde_json::Value,
    ) -> Result<ToolResult, Box<dyn Error + Send + Sync>> {
        let tool = self
            .tools
            .get(tool_name)
            .ok_or_else(|| ToolError::NotFound(tool_name.to_string()))?;

        tool.execute(parameters).await
    }

    /// Borrow the primary protocol implementation (for single-protocol mode).
    ///
    /// Returns None if registry was created with `empty()` or has multiple protocols.
    pub fn protocol(&self) -> Option<&Arc<dyn ToolProtocol>> {
        self.primary_protocol.as_ref()
    }

    /// Returns all registered tools as [`ToolDefinition`]s ready to pass to the LLM.
    ///
    /// Iterates over every tool in the registry, calling
    /// [`ToolMetadata::to_tool_definition`] on each, and returns the results as a `Vec`.
    /// An empty `Vec` is returned when no tools have been registered.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use async_trait::async_trait;
    /// use mcp::{Tool, ToolDefinition, ToolMetadata, ToolProtocol, ToolRegistry, ToolResult};
    /// use std::sync::Arc;
    ///
    /// struct DemoProtocol;
    ///
    /// #[async_trait]
    /// impl ToolProtocol for DemoProtocol {
    ///     async fn execute(
    ///         &self,
    ///         _tool_name: &str,
    ///         _parameters: serde_json::Value,
    ///     ) -> Result<ToolResult, Box<dyn std::error::Error + Send + Sync>> {
    ///         Ok(ToolResult::success(serde_json::json!({"ok": true})))
    ///     }
    ///
    ///     async fn list_tools(
    ///         &self,
    ///     ) -> Result<Vec<ToolMetadata>, Box<dyn std::error::Error + Send + Sync>> {
    ///         Ok(vec![])
    ///     }
    /// }
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let protocol = Arc::new(DemoProtocol);
    /// let mut registry = ToolRegistry::new(protocol.clone());
    ///
    /// let tool = Tool::new("calculator", "Evaluates math", protocol);
    /// registry.add_tool(tool);
    ///
    /// let defs = registry.to_tool_definitions();
    /// assert_eq!(defs.len(), 1);
    /// assert_eq!(defs[0].name, "calculator");
    /// # }
    /// ```
    pub fn to_tool_definitions(&self) -> Vec<ToolDefinition> {
        self.tools
            .values()
            .map(|t| t.metadata.to_tool_definition())
            .collect()
    }
}

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

    struct MockProtocol;

    #[async_trait]
    impl ToolProtocol for MockProtocol {
        async fn execute(
            &self,
            tool_name: &str,
            _parameters: serde_json::Value,
        ) -> Result<ToolResult, Box<dyn Error + Send + Sync>> {
            Ok(ToolResult::success(serde_json::json!({
                "tool": tool_name,
                "result": "mock_result"
            })))
        }

        async fn list_tools(&self) -> Result<Vec<ToolMetadata>, Box<dyn Error + Send + Sync>> {
            Ok(vec![])
        }

        async fn get_tool_metadata(
            &self,
            _tool_name: &str,
        ) -> Result<ToolMetadata, Box<dyn Error + Send + Sync>> {
            Ok(ToolMetadata::new("mock_tool", "A mock tool"))
        }

        fn protocol_name(&self) -> &str {
            "mock"
        }
    }

    // ── Private-field tests (must stay inline) ────────────────────────────

    #[tokio::test]
    async fn test_get_tool_protocol() {
        let protocol = Arc::new(MockProtocol);
        let mut registry = ToolRegistry::empty();

        registry
            .add_protocol("local", protocol.clone())
            .await
            .unwrap();

        let tool = Tool::new("calculator", "Performs calculations", protocol.clone());
        registry.add_tool(tool);
        registry
            .tool_to_protocol
            .insert("calculator".to_string(), "local".to_string());

        assert_eq!(registry.get_tool_protocol("calculator"), Some("local"));
        assert_eq!(registry.get_tool_protocol("nonexistent"), None);
    }

    #[tokio::test]
    async fn test_remove_protocol_removes_tools() {
        let protocol = Arc::new(MockProtocol);
        let mut registry = ToolRegistry::empty();

        registry
            .add_protocol("protocol1", protocol.clone())
            .await
            .unwrap();

        let tool1 = Tool::new("tool1", "First tool", protocol.clone());
        registry.add_tool(tool1);
        registry
            .tool_to_protocol
            .insert("tool1".to_string(), "protocol1".to_string());

        let tool2 = Tool::new("tool2", "Second tool", protocol.clone());
        registry.add_tool(tool2);
        registry
            .tool_to_protocol
            .insert("tool2".to_string(), "protocol1".to_string());

        assert_eq!(registry.list_tools().len(), 2);

        registry.remove_protocol("protocol1");

        assert_eq!(registry.list_tools().len(), 0);
        assert_eq!(registry.get_tool_protocol("tool1"), None);
        assert_eq!(registry.get_tool_protocol("tool2"), None);
    }
}