mcp-tools 0.1.0

Rust MCP tools library
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
//! CLI MCP Client
//!
//! Command-line interface for interacting with MCP servers
//! Provides interactive and batch modes for testing and automation

use async_trait::async_trait;
use clap::{Parser, Subcommand};
use serde_json::Value;
use std::collections::HashMap;
use std::io::{self, Write};
use tracing::{debug, error, info, warn};

use crate::common::{
    BaseClient, ClientConfig, ConnectionStatus, McpClientBase, McpToolRequest, McpToolResponse,
    ServerCapabilities,
};
use crate::{McpToolsError, Result};

/// CLI arguments for the MCP client
#[derive(Parser)]
#[command(name = "mcp-cli")]
#[command(about = "MCP Tools CLI Client")]
#[command(version = "1.0")]
pub struct CliArgs {
    /// Server URL to connect to
    #[arg(short, long, default_value = "http://localhost:8080")]
    pub server: String,

    /// Connection timeout in seconds
    #[arg(short, long, default_value = "30")]
    pub timeout: u64,

    /// Enable verbose logging
    #[arg(short, long)]
    pub verbose: bool,

    /// Output format (json, yaml, table)
    #[arg(short, long, default_value = "table")]
    pub format: String,

    /// Command to execute
    #[command(subcommand)]
    pub command: Option<CliCommand>,
}

/// CLI commands
#[derive(Subcommand, Clone)]
pub enum CliCommand {
    /// Connect to MCP server and show capabilities
    Connect,

    /// List available tools
    ListTools,

    /// Execute a tool
    Execute {
        /// Tool name to execute
        tool: String,

        /// Tool arguments as JSON string
        #[arg(short, long)]
        args: Option<String>,

        /// Tool arguments as key=value pairs
        #[arg(short = 'p', long = "param")]
        params: Vec<String>,
    },

    /// Interactive mode
    Interactive,

    /// Show server status
    Status,

    /// Disconnect from server
    Disconnect,
}

/// CLI MCP Client
pub struct CliClient {
    base: BaseClient,
    args: CliArgs,
}

impl CliClient {
    pub fn new(config: ClientConfig, args: CliArgs) -> Self {
        let base = BaseClient::new(config);
        Self { base, args }
    }

    /// Run the CLI client
    pub async fn run(&mut self) -> Result<()> {
        // Initialize logging
        if self.args.verbose {
            tracing_subscriber::fmt().with_env_filter("debug").init();
        } else {
            tracing_subscriber::fmt().with_env_filter("info").init();
        }

        info!("Starting MCP CLI Client");

        // Execute command or enter interactive mode
        match self.args.command.clone() {
            Some(command) => self.execute_command(command).await,
            None => self.interactive_mode().await,
        }
    }

    /// Execute a specific command
    async fn execute_command(&mut self, command: CliCommand) -> Result<()> {
        match command {
            CliCommand::Connect => {
                println!("Connecting to MCP server at {}...", self.args.server);
                self.connect().await?;
                let capabilities = self.get_server_capabilities().await?;
                self.print_capabilities(&capabilities);
                Ok(())
            }
            CliCommand::ListTools => {
                self.connect().await?;
                let capabilities = self.get_server_capabilities().await?;
                self.print_tools(&capabilities);
                Ok(())
            }
            CliCommand::Execute { tool, args, params } => {
                self.connect().await?;
                let arguments = self.parse_arguments(args.as_deref(), &params)?;
                let request = McpToolRequest {
                    id: uuid::Uuid::new_v4(),
                    tool: tool.clone(),
                    arguments: serde_json::to_value(arguments)?,
                    session_id: uuid::Uuid::new_v4().to_string(),
                    metadata: HashMap::new(),
                };
                let response = self.execute_tool(request).await?;
                self.print_response(&response);
                Ok(())
            }
            CliCommand::Interactive => self.interactive_mode().await,
            CliCommand::Status => {
                let status = self.get_status().await?;
                self.print_status(&status);
                Ok(())
            }
            CliCommand::Disconnect => {
                self.disconnect().await?;
                println!("Disconnected from MCP server");
                Ok(())
            }
        }
    }

