paladin-ai 0.1.0

Enterprise AI orchestration framework with multi-agent coordination patterns
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
//! Arsenal command implementations for MCP tool management
//!
//! This module provides CLI commands for discovering and testing MCP
//! (Model Context Protocol) tools and servers.
//!
//! # MCP Protocol Support
//!
//! - **STDIO**: Command-line tools executed via stdin/stdout
//! - **SSE**: HTTP-based remote tool services
//!
//! # Examples
//!
//! ```bash
//! # List all configured MCP tools
//! paladin arsenal list
//!
//! # Test an STDIO MCP server
//! paladin arsenal test --mcp-stdio "uvx mcp-web-search"
//!
//! # Test an SSE MCP server
//! paladin arsenal test --mcp-sse "http://localhost:8080/mcp"
//! ```

use crate::application::cli::error::CliError;
use clap::Subcommand;
use colored::Colorize;

/// Arsenal subcommands for MCP tool management
#[derive(Debug, Subcommand)]
pub enum ArsenalCommands {
    /// List available MCP tools
    List,
    /// Test an MCP server connection
    Test(ArsenalTestArgs),
}

/// Arguments for testing MCP server connections
#[derive(Debug, clap::Args)]
pub struct ArsenalTestArgs {
    /// Test STDIO-based MCP server (e.g., "uvx mcp-web-search")
    #[arg(long, conflicts_with = "mcp_sse")]
    pub mcp_stdio: Option<String>,

    /// Test SSE-based MCP server (endpoint URL)
    #[arg(long, conflicts_with = "mcp_stdio")]
    pub mcp_sse: Option<String>,
}

/// Handle the arsenal commands
pub async fn handle_arsenal_command(command: ArsenalCommands) -> Result<(), CliError> {
    match command {
        ArsenalCommands::List => handle_arsenal_list().await,
        ArsenalCommands::Test(args) => handle_arsenal_test(args).await,
    }
}

/// List available MCP tools from configured servers
pub async fn handle_arsenal_list() -> Result<(), CliError> {
    use crate::config::Settings;

    println!("{} Discovering MCP tools...\n", "".cyan().bold());

    // Load configuration
    let config = Settings::new().map_err(|e| CliError::ValidationError {
        message: format!("Failed to load configuration: {}", e),
    })?;

    let arsenal_config = config
        .arsenal
        .as_ref()
        .ok_or_else(|| CliError::ValidationError {
            message: "Arsenal configuration not found".to_string(),
        })?;

    if arsenal_config.mcp_servers.is_empty() {
        println!("{} No MCP servers configured.", "".yellow().bold());
        println!("\nTo add MCP servers, edit your config.yml file:");
        println!("\narsenal:");
        println!("  mcp_servers:");
        println!("    - name: \"web_search\"");
        println!("      server_type: \"stdio\"");
        println!("      command: \"uvx\"");
        println!("      args: [\"mcp-web-search\"]");
        return Ok(());
    }

    println!(
        "{} Found {} configured MCP server(s)\n",
        "".green().bold(),
        arsenal_config.mcp_servers.len()
    );

    // Collect all discovered tools
    struct ToolEntry {
        name: String,
        description: String,
        server_name: String,
        server_type: String,
        status: String,
    }

    let mut all_tools: Vec<ToolEntry> = Vec::new();

    // Try to connect to each configured MCP server
    for server_config in &arsenal_config.mcp_servers {
        println!(
            "{} Connecting to '{}' ({})...",
            "".cyan(),
            server_config.name,
            server_config.server_type
        );

        match server_config.server_type.as_str() {
            "stdio" => {
                let command = server_config.command.as_ref().ok_or_else(|| {
                    CliError::MissingRequiredField {
                        field: "command".to_string(),
                        message: format!(
                            "MCP server '{}' is type 'stdio' but missing 'command' field",
                            server_config.name
                        ),
                    }
                })?;

                let args = server_config.args.as_ref().cloned().unwrap_or_default();

                // Try to connect and discover tools
                match connect_and_discover_stdio(command, args).await {
                    Ok(tools) => {
                        println!("  {} Discovered {} tool(s)", "".green(), tools.len());
                        for tool in tools {
                            all_tools.push(ToolEntry {
                                name: tool.name,
                                description: tool.description,
                                server_name: server_config.name.clone(),
                                server_type: server_config.server_type.clone(),
                                status: "connected".to_string(),
                            });
                        }
                    }
                    Err(e) => {
                        println!("  {} Connection failed: {}", "".red(), e);
                        all_tools.push(ToolEntry {
                            name: format!("<{}>", server_config.name),
                            description: format!("Connection failed: {}", e),
                            server_name: server_config.name.clone(),
                            server_type: server_config.server_type.clone(),
                            status: "failed".to_string(),
                        });
                    }
                }
            }
            "sse" => {
                println!("  {} SSE servers not yet implemented", "".yellow());
                all_tools.push(ToolEntry {
                    name: format!("<{}>", server_config.name),
                    description: "SSE servers not yet implemented".to_string(),
                    server_name: server_config.name.clone(),
                    server_type: server_config.server_type.clone(),
                    status: "unsupported".to_string(),
                });
            }
            unknown => {
                println!("  {} Unknown server type: {}", "".red(), unknown);
            }
        }
    }

    // Display results table
    if all_tools.is_empty() {
        println!("\n{} No tools discovered", "".yellow().bold());
        return Ok(());
    }

    println!("\n{}", "".repeat(120));
    println!(
        "{:30} | {:50} | {:10} | {:10} | {}",
        "Tool Name".bold(),
        "Description".bold(),
        "Server".bold(),
        "Type".bold(),
        "Status".bold()
    );
    println!("{}", "".repeat(120));

    for tool in &all_tools {
        let status_colored = match tool.status.as_str() {
            "connected" => tool.status.green(),
            "failed" => tool.status.red(),
            "unsupported" => tool.status.yellow(),
            _ => tool.status.white(),
        };

        // Truncate long descriptions
        let description = if tool.description.len() > 47 {
            format!("{}...", &tool.description[..47])
        } else {
            tool.description.clone()
        };

        println!(
            "{:30} | {:50} | {:10} | {:10} | {}",
            tool.name, description, tool.server_name, tool.server_type, status_colored
        );
    }

    println!("{}", "".repeat(120));
    println!(
        "\n{} {} tool(s) from {} server(s)",
        "".green().bold(),
        all_tools.iter().filter(|t| t.status == "connected").count(),
        arsenal_config.mcp_servers.len()
    );

    Ok(())
}

