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
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
//! Code Analysis MCP Server
//!
//! Provides comprehensive code analysis via MCP protocol including:
//! - Syntax tree parsing with tree-sitter
//! - Complexity analysis and metrics
//! - Code quality assessment
//! - Security vulnerability detection
//! - Dependency analysis

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tracing::{debug, info, warn};
use tree_sitter::{Node, Parser, Query, QueryCursor, Tree};

use crate::common::{
    BaseServer, McpContent, McpServerBase, McpTool, McpToolRequest, McpToolResponse,
    ServerCapabilities, ServerConfig,
};
use crate::{McpToolsError, Result};

/// Code Analysis MCP Server
pub struct CodeAnalysisServer {
    base: BaseServer,
}

/// Complexity analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplexityAnalysis {
    pub cyclomatic_complexity: u32,
    pub cognitive_complexity: u32,
    pub lines_of_code: u32,
    pub functions: u32,
    pub classes: u32,
    pub nested_depth: u32,
}

/// Code quality metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityMetrics {
    pub maintainability_index: f64,
    pub documentation_ratio: f64,
    pub test_coverage: f64,
    pub code_duplication: f64,
    pub technical_debt: f64,
}

/// Security analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityAnalysis {
    pub vulnerabilities: Vec<SecurityVulnerability>,
    pub risk_score: u32,
    pub security_hotspots: Vec<String>,
}

/// Security vulnerability
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityVulnerability {
    pub severity: String,
    pub category: String,
    pub description: String,
    pub line: u32,
    pub recommendation: String,
}

/// Dependency analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DependencyAnalysis {
    pub imports: Vec<String>,
    pub external_dependencies: Vec<String>,
    pub internal_dependencies: Vec<String>,
    pub circular_dependencies: Vec<String>,
    pub unused_imports: Vec<String>,
}

/// Complete code analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeAnalysisResult {
    pub language: String,
    pub file_path: String,
    pub complexity: ComplexityAnalysis,
    pub quality: QualityMetrics,
    pub security: SecurityAnalysis,
    pub dependencies: DependencyAnalysis,
    pub suggestions: Vec<String>,
}

impl CodeAnalysisServer {
    pub async fn new(config: ServerConfig) -> Result<Self> {
        let base = BaseServer::new(config).await?;
        Ok(Self { base })
    }

    /// Detect programming language from file path and content
    fn detect_language(&self, file_path: &str, content: &str) -> String {
        // First try to detect by file extension
        if let Some(extension) = std::path::Path::new(file_path).extension() {
            match extension.to_str() {
                Some("rs") => return "rust".to_string(),
                Some("py") => return "python".to_string(),
                Some("js") => return "javascript".to_string(),
                Some("ts") => return "typescript".to_string(),
                Some("go") => return "go".to_string(),
                Some("java") => return "java".to_string(),
                Some("c") => return "c".to_string(),
                Some("cpp") | Some("cc") | Some("cxx") => return "cpp".to_string(),
                _ => {}
            }
        }

        // Fallback to content-based detection
        if content.contains("fn main()") || content.contains("use std::") {
            "rust".to_string()
        } else if content.contains("def ") || content.contains("import ") {
            "python".to_string()
        } else if content.contains("function ") || content.contains("const ") {
            "javascript".to_string()
        } else if content.contains("package main") || content.contains("func ") {
            "go".to_string()
        } else if content.contains("public class") || content.contains("import java") {
            "java".to_string()
        } else {
            "unknown".to_string()
        }
    }

    /// Analyze code complexity
    async fn analyze_complexity(
        &self,
        file_path: &str,
        content: &str,
    ) -> Result<ComplexityAnalysis> {
        let language = self.detect_language(file_path, content);

        // Create parser for the detected language
        let mut parser = Parser::new();
        let tree_sitter_language = match language.as_str() {
            "rust" => tree_sitter_rust::language(),
            "python" => tree_sitter_python::language(),
            "javascript" => tree_sitter_javascript::language(),
            "typescript" => tree_sitter_typescript::language_typescript(),
            "go" => tree_sitter_go::language(),
            "java" => tree_sitter_java::language(),
            "c" => tree_sitter_c::language(),
            "cpp" => tree_sitter_cpp::language(),
            _ => {
                // Return basic metrics for unsupported languages
                return Ok(ComplexityAnalysis {
                    cyclomatic_complexity: 1,
                    cognitive_complexity: 1,
                    lines_of_code: content.lines().count() as u32,
                    functions: 0,
                    classes: 0,
                    nested_depth: 0,
                });
            }
        };

        parser
            .set_language(tree_sitter_language)
            .map_err(|e| McpToolsError::Server(format!("Failed to set language: {}", e)))?;

        // Parse the code
        let tree = parser
            .parse(content, None)
            .ok_or_else(|| McpToolsError::Server("Failed to parse code".to_string()))?;

        // Analyze the syntax tree
        let root_node = tree.root_node();
        let mut complexity = ComplexityAnalysis {
            cyclomatic_complexity: 1, // Base complexity
            cognitive_complexity: 0,
            lines_of_code: content.lines().count() as u32,
            functions: 0,
            classes: 0,
            nested_depth: 0,
        };

        self.traverse_node(&root_node, &mut complexity, 0);

        Ok(complexity)
    }