    /// Enter interactive mode
    async fn interactive_mode(&mut self) -> Result<()> {
        println!("MCP Tools CLI - Interactive Mode");
        println!("Type 'help' for available commands, 'quit' to exit");

        // Connect to server
        print!("Connecting to {}... ", self.args.server);
        io::stdout().flush().unwrap();
        self.connect().await?;
        println!("Connected!");

        // Get capabilities
        let capabilities = self.get_server_capabilities().await?;
        println!(
            "Server capabilities loaded. {} tools available.",
            capabilities.tools.len()
        );

        loop {
            print!("mcp> ");
            io::stdout().flush().unwrap();

            let mut input = String::new();
            match io::stdin().read_line(&mut input) {
                Ok(_) => {
                    let input = input.trim();
                    if input.is_empty() {
                        continue;
                    }

                    match self.handle_interactive_command(input, &capabilities).await {
                        Ok(should_continue) => {
                            if !should_continue {
                                break;
                            }
                        }
                        Err(e) => {
                            eprintln!("Error: {}", e);
                        }
                    }
                }
                Err(e) => {
                    eprintln!("Error reading input: {}", e);
                    break;
                }
            }
        }

        self.disconnect().await?;
        println!("Goodbye!");
        Ok(())
    }

    /// Handle interactive command
    async fn handle_interactive_command(
        &mut self,
        input: &str,
        capabilities: &ServerCapabilities,
    ) -> Result<bool> {
        let parts: Vec<&str> = input.split_whitespace().collect();
        if parts.is_empty() {
            return Ok(true);
        }

        match parts[0] {
            "help" => {
                self.print_help();
                Ok(true)
            }
            "quit" | "exit" => Ok(false),
            "tools" | "list" => {
                self.print_tools(capabilities);
                Ok(true)
            }
            "status" => {
                let status = self.get_status().await?;
                self.print_status(&status);
                Ok(true)
            }
            "capabilities" => {
                self.print_capabilities(capabilities);
                Ok(true)
            }
            tool_name => {
                // Try to execute as a tool
                if capabilities.tools.iter().any(|t| t.name == tool_name) {
                    // Parse arguments from remaining parts
                    let mut arguments = HashMap::new();
                    for part in &parts[1..] {
                        if let Some((key, value)) = part.split_once('=') {
                            arguments.insert(key.to_string(), Value::String(value.to_string()));
                        }
                    }

                    let request = McpToolRequest {
                        id: uuid::Uuid::new_v4(),
                        tool: tool_name.to_string(),
                        arguments: serde_json::to_value(arguments)?,
                        session_id: uuid::Uuid::new_v4().to_string(),
                        metadata: HashMap::new(),
                    };

                    let response = self.execute_tool(request).await?;
                    self.print_response(&response);
                } else {
                    println!(
                        "Unknown command or tool: {}. Type 'help' for available commands.",
                        tool_name
                    );
                }
                Ok(true)
            }
        }
    }

    /// Parse arguments from JSON string or key=value pairs
    fn parse_arguments(
        &self,
        json_args: Option<&str>,
        params: &[String],
    ) -> Result<HashMap<String, Value>> {
        let mut arguments = HashMap::new();

        // Parse JSON arguments if provided
        if let Some(json_str) = json_args {
            let json_value: Value = serde_json::from_str(json_str)
                .map_err(|e| McpToolsError::Server(format!("Invalid JSON arguments: {}", e)))?;

            if let Value::Object(obj) = json_value {
                for (key, value) in obj {
                    arguments.insert(key, value);
                }
            }
        }

        // Parse key=value parameters
        for param in params {
            if let Some((key, value)) = param.split_once('=') {
                arguments.insert(key.to_string(), Value::String(value.to_string()));
            } else {
                return Err(McpToolsError::Server(format!(
                    "Invalid parameter format: {}. Use key=value",
                    param
                )));
            }
        }

        Ok(arguments)
    }

    /// Print help information
    fn print_help(&self) {
        println!("Available commands:");
        println!("  help                    - Show this help message");
        println!("  tools, list             - List available tools");
        println!("  status                  - Show connection status");
        println!("  capabilities            - Show server capabilities");
        println!("  <tool_name> key=value   - Execute a tool with parameters");
        println!("  quit, exit              - Exit interactive mode");
        println!();
        println!("Examples:");
        println!("  git_status repo_path=/path/to/repo");
        println!("  http_request url=https://api.example.com method=GET");
        println!("  analyze_code file_path=main.rs language=rust");
    }

