rustf-cli 1.0.0

CLI tool for analyzing RustF projects with MCP server support for AI agents
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
// Uniform MCP endpoint interface for consistent response handling and parameter processing
use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value, Map};
use jsonrpc_core::{Params, Error as JsonRpcError};
use std::path::PathBuf;

/// Standard MCP response format
#[derive(Debug, Serialize, Deserialize)]
pub struct McpResponse {
    /// Status of the operation
    pub status: McpStatus,
    /// Optional error information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<McpError>,
    /// Response data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
    /// Optional metadata about the operation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<McpMetadata>,
}

/// MCP operation status
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum McpStatus {
    Success,
    Error,
    Pending,
    Warning,
}

/// MCP error information
#[derive(Debug, Serialize, Deserialize)]
pub struct McpError {
    /// Error code for programmatic handling
    pub code: String,
    /// Human-readable error message
    pub message: String,
    /// Optional detailed error information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<Value>,
}

/// MCP operation metadata
#[derive(Debug, Serialize, Deserialize)]
pub struct McpMetadata {
    /// Operation execution time in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_ms: Option<u64>,
    /// Project path used for the operation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub project_path: Option<String>,
    /// Database type (for database operations)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_type: Option<String>,
    /// Connection name used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection: Option<String>,
    /// Additional contextual information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<Map<String, Value>>,
}

// reserved: MCP response builders, paired with server tool dispatch (not all entry points wired yet)
#[allow(dead_code)]
impl McpResponse {
    /// Create a successful response with data
    pub fn success(data: Value) -> Self {
        Self {
            status: McpStatus::Success,
            error: None,
            data: Some(data),
            metadata: None,
        }
    }

    /// Create a successful response with data and metadata
    pub fn success_with_metadata(data: Value, metadata: McpMetadata) -> Self {
        Self {
            status: McpStatus::Success,
            error: None,
            data: Some(data),
            metadata: Some(metadata),
        }
    }

    /// Create an error response
    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            status: McpStatus::Error,
            error: Some(McpError {
                code: code.into(),
                message: message.into(),
                details: None,
            }),
            data: None,
            metadata: None,
        }
    }

    /// Create an error response with details
    pub fn error_with_details(
        code: impl Into<String>, 
        message: impl Into<String>, 
        details: Value
    ) -> Self {
        Self {
            status: McpStatus::Error,
            error: Some(McpError {
                code: code.into(),
                message: message.into(),
                details: Some(details),
            }),
            data: None,
            metadata: None,
        }
    }

    /// Create a pending response for async operations
    pub fn pending(message: impl Into<String>) -> Self {
        Self {
            status: McpStatus::Pending,
            error: None,
            data: Some(json!({"message": message.into()})),
            metadata: None,
        }
    }

    /// Create a warning response
    pub fn warning(message: impl Into<String>, data: Option<Value>) -> Self {
        Self {
            status: McpStatus::Warning,
            error: Some(McpError {
                code: "WARNING".to_string(),
                message: message.into(),
                details: None,
            }),
            data,
            metadata: None,
        }
    }

    /// Convert to JSON Value for JSON-RPC response
    pub fn to_json_value(self) -> Value {
        serde_json::to_value(self).unwrap_or_else(|_| {
            json!({
                "status": "error",
                "error": {
                    "code": "SERIALIZATION_ERROR",
                    "message": "Failed to serialize response"
                }
            })
        })
    }
}

/// Standard parameter extraction utilities
// reserved: JSON-RPC param extraction helpers for MCP tool handlers
#[allow(dead_code)]
pub struct McpParams;

// reserved: JSON-RPC param extraction helpers for MCP tool handlers
#[allow(dead_code)]
impl McpParams {
    /// Parse JSON-RPC parameters into a map
    pub fn parse(params: Params) -> Result<Map<String, Value>, JsonRpcError> {
        params.parse::<Map<String, Value>>()
            .map_err(|_| JsonRpcError::invalid_params("Invalid parameters format"))
    }

    /// Extract required string parameter
    pub fn get_required_string(
        params: &Map<String, Value>, 
        key: &str
    ) -> Result<String, JsonRpcError> {
        params
            .get(key)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .ok_or_else(|| JsonRpcError::invalid_params(&format!("Missing required parameter: {}", key)))
    }

    /// Extract optional string parameter
    pub fn get_optional_string(
        params: &Map<String, Value>, 
        key: &str
    ) -> Option<String> {
        params
            .get(key)
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
    }

    /// Extract optional boolean parameter
    pub fn get_optional_bool(
        params: &Map<String, Value>, 
        key: &str
    ) -> Option<bool> {
        params
            .get(key)
            .and_then(|v| v.as_bool())
    }

    /// Extract optional array of strings parameter
    pub fn get_optional_string_array(
        params: &Map<String, Value>, 
        key: &str
    ) -> Option<Vec<String>> {
        params
            .get(key)
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.to_string())
                    .collect()
            })
    }

    /// Extract project path with validation
    pub fn get_project_path(
        params: &Map<String, Value>
    ) -> Result<PathBuf, JsonRpcError> {
        let path_str = Self::get_optional_string(params, "project_path")
            .unwrap_or_else(|| std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string());
        
        let path = PathBuf::from(path_str);
        if !path.exists() {
            return Err(JsonRpcError::invalid_params("Project path does not exist"));
        }
        
        Ok(path)
    }
}