    /// Traverse syntax tree node and calculate complexity
    fn traverse_node(&self, node: &Node, complexity: &mut ComplexityAnalysis, depth: u32) {
        complexity.nested_depth = complexity.nested_depth.max(depth);

        match node.kind() {
            // Function definitions
            "function_item"
            | "function_declaration"
            | "function_definition"
            | "method_declaration" => {
                complexity.functions += 1;
                complexity.cyclomatic_complexity += 1;
            }
            // Class definitions
            "struct_item" | "impl_item" | "class_declaration" | "class_specifier" => {
                complexity.classes += 1;
            }
            // Control flow statements that increase complexity
            "if_expression" | "if_statement" | "match_expression" | "while_statement"
            | "for_statement" | "loop_expression" | "try_statement" => {
                complexity.cyclomatic_complexity += 1;
                complexity.cognitive_complexity += 1;
            }
            // Logical operators
            "binary_expression" => {
                if let Some(operator) = node.child_by_field_name("operator") {
                    if matches!(operator.kind(), "&&" | "||" | "and" | "or") {
                        complexity.cyclomatic_complexity += 1;
                    }
                }
            }
            _ => {}
        }

        // Recursively traverse child nodes
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.traverse_node(&child, complexity, depth + 1);
            }
        }
    }

    /// Analyze code quality metrics
    async fn analyze_quality(&self, content: &str) -> QualityMetrics {
        let lines = content.lines().collect::<Vec<_>>();
        let total_lines = lines.len() as f64;

        // Count comment lines for documentation ratio
        let comment_lines = lines
            .iter()
            .filter(|line| {
                let trimmed = line.trim();
                trimmed.starts_with("//")
                    || trimmed.starts_with("#")
                    || trimmed.starts_with("/*")
                    || trimmed.starts_with("*")
                    || trimmed.starts_with("\"\"\"")
                    || trimmed.starts_with("'''")
            })
            .count() as f64;

        let documentation_ratio = if total_lines > 0.0 {
            (comment_lines / total_lines) * 100.0
        } else {
            0.0
        };

        // Basic maintainability index calculation (simplified)
        let maintainability_index = 100.0 - (documentation_ratio * 0.1).max(0.0).min(100.0);

        QualityMetrics {
            maintainability_index,
            documentation_ratio,
            test_coverage: 0.0,    // Would need test file analysis
            code_duplication: 0.0, // Would need more sophisticated analysis
            technical_debt: 0.0,   // Would need more sophisticated analysis
        }
    }

    /// Analyze security vulnerabilities (simplified)
    async fn analyze_security(&self, content: &str, language: &str) -> SecurityAnalysis {
        let mut vulnerabilities = Vec::new();
        let lines: Vec<&str> = content.lines().collect();

        // Basic security pattern detection
        for (line_num, line) in lines.iter().enumerate() {
            let line_lower = line.to_lowercase();

            // SQL injection patterns
            if line_lower.contains("select")
                && line_lower.contains("where")
                && line_lower.contains("+")
            {
                vulnerabilities.push(SecurityVulnerability {
                    severity: "High".to_string(),
                    category: "SQL Injection".to_string(),
                    description: "Potential SQL injection vulnerability".to_string(),
                    line: (line_num + 1) as u32,
                    recommendation: "Use parameterized queries".to_string(),
                });
            }

            // Hardcoded credentials
            if line_lower.contains("password")
                && (line_lower.contains("=") || line_lower.contains(":"))
            {
                vulnerabilities.push(SecurityVulnerability {
                    severity: "Medium".to_string(),
                    category: "Hardcoded Credentials".to_string(),
                    description: "Potential hardcoded password".to_string(),
                    line: (line_num + 1) as u32,
                    recommendation: "Use environment variables or secure storage".to_string(),
                });
            }

            // Unsafe operations (language-specific)
            match language {
                "rust" => {
                    if line.contains("unsafe") {
                        vulnerabilities.push(SecurityVulnerability {
                            severity: "Medium".to_string(),
                            category: "Unsafe Code".to_string(),
                            description: "Unsafe Rust code block".to_string(),
                            line: (line_num + 1) as u32,
                            recommendation: "Review unsafe code for memory safety".to_string(),
                        });
                    }
                }
                "c" | "cpp" => {
                    if line.contains("strcpy") || line.contains("sprintf") {
                        vulnerabilities.push(SecurityVulnerability {
                            severity: "High".to_string(),
                            category: "Buffer Overflow".to_string(),
                            description: "Unsafe string function".to_string(),
                            line: (line_num + 1) as u32,
                            recommendation: "Use safe string functions like strncpy or snprintf"
                                .to_string(),
                        });
                    }
                }
                _ => {}
            }
        }

        let risk_score = vulnerabilities
            .iter()
            .map(|v| match v.severity.as_str() {
                "High" => 30,
                "Medium" => 15,
                "Low" => 5,
                _ => 0,
            })
            .sum::<u32>()
            .min(100);

        SecurityAnalysis {
            vulnerabilities,
            risk_score,
            security_hotspots: vec![], // Would need more sophisticated analysis
        }
    }

    /// Analyze dependencies (simplified)
    async fn analyze_dependencies(&self, content: &str, language: &str) -> DependencyAnalysis {
        let lines: Vec<&str> = content.lines().collect();
        let mut imports = Vec::new();
        let mut external_dependencies = Vec::new();
        let mut internal_dependencies = Vec::new();

        for line in lines {
            let trimmed = line.trim();

            match language {
                "rust" => {
                    if trimmed.starts_with("use ") {
                        let import = trimmed
                            .strip_prefix("use ")
                            .unwrap_or("")
                            .split(';')
                            .next()
                            .unwrap_or("")
                            .trim();
                        imports.push(import.to_string());

                        if import.starts_with("std::") || import.starts_with("core::") {
                            // Standard library
                        } else if import.starts_with("crate::")
                            || import.starts_with("super::")
                            || import.starts_with("self::")
                        {
                            internal_dependencies.push(import.to_string());
                        } else {
                            external_dependencies.push(import.to_string());
                        }
                    }
                }
                "python" => {
                    if trimmed.starts_with("import ") || trimmed.starts_with("from ") {
                        imports.push(trimmed.to_string());
                        // Would need more sophisticated analysis for internal vs external
                    }
                }
                "javascript" | "typescript" => {
                    if trimmed.starts_with("import ") || trimmed.contains("require(") {
                        imports.push(trimmed.to_string());
                        // Would need more sophisticated analysis for internal vs external
                    }
                }
                _ => {}
            }
        }

        DependencyAnalysis {
            imports,
            external_dependencies,
            internal_dependencies,
            circular_dependencies: Vec::new(), // Would need graph analysis
            unused_imports: Vec::new(),        // Would need usage analysis
        }
    }
}

