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
//! # Arsenal Port - External Tool Integration Interface
//!
//! This module defines the port interfaces for the Arsenal tool system,
//! enabling Paladins to interact with external tools and services through
//! the Model Context Protocol (MCP).
//!
//! ## Purpose
//!
//! The Arsenal ports provide a standardized interface for:
//! - **Tool Discovery**: Listing available tools from MCP servers
//! - **Tool Registration**: Managing the tool registry lifecycle
//! - **Tool Invocation**: Executing tools with validated parameters
//! - **Tool Validation**: Checking parameter schemas before execution
//!
//! Following hexagonal architecture, these traits abstract tool operations
//! from their implementations (STDIO MCP, SSE MCP, direct integrations).
//!
//! ## Hexagonal Architecture Context
//!
//! ```text
//! ┌─────────────────────────────────────────────────────┐
//! │ Application Layer │
//! │ ┌──────────────────────────────────────────────┐ │
//! │ │ PaladinExecutionService │ │
//! │ │ - Uses ArsenalPort to execute tools │ │
//! │ │ - Validates calls before invocation │ │
//! │ └──────────────────────────────────────────────┘ │
//! │ │ │
//! │ ▼ │
//! │ ┌──────────────────────────────────────────────┐ │
//! │ │ ArsenalPort & ArsenalRegistry (this module) │ │
//! │ │ - Tool execution interface │ │
//! │ │ - Tool registry interface │ │
//! │ └──────────────────────────────────────────────┘ │
//! └─────────────────────────────────────────────────────┘
//! │
//! ▼
//! ┌─────────────────────────────────────────────────────┐
//! │ Infrastructure Layer │
//! │ ┌──────────────────────────────────────────────┐ │
//! │ │ MCPStdioAdapter (STDIN/STDOUT MCP servers) │ │
//! │ │ MCPSseAdapter (HTTP SSE MCP servers) │ │
//! │ │ DirectToolAdapter (Native Rust tools) │ │
//! │ └──────────────────────────────────────────────┘ │
//! └─────────────────────────────────────────────────────┘
//! ```
//!
//! ## Thread Safety
//!
//! All implementations must be `Send + Sync`:
//! - **Send**: Tools may be invoked from different threads
//! - **Sync**: Multiple Paladins may access the Arsenal concurrently
//! - Implementations must handle concurrent tool invocations safely
//!
//! ## Error Handling
//!
//! Tool operations can fail for several reasons:
//! - **Tool Not Found**: Requested tool doesn't exist in registry
//! - **Invalid Arguments**: Parameters don't match JSON schema
//! - **Timeout**: Tool execution exceeded time limit
//! - **Protocol Error**: MCP communication failure
//! - **Transport Error**: Network/process communication failure
//!
//! All errors are represented via [`ArsenalError`](paladin_core::platform::container::arsenal::ArsenalError)
//! with context for debugging and recovery strategies.
//!
//! ## Common Use Cases
//!
//! ### 1. Web Search Tool
//!
//! ```rust,no_run
//! use paladin::application::ports::output::arsenal_port::{ArsenalPort, ArsenalRegistry};
//! use paladin::core::platform::container::arsenal::{Armament, ArmamentCall};
//! use std::collections::HashMap;
//! use serde_json::json;
//!
//! async fn search_web(
//! arsenal: &dyn ArsenalPort,
//! query: &str,
//! ) -> Result<String, Box<dyn std::error::Error>> {
//! let mut args = HashMap::new();
//! args.insert("query".to_string(), json!(query));
//!
//! let call = ArmamentCall::new("web_search", args);
//! arsenal.validate_call(&call)?;
//!
//! let result = arsenal.invoke(call).await?;
//!
//! if result.success {
//! Ok(result.output.unwrap().to_string())
//! } else {
//! Err(result.error.unwrap().into())
//! }
//! }
//! ```
//!
//! ### 2. File System Operations
//!
//! ```rust,no_run
//! use paladin::application::ports::output::arsenal_port::{ArsenalPort, ArsenalRegistry};
//! use paladin::core::platform::container::arsenal::ArmamentCall;
//! use std::collections::HashMap;
//! use serde_json::json;
//!
//! async fn read_file_content(
//! arsenal: &dyn ArsenalPort,
//! file_path: &str,
//! ) -> Result<String, Box<dyn std::error::Error>> {
//! let mut args = HashMap::new();
//! args.insert("path".to_string(), json!(file_path));
//!
//! let call = ArmamentCall::new("read_file", args);
//! let result = arsenal.invoke(call).await?;
//!
//! Ok(serde_json::from_value(result.output.unwrap())?)
//! }
//! ```
//!
//! ### 3. MCP Tool Discovery and Registration
//!
//! ```rust,no_run
//! use paladin::application::ports::output::arsenal_port::ArsenalRegistry;
//! use paladin::core::platform::container::arsenal::Armament;
//! use serde_json::json;
//!
//! async fn discover_and_register_tools(
//! registry: &dyn ArsenalRegistry,
//! ) -> Result<(), Box<dyn std::error::Error>> {
//! // Simulate MCP tool discovery
//! let calculator = Armament {
//! name: "calculator".to_string(),
//! description: "Arithmetic operations".to_string(),
//! parameters: json!({
//! "type": "object",
//! "properties": {
//! "operation": {"type": "string", "enum": ["add", "subtract"]},
//! "x": {"type": "number"},
//! "y": {"type": "number"}
//! }
//! }),
//! required_params: vec!["operation".to_string(), "x".to_string(), "y".to_string()],
//! };
//!
//! registry.register(calculator).await;
//!
//! // Verify registration
//! if let Some(tool) = registry.get("calculator").await {
//! println!("Registered: {} - {}", tool.name, tool.description);
//! }
//!
//! Ok(())
//! }
//! ```
//!
//! ### 4. Tool Listing and Discovery
//!
//! ```rust,no_run
//! use paladin::application::ports::output::arsenal_port::ArsenalPort;
//!
//! async fn list_available_tools(arsenal: &dyn ArsenalPort) {
//! let tools = arsenal.list_armaments().await;
//!
//! println!("Available tools: {}", tools.len());
//! for tool in tools {
//! println!(" • {} - {}", tool.name, tool.description);
//! println!(" Required params: {:?}", tool.required_params);
//! }
//! }
//! ```
//!
//! ## Implementation Notes
//!
//! ### MCP Protocol Integration
//!
//! The Model Context Protocol (MCP) enables standardized tool communication:
//!
//! ```rust,ignore
//! // STDIO-based MCP (command-line tools)
//! let stdio_adapter = MCPStdioAdapter::new("uvx", vec!["mcp-web-search"]);
//! stdio_adapter.connect().await?;
//!
//! // SSE-based MCP (HTTP streaming)
//! let sse_adapter = MCPSseAdapter::new("https://mcp-server.example.com");
//! sse_adapter.connect().await?;
//!
//! // Discover tools from MCP server
//! let client = MCPClient::new(Box::new(stdio_adapter));
//! let tools = client.discover_tools().await?;
//!
//! // Register discovered tools
//! for tool in tools {
//! registry.register(tool).await;
//! }
//! ```
//!
//! ### Tool Validation Strategy
//!
//! Always validate tool calls before invocation to catch errors early:
//!
//! ```rust,ignore
//! // Validate before invoking
//! if let Err(e) = arsenal.validate_call(&call) {
//! return Err(format!("Invalid tool call: {}", e));
//! }
//!
//! // Validation checks:
//! // 1. Tool exists in registry
//! // 2. All required parameters provided
//! // 3. Parameter types match JSON schema
//! // 4. Additional custom constraints (if any)
//! ```
//!
//! ### Performance Considerations
//!
//! 1. **Connection Pooling**: Reuse MCP connections across invocations
//! 2. **Timeout Configuration**: Set appropriate timeouts (5-30s typical)
//! 3. **Caching**: Cache tool metadata to avoid repeated discovery
//! 4. **Parallel Execution**: Multiple tools can run concurrently
//!
//! ### Best Practices
//!
//! 1. **Validate Early**: Use `validate_call()` before `invoke()`
//! 2. **Handle Timeouts**: Set reasonable timeouts for long-running tools
//! 3. **Log Tool Calls**: Track tool usage for debugging and cost monitoring
//! 4. **Error Recovery**: Implement retry logic for transient failures
//! 5. **Schema Versioning**: Version tool schemas for backward compatibility
//!
//! ## Common Pitfalls
//!
//! - Not validating tool calls before invocation (wasted resources)
//! - Missing required parameters in argument maps
//! - Not handling tool timeouts (blocked Paladin execution)
//! - Not checking `success` field in `ArmamentResult`
//! - Mixing JSON types (passing string when number expected)
//!
//! ## Related Modules
//!
//! - [`Armament`](paladin_core::platform::container::arsenal::Armament) - Tool metadata
//! - [`ArmamentCall`](paladin_core::platform::container::arsenal::ArmamentCall) - Tool invocation request
//! - [`ArmamentResult`](paladin_core::platform::container::arsenal::ArmamentResult) - Tool execution result
//! - [`ArsenalError`](paladin_core::platform::container::arsenal::ArsenalError) - Error types
//! - [`LlmPort`](crate::output::llm_port::LlmPort) - LLM integration (generates tool calls)
//!
//! ## See Also
//!
//! - [ARSENAL.md](https://github.com/DF3NDR/paladin-dev-env/blob/main/docs/ARSENAL.md) - Comprehensive Arsenal guide
//! - [MCP Specification](https://modelcontextprotocol.io) - Model Context Protocol details
//! - `examples/arsenal_stdio_tools.rs` - STDIO MCP example
//! - `examples/arsenal_sse_tools.rs` - SSE MCP example
use async_trait;
use ;
/// Port trait for executing external tools via the Arsenal system.
///
/// Provides the interface for tool invocation, validation, and discovery.
/// Implementations handle MCP protocol communication, tool execution,
/// timeout management, and result formatting.
///
/// # Capabilities
///
/// - **Tool Discovery**: List all available tools with [`list_armaments`](Self::list_armaments)
/// - **Tool Invocation**: Execute tools with validated parameters via [`invoke`](Self::invoke)
/// - **Call Validation**: Verify tool calls before execution with [`validate_call`](Self::validate_call)
///
/// # Thread Safety
///
/// All implementations must be `Send + Sync` to support:
/// - Concurrent tool invocations from multiple Paladins
/// - Async execution across thread boundaries
/// - Shared access to MCP connections and tool state
///
/// # Implementation Requirements
///
/// Implementations should:
/// 1. Validate tool calls before execution (required parameters, type checking)
/// 2. Handle tool timeouts gracefully (5-30s typical, configurable)
/// 3. Manage MCP connection lifecycle (connect, reconnect, cleanup)
/// 4. Return detailed error context for debugging
/// 5. Track execution metrics (time, success rate, errors)
///
/// # Examples
///
/// ## Tool Invocation with Validation
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalPort;
/// use paladin::core::platform::container::arsenal::ArmamentCall;
/// use std::collections::HashMap;
/// use serde_json::json;
///
/// async fn execute_calculator(
/// arsenal: &dyn ArsenalPort,
/// ) -> Result<(), Box<dyn std::error::Error>> {
/// let mut args = HashMap::new();
/// args.insert("operation".to_string(), json!("add"));
/// args.insert("x".to_string(), json!(10));
/// args.insert("y".to_string(), json!(5));
///
/// let call = ArmamentCall::new("calculator", args);
///
/// // Validate before invoking
/// arsenal.validate_call(&call)?;
///
/// // Execute tool
/// let result = arsenal.invoke(call).await?;
///
/// if result.success {
/// println!("Result: {:?}", result.output);
/// } else {
/// eprintln!("Tool failed: {:?}", result.error);
/// }
///
/// Ok(())
/// }
/// ```
///
/// ## Error Handling with Retry
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalPort;
/// use paladin::core::platform::container::arsenal::{ArmamentCall, ArsenalError};
///
/// async fn invoke_with_retry(
/// arsenal: &dyn ArsenalPort,
/// call: ArmamentCall,
/// max_retries: u32,
/// ) -> Result<String, ArsenalError> {
/// let mut attempts = 0;
///
/// loop {
/// match arsenal.invoke(call.clone()).await {
/// Ok(result) if result.success => {
/// return Ok(result.output.unwrap().to_string());
/// }
/// Ok(result) => {
/// return Err(ArsenalError::ProtocolError(
/// result.error.unwrap_or_else(|| "Unknown error".to_string())
/// ));
/// }
/// Err(ArsenalError::Timeout(_)) if attempts < max_retries => {
/// attempts += 1;
/// tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
/// continue;
/// }
/// Err(e) => return Err(e),
/// }
/// }
/// }
/// ```
///
/// ## Listing and Discovering Tools
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalPort;
///
/// async fn discover_tools(arsenal: &dyn ArsenalPort) {
/// let tools = arsenal.list_armaments().await;
///
/// println!("Available tools: {}", tools.len());
/// for tool in tools {
/// println!(" • {} - {}", tool.name, tool.description);
/// println!(" Required: {:?}", tool.required_params);
/// println!(" Schema: {}", tool.parameters);
/// }
/// }
/// ```
///
/// ## Custom Implementation Example
///
/// ```rust
/// use paladin::application::ports::output::arsenal_port::ArsenalPort;
/// use paladin::core::platform::container::arsenal::{
/// Armament, ArmamentCall, ArmamentResult, ArsenalError
/// };
/// use async_trait::async_trait;
/// use std::collections::HashMap;
/// use std::sync::{Arc, RwLock};
/// use serde_json::json;
///
/// struct MockArsenal {
/// tools: Arc<RwLock<HashMap<String, Armament>>>,
/// }
///
/// #[async_trait]
/// impl ArsenalPort for MockArsenal {
/// async fn list_armaments(&self) -> Vec<Armament> {
/// self.tools.read().unwrap().values().cloned().collect()
/// }
///
/// async fn invoke(&self, call: ArmamentCall) -> Result<ArmamentResult, ArsenalError> {
/// // Simulate tool execution
/// if !self.tools.read().unwrap().contains_key(&call.tool_name) {
/// return Err(ArsenalError::ToolNotFound(call.tool_name));
/// }
///
/// Ok(ArmamentResult::success(
/// call.call_id,
/// json!({"result": "mock success"}),
/// 100, // execution time ms
/// ))
/// }
///
/// fn validate_call(&self, call: &ArmamentCall) -> Result<(), ArsenalError> {
/// if !self.tools.read().unwrap().contains_key(&call.tool_name) {
/// return Err(ArsenalError::ToolNotFound(call.tool_name.clone()));
/// }
/// Ok(())
/// }
/// }
/// ```
///
/// # Implementation Notes
///
/// ## MCP Protocol Support
///
/// Implementations typically support multiple MCP transports:
///
/// - **STDIO**: Subprocess communication (Python, Node.js, CLI tools)
/// - **SSE**: HTTP streaming (web services, cloud APIs)
/// - **Direct**: Native Rust tool implementations
///
/// ```rust,ignore
/// // STDIO example
/// let stdio = MCPStdioAdapter::new("python3", vec!["mcp_server.py"]);
/// let arsenal = ArsenalExecutionService::new(stdio);
///
/// // SSE example
/// let sse = MCPSseAdapter::new("https://mcp.example.com");
/// let arsenal = ArsenalExecutionService::new(sse);
/// ```
///
/// ## Timeout Management
///
/// Tool execution should have configurable timeouts:
///
/// - **Short-running**: 5-10s (API calls, simple calculations)
/// - **Medium**: 10-30s (web scraping, data processing)
/// - **Long-running**: 30-120s (code generation, analysis)
///
/// ## Performance Optimization
///
/// 1. **Connection Pooling**: Reuse MCP connections
/// 2. **Parallel Execution**: Multiple tools can run concurrently
/// 3. **Caching**: Cache tool metadata from discovery
/// 4. **Lazy Loading**: Connect to MCP servers on first use
///
/// ## Error Recovery Strategies
///
/// - **Timeout**: Retry with increased timeout or fail fast
/// - **Transport Error**: Reconnect and retry once
/// - **Protocol Error**: Check MCP version compatibility
/// - **Tool Not Found**: Refresh tool registry from MCP server
///
/// # Common Pitfalls
///
/// - Not validating calls before invocation (wasted execution)
/// - Missing timeout configuration (hung Paladin execution)
/// - Not checking `success` field in result (silent failures)
/// - Blocking on synchronous tool execution (use async)
/// - Not handling MCP reconnection (fragile connections)
///
/// # See Also
///
/// - [`ArsenalRegistry`] - Tool registration and lifecycle management
/// - [`Armament`](paladin_core::platform::container::arsenal::Armament) - Tool metadata structure
/// - [`ArmamentCall`](paladin_core::platform::container::arsenal::ArmamentCall) - Invocation request
/// - [`ArmamentResult`](paladin_core::platform::container::arsenal::ArmamentResult) - Execution result
/// - [`ArsenalError`](paladin_core::platform::container::arsenal::ArsenalError) - Error types
/// Port trait for managing the Arsenal tool registry.
///
/// Provides the interface for registering, unregistering, and retrieving
/// tool metadata. Implementations handle tool storage, lifecycle management,
/// and thread-safe access to the tool collection.
///
/// # Capabilities
///
/// - **Registration**: Add tools to the registry with [`register`](Self::register)
/// - **Unregistration**: Remove tools by name with [`unregister`](Self::unregister)
/// - **Lookup**: Retrieve tool metadata with [`get`](Self::get)
///
/// # Thread Safety
///
/// All implementations must be `Send + Sync` to support:
/// - Concurrent registration from multiple sources
/// - Safe lookup from multiple Paladins
/// - MCP server discovery updates during runtime
///
/// # Implementation Requirements
///
/// Implementations should:
/// 1. Handle concurrent access safely (use Arc<RwLock<>> or similar)
/// 2. Support idempotent registration (replace existing tools)
/// 3. Return cloned tool metadata (avoid holding locks during I/O)
/// 4. Validate tool metadata on registration (non-empty names, valid schemas)
/// 5. Track registration history for debugging (optional)
///
/// # Examples
///
/// ## Tool Registration and Lookup
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalRegistry;
/// use paladin::core::platform::container::arsenal::Armament;
/// use serde_json::json;
///
/// async fn register_calculator(
/// registry: &dyn ArsenalRegistry,
/// ) -> Result<(), Box<dyn std::error::Error>> {
/// let calculator = Armament {
/// name: "calculator".to_string(),
/// description: "Performs arithmetic operations".to_string(),
/// parameters: json!({
/// "type": "object",
/// "properties": {
/// "operation": {"type": "string", "enum": ["add", "subtract"]},
/// "x": {"type": "number"},
/// "y": {"type": "number"}
/// }
/// }),
/// required_params: vec!["operation".to_string(), "x".to_string(), "y".to_string()],
/// };
///
/// registry.register(calculator).await;
///
/// // Verify registration
/// if let Some(tool) = registry.get("calculator").await {
/// println!("Registered: {} - {}", tool.name, tool.description);
/// }
///
/// Ok(())
/// }
/// ```
///
/// ## Batch Registration from MCP Discovery
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalRegistry;
/// use paladin::core::platform::container::arsenal::Armament;
///
/// async fn register_discovered_tools(
/// registry: &dyn ArsenalRegistry,
/// tools: Vec<Armament>,
/// ) {
/// println!("Registering {} tools from MCP discovery", tools.len());
///
/// for tool in tools {
/// println!(" • Registering: {}", tool.name);
/// registry.register(tool).await;
/// }
///
/// println!("Registration complete");
/// }
/// ```
///
/// ## Tool Lifecycle Management
///
/// ```rust,no_run
/// use paladin::application::ports::output::arsenal_port::ArsenalRegistry;
///
/// async fn replace_tool(
/// registry: &dyn ArsenalRegistry,
/// tool_name: &str,
/// new_tool: paladin::core::platform::container::arsenal::Armament,
/// ) {
/// // Unregister old version
/// if let Some(old) = registry.unregister(tool_name).await {
/// println!("Unregistered old version: {}", old.description);
/// }
///
/// // Register new version
/// registry.register(new_tool).await;
/// println!("Registered new version");
/// }
/// ```
///
/// ## Custom Implementation Example
///
/// ```rust
/// use paladin::application::ports::output::arsenal_port::ArsenalRegistry;
/// use paladin::core::platform::container::arsenal::Armament;
/// use async_trait::async_trait;
/// use std::collections::HashMap;
/// use std::sync::{Arc, RwLock};
///
/// struct InMemoryRegistry {
/// tools: Arc<RwLock<HashMap<String, Armament>>>,
/// }
///
/// impl InMemoryRegistry {
/// pub fn new() -> Self {
/// Self {
/// tools: Arc::new(RwLock::new(HashMap::new())),
/// }
/// }
/// }
///
/// #[async_trait]
/// impl ArsenalRegistry for InMemoryRegistry {
/// async fn register(&self, armament: Armament) {
/// let mut tools = self.tools.write().unwrap();
/// tools.insert(armament.name.clone(), armament);
/// }
///
/// async fn unregister(&self, name: &str) -> Option<Armament> {
/// let mut tools = self.tools.write().unwrap();
/// tools.remove(name)
/// }
///
/// async fn get(&self, name: &str) -> Option<Armament> {
/// let tools = self.tools.read().unwrap();
/// tools.get(name).cloned()
/// }
/// }
/// ```
///
/// # Implementation Notes
///
/// ## Storage Backend
///
/// Implementations can use different storage backends:
///
/// - **In-Memory**: `HashMap` with `Arc<RwLock<>>` (default, fast)
/// - **Persistent**: SQLite, PostgreSQL (survives restarts)
/// - **Distributed**: Redis, Consul (multi-instance deployments)
///
/// ```rust,ignore
/// // In-memory registry
/// let registry = InMemoryArsenalRegistry::new();
///
/// // Persistent registry
/// let registry = SqliteArsenalRegistry::new("arsenal.db").await?;
///
/// // Distributed registry
/// let registry = RedisArsenalRegistry::new("redis://localhost").await?;
/// ```
///
/// ## Concurrency Patterns
///
/// For thread-safe access:
///
/// ```rust,ignore
/// use std::sync::{Arc, RwLock};
/// use std::collections::HashMap;
///
/// // Multiple readers, single writer
/// let tools: Arc<RwLock<HashMap<String, Armament>>> = Arc::new(RwLock::new(HashMap::new()));
///
/// // Read (shared lock)
/// let tool = tools.read().unwrap().get("calculator").cloned();
///
/// // Write (exclusive lock)
/// tools.write().unwrap().insert("calculator".to_string(), tool);
/// ```
///
/// ## Tool Versioning Strategy
///
/// When replacing tools, consider versioning:
///
/// ```rust,ignore
/// // Option 1: Version in tool name
/// registry.register(Armament {
/// name: "calculator_v2".to_string(),
/// // ...
/// });
///
/// // Option 2: Metadata versioning
/// registry.register(Armament {
/// name: "calculator".to_string(),
/// description: "Calculator v2.0 - Supports complex numbers".to_string(),
/// // ...
/// });
/// ```
///
/// ## Best Practices
///
/// 1. **Idempotent Registration**: Allow re-registering the same tool
/// 2. **Clone on Return**: Don't expose internal storage directly
/// 3. **Validate on Register**: Check name, schema format before storing
/// 4. **Log Changes**: Track registration/unregistration for auditing
/// 5. **Support Bulk Operations**: Optimize for MCP batch discovery
///
/// ## Performance Considerations
///
/// - **Read-Heavy**: Optimize for fast lookups (RwLock, caching)
/// - **Write-Heavy**: Use channels for async registration queues
/// - **Large Registry**: Consider indexing by tags/categories
/// - **Distributed**: Cache locally, sync periodically
///
/// # Common Pitfalls
///
/// - Holding locks during async operations (deadlock risk)
/// - Not cloning on return (borrowing internal state)
/// - Missing validation on registration (corrupt registry)
/// - No cleanup on unregister (memory leaks if tools hold resources)
/// - Not handling concurrent replacement (lost updates)
///
/// # See Also
///
/// - [`ArsenalPort`] - Tool execution interface
/// - [`Armament`](paladin_core::platform::container::arsenal::Armament) - Tool metadata structure
/// - [ARSENAL.md](https://github.com/DF3NDR/paladin-dev-env/blob/main/docs/ARSENAL.md) - Comprehensive guide