pmat 2.93.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
//! Analysis tool handlers for the pmcp-based MCP server.
//!
//! This module contains tool handlers for various code analysis operations
//! including complexity analysis, technical debt detection, and code quality metrics.

use crate::mcp_pmcp::tool_functions;
use async_trait::async_trait;
use pmcp::{Error, RequestHandlerExtra, Result, ToolHandler};
use serde::Deserialize;
use serde_json::Value;
use std::path::PathBuf;
use tracing::debug;

// Re-export for convenience
pub use self::{
    ChurnTool as AnalyzeDeepContextTool, ComplexityTool as AnalyzeComplexityTool,
    CouplingTool as AnalyzeBigOTool, DeadCodeTool as AnalyzeDeadCodeTool,
    LintHotspotTool as AnalyzeDagTool, SatdTool as AnalyzeSatdTool,
    TdgCompareTool as AnalyzeTdgCompareTool, TdgTool as AnalyzeTdgTool,
};

// Complexity Analysis Tool

#[derive(Debug, Deserialize)]
struct ComplexityArgs {
    paths: Vec<String>,
    #[serde(default)]
    top_files: Option<usize>,
    #[serde(default)]
    threshold: Option<u64>,
}

/// Tool handler for analyzing code complexity metrics.
///
/// This tool calculates cyclomatic and cognitive complexity for source files,
/// helping identify areas of code that may be difficult to understand or maintain.
///
/// # Arguments
///
/// The tool accepts JSON arguments with the following schema:
/// ```json
/// {
///   "paths": ["src/", "tests/"],        // Required: paths to analyze
///   "top_files": 10,                    // Optional: number of files to return
///   "threshold": 20                     // Optional: complexity threshold
/// }
/// ```
///
/// # Examples
///
/// ```rust
/// use pmat::mcp_pmcp::analyze_handlers::AnalyzeComplexityTool;
/// use pmcp::ToolHandler;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tool = AnalyzeComplexityTool::new();
/// let args = json!({
///     "paths": ["src/"],
///     "top_files": 5,
///     "threshold": 15
/// });
///
/// // In practice, this would be called by the MCP server
/// // let result = tool.handle(args, Default::default()).await?;
/// # Ok(())
/// # }
/// ```
pub struct ComplexityTool;

impl ComplexityTool {
    /// Creates a new complexity analysis tool handler.
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for ComplexityTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for ComplexityTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.complexity with args: {}", args);

        let params: ComplexityArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results =
            tool_functions::analyze_complexity(&paths, params.top_files, params.threshold)
                .await
                .map_err(|e| Error::internal(format!("Complexity analysis failed: {e}")))?;

        Ok(results)
    }
}

// SATD (Self-Admitted Technical Debt) Analysis Tool

#[derive(Debug, Deserialize)]
struct SatdArgs {
    paths: Vec<String>,
    #[serde(default)]
    include_resolved: bool,
}

/// Tool handler for detecting self-admitted technical debt in code comments.
///
/// This tool scans source files for TODO, FIXME, HACK, and other markers
/// that indicate technical debt acknowledged by developers.
///
/// # Arguments
///
/// ```json
/// {
///   "paths": ["src/"],              // Required: paths to analyze
///   "include_resolved": false       // Optional: include resolved items
/// }
/// ```
///
/// # Examples
///
/// ```rust
/// # #[cfg(feature = "pmcp-mcp")]
/// # {
/// use pmat::mcp_pmcp::analyze_handlers::AnalyzeSatdTool;
/// use serde_json::json;
///
/// let tool = AnalyzeSatdTool::new();
/// let args = json!({
///     "paths": ["src/", "tests/"],
///     "include_resolved": false
/// });
/// # }
/// ```
pub struct SatdTool;

impl SatdTool {
    /// Creates a new SATD analysis tool handler.
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for SatdTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for SatdTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.satd with args: {}", args);

        let params: SatdArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_satd(&paths, params.include_resolved)
            .await
            .map_err(|e| Error::internal(format!("SATD analysis failed: {e}")))?;

        Ok(results)
    }
}

// Dead Code Analysis Tool

#[derive(Debug, Deserialize)]
struct DeadCodeArgs {
    paths: Vec<String>,
    #[serde(default)]
    include_tests: bool,
}

pub struct DeadCodeTool;

impl DeadCodeTool {
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for DeadCodeTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for DeadCodeTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.dead-code with args: {}", args);

        let params: DeadCodeArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_dead_code(&paths, params.include_tests)
            .await
            .map_err(|e| Error::internal(format!("Dead code analysis failed: {e}")))?;

        Ok(results)
    }
}

// Lint Hotspot Analysis Tool

#[derive(Debug, Deserialize)]
struct LintHotspotArgs {
    paths: Vec<String>,
    #[serde(default)]
    top_files: Option<usize>,
}

pub struct LintHotspotTool;

impl LintHotspotTool {
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for LintHotspotTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for LintHotspotTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.lint-hotspot with args: {}", args);