/// Execution context for MCP operations
// reserved: per-request MCP execution context, used to build response metadata
#[allow(dead_code)]
pub struct McpContext {
    pub project_path: PathBuf,
    pub start_time: std::time::Instant,
}

// reserved: per-request MCP execution context, used to build response metadata
#[allow(dead_code)]
impl McpContext {
    pub fn new(project_path: PathBuf) -> Self {
        Self {
            project_path,
            start_time: std::time::Instant::now(),
        }
    }

    /// Create metadata for the response
    pub fn create_metadata(&self) -> McpMetadata {
        McpMetadata {
            execution_time_ms: Some(self.start_time.elapsed().as_millis() as u64),
            project_path: Some(self.project_path.to_string_lossy().to_string()),
            database_type: None,
            connection: None,
            context: None,
        }
    }

    /// Create metadata with database information
    pub fn create_db_metadata(
        &self, 
        database_type: Option<String>, 
        connection: Option<String>
    ) -> McpMetadata {
        McpMetadata {
            execution_time_ms: Some(self.start_time.elapsed().as_millis() as u64),
            project_path: Some(self.project_path.to_string_lossy().to_string()),
            database_type,
            connection,
            context: None,
        }
    }
}

/// Trait for uniform MCP operation handlers
// reserved: uniform handler trait, implemented via impl_mcp_handler! macro for MCP tools
#[allow(dead_code)]
#[async_trait::async_trait]
pub trait McpHandler {
    /// The name of the MCP tool/method
    fn tool_name(&self) -> &'static str;
    
    /// Execute the MCP operation
    async fn execute(&self, params: Params) -> Result<Value, JsonRpcError>;
    
    /// Get tool description for MCP protocol
    fn description(&self) -> &'static str;
    
    /// Get parameter schema for the tool
    fn parameter_schema(&self) -> Value {
        json!({
            "type": "object",
            "properties": {},
            "required": []
        })
    }
}

/// Macro to implement standard MCP handler boilerplate
#[macro_export]
macro_rules! impl_mcp_handler {
    (
        $handler:ident,
        $tool_name:literal,
        $description:literal,
        $execute_fn:ident
    ) => {
        pub struct $handler;

        #[async_trait::async_trait]
        impl McpHandler for $handler {
            fn tool_name(&self) -> &'static str {
                $tool_name
            }

            async fn execute(&self, params: Params) -> Result<Value, JsonRpcError> {
                $execute_fn(params).await
            }

            fn description(&self) -> &'static str {
                $description
            }
        }
    };
}

/// Helper function to convert anyhow::Error to standardized MCP response
// reserved: error normalizer for MCP tool dispatch
#[allow(dead_code)]
pub fn error_to_mcp_response(error: anyhow::Error) -> Value {
    let error_msg = error.to_string();
    let error_code = if error_msg.contains("connection") {
        "CONNECTION_ERROR"
    } else if error_msg.contains("permission") || error_msg.contains("access") {
        "ACCESS_ERROR"
    } else if error_msg.contains("not found") || error_msg.contains("missing") {
        "NOT_FOUND"
    } else if error_msg.contains("invalid") {
        "INVALID_INPUT"
    } else if error_msg.contains("timeout") {
        "TIMEOUT_ERROR"
    } else {
        "INTERNAL_ERROR"
    };

    McpResponse::error(error_code, error_msg).to_json_value()
}

/// Helper function to convert Result to standardized MCP JSON-RPC response
// reserved: Result->JSON-RPC adapter for MCP tool dispatch
#[allow(dead_code)]
pub fn result_to_json_rpc<T>(
    result: Result<T>, 
    context: Option<McpContext>
) -> Result<Value, JsonRpcError>
where
    T: Serialize,
{
    match result {
        Ok(data) => {
            let json_data = serde_json::to_value(data)
                .map_err(|_| JsonRpcError::internal_error())?;
            
            let response = if let Some(ctx) = context {
                McpResponse::success_with_metadata(json_data, ctx.create_metadata())
            } else {
                McpResponse::success(json_data)
            };
            
            Ok(response.to_json_value())
        }
        Err(error) => {
            Ok(error_to_mcp_response(error))
        }
    }
}

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

    #[test]
    fn test_mcp_response_success() {
        let data = json!({"test": "value"});
        let response = McpResponse::success(data.clone());
        
        assert!(matches!(response.status, McpStatus::Success));
        assert_eq!(response.data, Some(data));
        assert!(response.error.is_none());
    }

    #[test]
    fn test_mcp_response_error() {
        let response = McpResponse::error("TEST_ERROR", "Test error message");
        
        assert!(matches!(response.status, McpStatus::Error));
        assert!(response.data.is_none());
        assert!(response.error.is_some());
        
        let error = response.error.unwrap();
        assert_eq!(error.code, "TEST_ERROR");
        assert_eq!(error.message, "Test error message");
    }

    #[test]
    fn test_mcp_params_extraction() {
        let mut params_map = Map::new();
        params_map.insert("test_string".to_string(), json!("test_value"));
        params_map.insert("test_bool".to_string(), json!(true));
        params_map.insert("test_array".to_string(), json!(["item1", "item2"]));

        assert_eq!(
            McpParams::get_optional_string(&params_map, "test_string"),
            Some("test_value".to_string())
        );

        assert_eq!(
            McpParams::get_optional_bool(&params_map, "test_bool"),
            Some(true)
        );

        assert_eq!(
            McpParams::get_optional_string_array(&params_map, "test_array"),
            Some(vec!["item1".to_string(), "item2".to_string()])
        );
    }
}