/// Connect to an MCP STDIO server and discover tools
async fn connect_and_discover_stdio(
    command: &str,
    args: Vec<String>,
) -> Result<Vec<crate::core::platform::container::arsenal::Armament>, String> {
    use crate::infrastructure::adapters::arsenal::mcp_protocol::MCPClient;
    use crate::infrastructure::adapters::arsenal::mcp_stdio_adapter::MCPStdioAdapter;

    // Create and connect STDIO adapter
    let mut adapter = MCPStdioAdapter::new(command, args);
    adapter
        .connect()
        .await
        .map_err(|e| format!("Connection failed: {}", e))?;

    // Create MCP client
    let client = MCPClient::new(Box::new(adapter));

    // Discover tools
    client
        .discover_tools()
        .await
        .map_err(|e| format!("Tool discovery failed: {}", e))
}

/// Test an MCP server connection with timing and diagnostics
async fn handle_arsenal_test(args: ArsenalTestArgs) -> Result<(), CliError> {
    use crate::infrastructure::adapters::arsenal::mcp_protocol::MCPClient;
    use crate::infrastructure::adapters::arsenal::mcp_stdio_adapter::MCPStdioAdapter;
    use std::time::Instant;

    // Validate mutually exclusive args
    if args.mcp_stdio.is_none() && args.mcp_sse.is_none() {
        return Err(CliError::MissingRequiredField {
            field: "mcp_stdio or mcp_sse".to_string(),
            message: "You must specify either --mcp-stdio or --mcp-sse".to_string(),
        });
    }

    println!("{} Testing MCP server connection...\n", "".cyan().bold());

    // Handle STDIO server testing
    if let Some(stdio_command) = args.mcp_stdio {
        println!("{} Server type: {}", "".cyan(), "STDIO".bold());
        println!("{} Command string: {}", "".cyan(), stdio_command.cyan());

        // Parse command and args
        let parts: Vec<&str> = stdio_command.split_whitespace().collect();
        if parts.is_empty() {
            return Err(CliError::InvalidFieldValue {
                field: "mcp_stdio".to_string(),
                message: "Command string cannot be empty".to_string(),
            });
        }

        let command = parts[0];
        let args_vec: Vec<String> = parts[1..].iter().map(|s| s.to_string()).collect();

        println!("{} Parsed command: {}", "".cyan(), command.yellow());
        if !args_vec.is_empty() {
            println!("{} Arguments: {}", "".cyan(), args_vec.join(" ").yellow());
        }

        println!("\n{} Connecting to MCP server...", "".cyan().bold());

        // Create adapter and measure connection time
        let start = Instant::now();
        let mut adapter = MCPStdioAdapter::new(command, args_vec);

        match adapter.connect().await {
            Ok(_) => {
                let connection_time = start.elapsed();
                println!(
                    "{} Connected successfully in {:.2}ms\n",
                    "".green().bold(),
                    connection_time.as_secs_f64() * 1000.0
                );

                // Create MCP client and discover tools
                println!("{} Discovering available tools...", "".cyan());
                let client = MCPClient::new(Box::new(adapter));

                let discovery_start = Instant::now();
                match client.discover_tools().await {
                    Ok(tools) => {
                        let discovery_time = discovery_start.elapsed();
                        println!(
                            "{} Discovered {} tool(s) in {:.2}ms\n",
                            "".green().bold(),
                            tools.len(),
                            discovery_time.as_secs_f64() * 1000.0
                        );

                        if tools.is_empty() {
                            println!(
                                "{} No tools available from this server",
                                "".yellow().bold()
                            );
                        } else {
                            // Display tools table
                            println!("{}", "".repeat(100));
                            println!("{:30} | {}", "Tool Name".bold(), "Description".bold());
                            println!("{}", "".repeat(100));

                            for tool in &tools {
                                let description = if tool.description.len() > 65 {
                                    format!("{}...", &tool.description[..65])
                                } else {
                                    tool.description.clone()
                                };
                                println!("{:30} | {}", tool.name.cyan(), description);
                            }

                            println!("{}", "".repeat(100));

                            // Show detailed schema for first tool as example
                            if let Some(first_tool) = tools.first() {
                                println!(
                                    "\n{} Example tool schema ({})",
                                    "".cyan().bold(),
                                    first_tool.name.cyan()
                                );
                                println!("{}", "".repeat(100));
                                let schema_json =
                                    serde_json::to_string_pretty(&first_tool.parameters)
                                        .unwrap_or_else(|_| {
                                            "Unable to serialize schema".to_string()
                                        });
                                println!("{}", schema_json.dimmed());
                                println!("{}", "".repeat(100));
                            }
                        }

                        // Display summary
                        println!("\n{}", "".repeat(100));
                        println!("{} Connection Test Summary", "📊".cyan().bold());
                        println!("{}", "".repeat(100));
                        println!(
                            "  {} Connection:  {}",
                            "".cyan(),
                            "Successful".green().bold()
                        );
                        println!(
                            "  {} Latency:     {:.2}ms",
                            "".cyan(),
                            connection_time.as_secs_f64() * 1000.0
                        );
                        println!(
                            "  {} Discovery:   {:.2}ms",
                            "".cyan(),
                            discovery_time.as_secs_f64() * 1000.0
                        );
                        println!(
                            "  {} Tools:       {}",
                            "".cyan(),
                            tools.len().to_string().yellow().bold()
                        );
                        println!("{}", "".repeat(100));

                        Ok(())
                    }
                    Err(e) => {
                        println!("{} Tool discovery failed: {}", "".red().bold(), e);

                        println!("\n{} Debugging Tips:", "💡".yellow().bold());
                        println!("  • Ensure the MCP server responds to 'tools/list' requests");
                        println!("  • Check server logs for protocol errors");
                        println!("  • Verify the server implements the MCP protocol correctly");

                        Err(CliError::ToolError {
                            message: format!("Tool discovery failed: {}", e),
                        })
                    }
                }
            }
            Err(e) => {
                let connection_time = start.elapsed();
                println!(
                    "{} Connection failed after {:.2}ms",
                    "".red().bold(),
                    connection_time.as_secs_f64() * 1000.0
                );
                println!("\n{} Error: {}", "".red(), e);

                println!("\n{} Debugging Tips:", "💡".yellow().bold());
                println!("  • Verify the command exists and is in your PATH");
                println!("  • Check that the command accepts STDIO communication");
                println!("  • Ensure the command implements the MCP protocol");
                println!(
                    "  • Try running the command manually to test: {}",
                    stdio_command.yellow()
                );

                Err(CliError::McpConnectionError {
                    message: format!("Connection failed: {}", e),
                })
            }
        }
    }
    // Handle SSE server testing
    else if let Some(sse_endpoint) = args.mcp_sse {
        println!("{} Server type: {}", "".cyan(), "SSE (HTTP)".bold());
        println!("{} Endpoint: {}", "".cyan(), sse_endpoint.cyan());

        println!(
            "\n{} SSE server support not yet implemented",
            "".yellow().bold()
        );
        println!("\n{} Debugging Tips:", "💡".yellow().bold());
        println!("  • SSE MCP servers will be supported in a future release");
        println!("  • Use --mcp-stdio for command-line MCP servers");

        Err(CliError::Other(
            "SSE server testing not yet implemented".to_string(),
        ))
    } else {
        unreachable!("Validation ensures at least one is Some")
    }
}

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

    #[test]
    fn test_arsenal_test_args_default_construction() {
        let args = ArsenalTestArgs {
            mcp_stdio: None,
            mcp_sse: None,
        };

        assert_eq!(args.mcp_stdio, None);
        assert_eq!(args.mcp_sse, None);
    }

    #[test]
    fn test_arsenal_test_args_mcp_stdio_option() {
        let args = ArsenalTestArgs {
            mcp_stdio: Some("uvx mcp-web-search".to_string()),
            mcp_sse: None,
        };

        assert_eq!(args.mcp_stdio, Some("uvx mcp-web-search".to_string()));
        assert_eq!(args.mcp_sse, None);
    }

    #[test]
    fn test_arsenal_test_args_mcp_sse_option() {
        let args = ArsenalTestArgs {
            mcp_stdio: None,
            mcp_sse: Some("http://localhost:8080/mcp".to_string()),
        };

        assert_eq!(args.mcp_stdio, None);
        assert_eq!(args.mcp_sse, Some("http://localhost:8080/mcp".to_string()));
    }

    #[test]
    fn test_arsenal_test_args_stdio_with_arguments() {
        let args = ArsenalTestArgs {
            mcp_stdio: Some("uvx mcp-web-search --verbose".to_string()),
            mcp_sse: None,
        };

        assert!(args.mcp_stdio.is_some());
        assert!(args.mcp_stdio.unwrap().contains("--verbose"));
    }

    #[test]
    fn test_arsenal_test_args_sse_with_full_url() {
        let args = ArsenalTestArgs {
            mcp_stdio: None,
            mcp_sse: Some("https://api.example.com/mcp/tools".to_string()),
        };

        assert!(args.mcp_sse.is_some());
        assert!(args.mcp_sse.unwrap().starts_with("https://"));
    }

    #[test]
    fn test_arsenal_test_args_mutual_exclusivity_at_runtime() {
        // Note: Clap enforces this at parse time with conflicts_with
        // This test verifies the data structure allows only one at a time
        let stdio_args = ArsenalTestArgs {
            mcp_stdio: Some("uvx mcp-web-search".to_string()),
            mcp_sse: None,
        };

        let sse_args = ArsenalTestArgs {
            mcp_stdio: None,
            mcp_sse: Some("http://localhost:8080/mcp".to_string()),
        };

        // Verify exactly one is set for each variant
        assert!(stdio_args.mcp_stdio.is_some() && stdio_args.mcp_sse.is_none());
        assert!(sse_args.mcp_stdio.is_none() && sse_args.mcp_sse.is_some());
    }

    #[test]
    fn test_arsenal_test_args_debug_format() {
        let args = ArsenalTestArgs {
            mcp_stdio: Some("uvx mcp-web-search".to_string()),
            mcp_sse: None,
        };

        let debug_str = format!("{:?}", args);
        assert!(debug_str.contains("ArsenalTestArgs"));
        assert!(debug_str.contains("mcp_stdio"));
    }

    #[test]
    fn test_arsenal_commands_variants_exist() {
        // Test List variant
        let list_command = ArsenalCommands::List;
        match list_command {
            ArsenalCommands::List => {} // Expected
            _ => panic!("Expected List variant"),
        }

        // Test Test variant
        let test_args = ArsenalTestArgs {
            mcp_stdio: Some("test".to_string()),
            mcp_sse: None,
        };
        let test_command = ArsenalCommands::Test(test_args);
        match test_command {
            ArsenalCommands::Test(_) => {} // Expected
            _ => panic!("Expected Test variant"),
        }
    }
}