    /// Print server capabilities
    fn print_capabilities(&self, capabilities: &ServerCapabilities) {
        match self.args.format.as_str() {
            "json" => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(capabilities).unwrap_or_default()
                );
            }
            "yaml" => {
                // Would need serde_yaml dependency
                println!("YAML format not implemented");
            }
            _ => {
                println!("Server Capabilities:");
                println!("  Protocol Version: {}", capabilities.info.protocol_version);
                println!("  Server Name: {}", capabilities.info.name);
                println!("  Server Version: {}", capabilities.info.version);
                println!("  Tools Available: {}", capabilities.tools.len());

                if !capabilities.tools.is_empty() {
                    println!("\nTools:");
                    for tool in &capabilities.tools {
                        println!("  - {} ({})", tool.name, tool.category);
                        println!("    Description: {}", tool.description);
                        if tool.requires_permission {
                            println!("    Permissions: {:?}", tool.permissions);
                        }
                    }
                }
            }
        }
    }

    /// Print available tools
    fn print_tools(&self, capabilities: &ServerCapabilities) {
        match self.args.format.as_str() {
            "json" => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(&capabilities.tools).unwrap_or_default()
                );
            }
            _ => {
                println!("Available Tools ({}):", capabilities.tools.len());
                println!("{:<20} {:<15} {}", "Name", "Category", "Description");
                println!("{}", "-".repeat(80));

                for tool in &capabilities.tools {
                    println!(
                        "{:<20} {:<15} {}",
                        tool.name,
                        tool.category,
                        if tool.description.len() > 40 {
                            format!("{}...", &tool.description[..37])
                        } else {
                            tool.description.clone()
                        }
                    );
                }
            }
        }
    }

    /// Print tool response
    fn print_response(&self, response: &McpToolResponse) {
        match self.args.format.as_str() {
            "json" => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(response).unwrap_or_default()
                );
            }
            _ => {
                if response.is_error {
                    println!(
                        "Error: {}",
                        response.error.as_deref().unwrap_or("Unknown error")
                    );
                } else {
                    println!("Tool Response (ID: {}):", response.id);
                    for content in &response.content {
                        match content {
                            crate::common::McpContent::Text { text } => {
                                println!("{}", text);
                            }
                            crate::common::McpContent::Image { data, mime_type } => {
                                println!("Image: {} bytes ({})", data.len(), mime_type);
                            }
                            crate::common::McpContent::Resource {
                                uri,
                                mime_type,
                                text,
                            } => {
                                println!(
                                    "Resource: {} ({})",
                                    uri,
                                    mime_type.as_deref().unwrap_or("unknown")
                                );
                                if let Some(text) = text {
                                    println!("{}", text);
                                }
                            }
                        }
                    }

                    if !response.metadata.is_empty() {
                        println!("\nMetadata:");
                        for (key, value) in &response.metadata {
                            println!("  {}: {}", key, value);
                        }
                    }
                }
            }
        }
    }

    /// Print connection status
    fn print_status(&self, status: &ConnectionStatus) {
        match self.args.format.as_str() {
            "json" => {
                println!(
                    "{}",
                    serde_json::to_string_pretty(status).unwrap_or_default()
                );
            }
            _ => {
                println!("Connection Status:");
                match status {
                    ConnectionStatus::Disconnected => println!("  Status: Disconnected"),
                    ConnectionStatus::Connecting => println!("  Status: Connecting"),
                    ConnectionStatus::Connected => println!("  Status: Connected"),
                    ConnectionStatus::Error(error) => println!("  Status: Error - {}", error),
                }
            }
        }
    }
}

#[async_trait]
impl McpClientBase for CliClient {
    async fn connect(&mut self) -> Result<()> {
        debug!("Connecting to MCP server");
        self.base.connect().await
    }

    async fn disconnect(&mut self) -> Result<()> {
        debug!("Disconnecting from MCP server");
        self.base.disconnect().await
    }

    async fn get_server_capabilities(&self) -> Result<ServerCapabilities> {
        debug!("Getting server capabilities");
        self.base.get_server_capabilities().await
    }

    async fn execute_tool(&self, request: McpToolRequest) -> Result<McpToolResponse> {
        debug!("Executing tool: {}", request.tool);
        self.base.execute_tool(request).await
    }

    async fn get_status(&self) -> Result<ConnectionStatus> {
        debug!("Getting connection status");
        self.base.get_status().await
    }
}