#[async_trait]
impl McpServerBase for CodeAnalysisServer {
    async fn get_capabilities(&self) -> Result<ServerCapabilities> {
        let mut capabilities = self.base.get_capabilities().await?;

        // Add Code Analysis-specific tools
        let analysis_tools = vec![
            McpTool {
                name: "analyze_code".to_string(),
                description: "Perform comprehensive code analysis including complexity, quality, security, and dependencies".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the code file to analyze"
                        },
                        "content": {
                            "type": "string",
                            "description": "Code content to analyze (alternative to file_path)"
                        },
                        "language": {
                            "type": "string",
                            "description": "Programming language (optional, auto-detected if not provided)"
                        },
                        "analysis_type": {
                            "type": "string",
                            "description": "Type of analysis: 'complexity', 'quality', 'security', 'dependencies', or 'comprehensive'",
                            "enum": ["complexity", "quality", "security", "dependencies", "comprehensive"]
                        }
                    },
                    "required": ["file_path"],
                    "oneOf": [
                        {"required": ["file_path"]},
                        {"required": ["content"]}
                    ]
                }),
                category: "code-analysis".to_string(),
                requires_permission: false,
                permissions: vec![],
            },
            McpTool {
                name: "detect_language".to_string(),
                description: "Detect programming language from file path or content".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the file"
                        },
                        "content": {
                            "type": "string",
                            "description": "Code content to analyze"
                        }
                    },
                    "oneOf": [
                        {"required": ["file_path"]},
                        {"required": ["content"]}
                    ]
                }),
                category: "code-analysis".to_string(),
                requires_permission: false,
                permissions: vec![],
            },
            McpTool {
                name: "complexity_analysis".to_string(),
                description: "Analyze code complexity metrics including cyclomatic complexity and nesting depth".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the code file"
                        },
                        "content": {
                            "type": "string",
                            "description": "Code content to analyze"
                        },
                        "language": {
                            "type": "string",
                            "description": "Programming language (optional)"
                        }
                    },
                    "oneOf": [
                        {"required": ["file_path"]},
                        {"required": ["content"]}
                    ]
                }),
                category: "code-analysis".to_string(),
                requires_permission: false,
                permissions: vec![],
            },
            McpTool {
                name: "security_analysis".to_string(),
                description: "Analyze code for security vulnerabilities and risks".to_string(),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {
                        "file_path": {
                            "type": "string",
                            "description": "Path to the code file"
                        },
                        "content": {
                            "type": "string",
                            "description": "Code content to analyze"
                        },
                        "language": {
                            "type": "string",
                            "description": "Programming language (optional)"
                        }
                    },
                    "oneOf": [
                        {"required": ["file_path"]},
                        {"required": ["content"]}
                    ]
                }),
                category: "code-analysis".to_string(),
                requires_permission: false,
                permissions: vec![],
            },
        ];

        capabilities.tools = analysis_tools;
        Ok(capabilities)
    }

    async fn handle_tool_request(&self, request: McpToolRequest) -> Result<McpToolResponse> {
        info!("Handling Code Analysis tool request: {}", request.tool);

        // Get file path or content
        let file_path = request
            .arguments
            .get("file_path")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown");

        let content = if let Some(content_value) = request.arguments.get("content") {
            content_value.as_str().unwrap_or("").to_string()
        } else if file_path != "unknown" {
            // In a real implementation, we would read the file
            // For now, return an error asking for content
            return Ok(McpToolResponse {
                id: request.id,
                content: vec![McpContent::text(
                    "File reading not implemented. Please provide 'content' parameter.".to_string(),
                )],
                is_error: true,
                error: Some("File reading not implemented".to_string()),
                metadata: HashMap::new(),
            });
        } else {
            return Ok(McpToolResponse {
                id: request.id,
                content: vec![McpContent::text(
                    "Either 'file_path' or 'content' parameter is required".to_string(),
                )],
                is_error: true,
                error: Some("Missing required parameter".to_string()),
                metadata: HashMap::new(),
            });
        };

        let language = request
            .arguments
            .get("language")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string())
            .unwrap_or_else(|| self.detect_language(file_path, &content));

        match request.tool.as_str() {
            "analyze_code" => {
                debug!("Performing comprehensive code analysis for: {}", file_path);

                let analysis_type = request
                    .arguments
                    .get("analysis_type")
                    .and_then(|v| v.as_str())
                    .unwrap_or("comprehensive");

                match analysis_type {
                    "comprehensive" => {
                        let complexity = self.analyze_complexity(file_path, &content).await?;
                        let quality = self.analyze_quality(&content).await;
                        let security = self.analyze_security(&content, &language).await;
                        let dependencies = self.analyze_dependencies(&content, &language).await;

                        // Generate suggestions
                        let mut suggestions = Vec::new();
                        if complexity.cyclomatic_complexity > 10 {
                            suggestions
                                .push("Consider breaking down complex functions".to_string());
                        }
                        if complexity.nested_depth > 4 {
                            suggestions
                                .push("Reduce nesting depth for better readability".to_string());
                        }
                        if quality.documentation_ratio < 10.0 {
                            suggestions.push("Add more documentation and comments".to_string());
                        }

                        let result = CodeAnalysisResult {
                            language: language.clone(),
                            file_path: file_path.to_string(),
                            complexity,
                            quality,
                            security,
                            dependencies,
                            suggestions,
                        };

                        let content_text = format!(
                            "Code Analysis Complete\n\
                            Language: {}\n\
                            Cyclomatic Complexity: {}\n\
                            Lines of Code: {}\n\
                            Functions: {}\n\
                            Security Issues: {}\n\
                            Risk Score: {}/100",
                            result.language,
                            result.complexity.cyclomatic_complexity,
                            result.complexity.lines_of_code,
                            result.complexity.functions,
                            result.security.vulnerabilities.len(),
                            result.security.risk_score
                        );

                        let mut metadata = HashMap::new();
                        metadata
                            .insert("analysis_result".to_string(), serde_json::to_value(result)?);

                        Ok(McpToolResponse {
                            id: request.id,
                            content: vec![McpContent::text(content_text)],
                            is_error: false,
                            error: None,
                            metadata,
                        })
                    }
                    "complexity" => {
                        let complexity = self.analyze_complexity(file_path, &content).await?;
                        let content_text = format!(
                            "Complexity Analysis\n\
                            Cyclomatic Complexity: {}\n\
                            Cognitive Complexity: {}\n\
                            Lines of Code: {}\n\
                            Functions: {}\n\
                            Classes: {}\n\
                            Max Nesting Depth: {}",
                            complexity.cyclomatic_complexity,
                            complexity.cognitive_complexity,
                            complexity.lines_of_code,
                            complexity.functions,
                            complexity.classes,
                            complexity.nested_depth
                        );

                        let mut metadata = HashMap::new();
                        metadata
                            .insert("complexity".to_string(), serde_json::to_value(complexity)?);

                        Ok(McpToolResponse {
                            id: request.id,
                            content: vec![McpContent::text(content_text)],
                            is_error: false,
                            error: None,
                            metadata,
                        })
                    }
                    "security" => {
                        let security = self.analyze_security(&content, &language).await;
                        let content_text = format!(
                            "Security Analysis\n\
                            Vulnerabilities Found: {}\n\
                            Risk Score: {}/100\n\
                            Security Hotspots: {}",
                            security.vulnerabilities.len(),
                            security.risk_score,
                            security.security_hotspots.len()
                        );

                        let mut metadata = HashMap::new();
                        metadata.insert("security".to_string(), serde_json::to_value(security)?);

                        Ok(McpToolResponse {
                            id: request.id,
                            content: vec![McpContent::text(content_text)],
                            is_error: false,
                            error: None,
                            metadata,
                        })
                    }
                    _ => {
                        warn!("Unknown analysis type: {}", analysis_type);
                        Ok(McpToolResponse {
                            id: request.id,
                            content: vec![McpContent::text(format!(
                                "Unknown analysis type: {}",
                                analysis_type
                            ))],
                            is_error: true,
                            error: Some("Invalid analysis type".to_string()),
                            metadata: HashMap::new(),
                        })
                    }
                }
            }
            "detect_language" => {
                debug!("Detecting language for: {}", file_path);
                let detected_language = self.detect_language(file_path, &content);

                let content_text = format!("Detected Language: {}", detected_language);
                let mut metadata = HashMap::new();
                metadata.insert(
                    "language".to_string(),
                    serde_json::Value::String(detected_language),
                );

                Ok(McpToolResponse {
                    id: request.id,
                    content: vec![McpContent::text(content_text)],
                    is_error: false,
                    error: None,
                    metadata,
                })
            }
            "complexity_analysis" => {
                debug!("Analyzing complexity for: {}", file_path);
                let complexity = self.analyze_complexity(file_path, &content).await?;

                let content_text = format!(
                    "Complexity Analysis\n\
                    Cyclomatic Complexity: {}\n\
                    Lines of Code: {}\n\
                    Functions: {}",
                    complexity.cyclomatic_complexity,
                    complexity.lines_of_code,
                    complexity.functions
                );

                let mut metadata = HashMap::new();
                metadata.insert("complexity".to_string(), serde_json::to_value(complexity)?);

                Ok(McpToolResponse {
                    id: request.id,
                    content: vec![McpContent::text(content_text)],
                    is_error: false,
                    error: None,
                    metadata,
                })
            }
            "security_analysis" => {
                debug!("Analyzing security for: {}", file_path);
                let security = self.analyze_security(&content, &language).await;

                let content_text = format!(
                    "Security Analysis\n\
                    Vulnerabilities: {}\n\
                    Risk Score: {}/100",
                    security.vulnerabilities.len(),
                    security.risk_score
                );

                let mut metadata = HashMap::new();
                metadata.insert("security".to_string(), serde_json::to_value(security)?);

                Ok(McpToolResponse {
                    id: request.id,
                    content: vec![McpContent::text(content_text)],
                    is_error: false,
                    error: None,
                    metadata,
                })
            }
            _ => {
                warn!("Unknown Code Analysis tool: {}", request.tool);
                Err(McpToolsError::Server(format!(
                    "Unknown Code Analysis tool: {}",
                    request.tool
                )))
            }
        }
    }

    async fn get_stats(&self) -> Result<crate::common::ServerStats> {
        self.base.get_stats().await
    }

    async fn initialize(&mut self) -> Result<()> {
        info!("Initializing Code Analysis MCP Server");
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        info!("Shutting down Code Analysis MCP Server");
        Ok(())
    }
}