        let params: LintHotspotArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_lint_hotspots(&paths, params.top_files)
            .await
            .map_err(|e| Error::internal(format!("Lint hotspot analysis failed: {e}")))?;

        Ok(results)
    }
}

// Churn Analysis Tool

#[derive(Debug, Deserialize)]
struct ChurnArgs {
    paths: Vec<String>,
    #[serde(default)]
    days: Option<u32>,
    #[serde(default)]
    top_files: Option<usize>,
}

pub struct ChurnTool;

impl ChurnTool {
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for ChurnTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for ChurnTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.churn with args: {}", args);

        let params: ChurnArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_churn(&paths, params.days, params.top_files)
            .await
            .map_err(|e| Error::internal(format!("Churn analysis failed: {e}")))?;

        Ok(results)
    }
}

// Coupling Analysis Tool

#[derive(Debug, Deserialize)]
struct CouplingArgs {
    paths: Vec<String>,
    #[serde(default)]
    threshold: Option<f64>,
}

pub struct CouplingTool;

impl CouplingTool {
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for CouplingTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for CouplingTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.coupling with args: {}", args);

        let params: CouplingArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_coupling(&paths, params.threshold)
            .await
            .map_err(|e| Error::internal(format!("Coupling analysis failed: {e}")))?;

        Ok(results)
    }
}

// TDG (Technical Debt Grading) Analysis Tool

#[derive(Debug, Deserialize)]
struct TdgArgs {
    paths: Vec<String>,
    #[serde(default)]
    threshold: Option<f64>,
    #[serde(default)]
    top_files: Option<usize>,
    #[serde(default)]
    include_components: Option<bool>,
}

/// Tool handler for analyzing Technical Debt Grading (TDG) scores.
///
/// This tool calculates comprehensive code quality scores using orthogonal metrics:
/// structural complexity, semantic complexity, code duplication, coupling,
/// documentation coverage, and code consistency.
///
/// # Arguments
///
/// The tool accepts JSON arguments with the following schema:
/// ```json
/// {
///   "paths": ["src/", "tests/"],        // Required: paths to analyze
///   "threshold": 75.0,                  // Optional: minimum score threshold
///   "top_files": 10,                    // Optional: number of files to return
///   "include_components": true          // Optional: include metric breakdown
/// }
/// ```
///
/// # Examples
///
/// ```rust
/// use pmat::mcp_pmcp::analyze_handlers::AnalyzeTdgTool;
/// use pmcp::ToolHandler;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let tool = AnalyzeTdgTool::new();
/// let args = json!({
///     "paths": ["src/"],
///     "threshold": 80.0,
///     "top_files": 5,
///     "include_components": true
/// });
///
/// // In practice, this would be called by the MCP server
/// // let result = tool.handle(args, Default::default()).await?;
/// # Ok(())
/// # }
/// ```
pub struct TdgTool;

impl TdgTool {
    /// Creates a new TDG analysis tool handler.
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for TdgTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for TdgTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.tdg with args: {}", args);

        let params: TdgArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let paths: Vec<PathBuf> = params.paths.into_iter().map(PathBuf::from).collect();

        let results = tool_functions::analyze_tdg(
            &paths,
            params.threshold,
            params.top_files,
            params.include_components,
        )
        .await
        .map_err(|e| Error::internal(format!("TDG analysis failed: {e}")))?;

        Ok(results)
    }
}

// TDG Comparison Tool

#[derive(Debug, Deserialize)]
struct TdgCompareArgs {
    path1: String,
    path2: String,
}

/// Tool handler for comparing TDG scores between two files or directories.
///
/// This tool compares the technical debt grading scores between two codebases
/// or files, showing improvements, regressions, and overall changes.
///
/// # Arguments
///
/// The tool accepts JSON arguments with the following schema:
/// ```json
/// {
///   "path1": "src/old_version/",       // Required: first path to compare
///   "path2": "src/new_version/"        // Required: second path to compare
/// }
/// ```
pub struct TdgCompareTool;

impl TdgCompareTool {
    /// Creates a new TDG comparison tool handler.
    #[must_use] 
    pub fn new() -> Self {
        Self
    }
}

impl Default for TdgCompareTool {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl ToolHandler for TdgCompareTool {
    async fn handle(&self, args: Value, _extra: RequestHandlerExtra) -> Result<Value> {
        debug!("Handling analyze.tdg_compare with args: {}", args);

        let params: TdgCompareArgs = serde_json::from_value(args)
            .map_err(|e| Error::validation(format!("Invalid arguments: {e}")))?;

        let path1 = PathBuf::from(params.path1);
        let path2 = PathBuf::from(params.path2);

        let results = tool_functions::compare_tdg(&path1, &path2)
            .await
            .map_err(|e| Error::internal(format!("TDG comparison failed: {e}")))?;

        Ok(results)
    }
}

#[cfg(test)]
mod property_tests {
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn basic_property_stability(_input in ".*") {
            // Basic property test for coverage
            prop_assert!(true);
        }

        #[test]
        fn module_consistency_check(_x in 0u32..1000) {
            // Module consistency verification
            prop_assert!(_x < 1001);
        }
    }
}