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
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
use crate::mcp_server::cache::{CacheConfig, CacheKeyBuilder, McpCache};
use crate::mcp_server::handlers;
use crate::mcp_server::state_manager::StateManager;
use crate::models::mcp::{McpRequest, McpResponse};
use serde_json::json;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::Mutex;
use tracing::{debug, error, info};

/// Model Context Protocol (MCP) server for PMAT refactoring capabilities.
///
/// This server implements the MCP specification for AI-assisted refactoring,
/// providing a standardized interface for Claude and other AI models to interact
/// with PMAT's analysis and refactoring capabilities. Critical for maintaining
/// MCP protocol compliance and preventing API drift.
///
/// # MCP Protocol Support
///
/// - **Protocol Version**: 2024-11-05
/// - **Transport**: JSON-RPC 2.0 over stdin/stdout
/// - **Capabilities**: Refactoring state machine control
/// - **Error Handling**: Standard JSON-RPC error codes
///
/// # Supported Methods
///
/// ## Core Protocol Methods
/// - `initialize` - Initialize MCP session with capabilities
///
/// ## Refactoring Methods
/// - `refactor.start` - Start new refactoring session
/// - `refactor.nextIteration` - Advance refactoring state machine
/// - `refactor.getState` - Get current refactoring state
/// - `refactor.stop` - Stop current refactoring session
///
/// # State Management
///
/// The server maintains refactoring sessions with:
/// - Target files and configuration
/// - State machine progression (Scan → Analyze → Plan → Refactor → Complete)
/// - Session isolation and cleanup
/// - Error recovery and rollback
///
/// # Examples
///
/// ```rust,no_run
/// use pmat::mcp_server::server::McpServer;
///
/// # tokio_test::block_on(async {
/// // Create MCP server
/// let server = McpServer::new();
///
/// // Server is ready for MCP communication
/// // In real usage, server.run().await would handle stdin/stdout
/// # });
/// ```
///
/// # MCP Message Examples
///
/// ## Initialize Request
/// ```json
/// {
///   "jsonrpc": "2.0",
///   "id": 1,
///   "method": "initialize",
///   "params": {
///     "protocolVersion": "2024-11-05",
///     "clientInfo": {
///       "name": "claude-desktop",
///       "version": "1.0.0"
///     }
///   }
/// }
/// ```
///
/// ## Refactor Start Request
/// ```json
/// {
///   "jsonrpc": "2.0",
///   "id": 2,
///   "method": "refactor.start",
///   "params": {
///     "targets": ["/path/to/file.rs"],
///     "config": {
///       "target_complexity": 15,
///       "remove_satd": true
///     }
///   }
/// }
/// ```
///
/// ## State Query Request
/// ```json
/// {
///   "jsonrpc": "2.0",
///   "id": 3,
///   "method": "refactor.getState"
/// }
/// ```
pub struct McpServer {
    state_manager: Arc<Mutex<StateManager>>,
    cache: Arc<McpCache>,
}

impl McpServer {
    /// Creates a new MCP server with default state management.
    ///
    /// Initializes the server with a new state manager for handling refactoring
    /// sessions. The server is ready to accept MCP connections and process
    /// refactoring requests according to the MCP protocol specification.
    ///
    /// # Returns
    ///
    /// A new `McpServer` instance with initialized state management.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use pmat::mcp_server::server::McpServer;
    ///
    /// // Create MCP server for AI integration
    /// let server = McpServer::new();
    ///
    /// // Server is ready for MCP protocol communication
    /// // Typically used with: server.run().await
    /// ```
    ///
    /// # MCP Integration
    ///
    /// The server is designed to integrate with MCP clients like:
    /// - Claude Desktop application
    /// - VS Code with MCP extension
    /// - Custom MCP clients
    /// - CI/CD pipeline integrations
    #[must_use] 
    pub fn new() -> Self {
        let cache_config = CacheConfig {
            max_entries: 5000,
            default_ttl: Duration::from_secs(600), // 10 minutes
            enable_metrics: true,
        };

        Self {
            state_manager: Arc::new(Mutex::new(StateManager::new())),
            cache: Arc::new(McpCache::with_config(cache_config)),
        }
    }

    /// Runs the MCP server main loop, handling stdin/stdout communication.
    ///
    /// This method implements the core MCP protocol communication loop, reading
    /// JSON-RPC messages from stdin and writing responses to stdout. Handles
    /// the complete MCP session lifecycle including initialization, method dispatch,
    /// and error handling.
    ///
    /// # Protocol Flow
    ///
    /// 1. **Initialization**: Send server capabilities to client
    /// 2. **Message Loop**: Process incoming JSON-RPC requests
    /// 3. **Method Dispatch**: Route requests to appropriate handlers
    /// 4. **Response Generation**: Send JSON-RPC responses
    /// 5. **Error Handling**: Handle protocol and processing errors
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Server shutdown gracefully
    /// * `Err(Box<dyn std::error::Error>)` - I/O error, protocol error, or handler failure
    ///
    /// # Communication Protocol
    ///
    /// The server uses line-delimited JSON over stdin/stdout:
    /// - **Input**: JSON-RPC 2.0 requests (one per line)
    /// - **Output**: JSON-RPC 2.0 responses (one per line)
    /// - **Transport**: stdin/stdout pipes
    /// - **Encoding**: UTF-8 text
    ///
    /// # Error Handling
    ///
    /// Standard JSON-RPC error codes:
    /// - `-32700`: Parse error (invalid JSON)
    /// - `-32600`: Invalid request (bad JSON-RPC)
    /// - `-32601`: Method not found
    /// - `-32602`: Invalid params
    /// - `-32603`: Internal error
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmat::mcp_server::server::McpServer;
    ///
    /// # tokio_test::block_on(async {
    /// let server = McpServer::new();
    ///
    /// // In real usage, this would run the MCP protocol loop
    /// // let result = server.run().await;
    /// // assert!(result.is_ok());
    ///
    /// // For testing, we just verify the server can be created
    /// # });
    /// ```
    ///
    /// # MCP Client Integration
    ///
    /// ## Claude Desktop Configuration
    /// ```json
    /// {
    ///   "mcpServers": {
    ///     "pmat": {
    ///       "command": "pmat",
    ///       "args": ["serve", "mcp"],
    ///       "env": {}
    ///     }
    ///   }
    /// }
    /// ```
    ///
    /// ## VS Code MCP Extension
    /// ```json
    /// {
    ///   "mcp.servers": [{
    ///     "name": "PMAT Refactoring",
    ///     "command": ["pmat", "serve", "mcp"],
    ///     "capabilities": ["refactor"]
    ///   }]
    /// }
    /// ```
    ///
    /// # Protocol Messages
    ///
    /// ## Initialization Response
    /// ```json
    /// {
    ///   "jsonrpc": "2.0",
    ///   "result": {
    ///     "protocolVersion": "2024-11-05",
    ///     "capabilities": {
    ///       "refactor": {
    ///         "start": true,
    ///         "nextIteration": true,
    ///         "getState": true,
    ///         "stop": true
    ///       }
    ///     },
    ///     "serverInfo": {
    ///       "name": "pmat-mcp-server",
    ///       "version": "0.27.5"
    ///     }
    ///   }
    /// }
    /// ```
    pub async fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        info!("Starting MCP server on stdin/stdout");

        let stdin = tokio::io::stdin();
        let mut stdout = tokio::io::stdout();
        let reader = BufReader::new(stdin);
        let mut lines = reader.lines();

        // Send initialization response
        let init_response = json!({
            "jsonrpc": "2.0",
            "result": {
                "protocolVersion": "2024-11-05",
                "capabilities": {
                    "refactor": {
                        "start": true,
                        "nextIteration": true,
                        "getState": true,
                        "stop": true
                    }
                },
                "serverInfo": {
                    "name": "pmat-mcp-server",
                    "version": env!("CARGO_PKG_VERSION")
                }
            }
        });

        stdout
            .write_all(format!("{init_response}\n").as_bytes())
            .await?;
        stdout.flush().await?;

        // Main message loop
        while let Some(line) = lines.next_line().await? {
            if line.trim().is_empty() {
                continue;
            }

            debug!("Received MCP request: {}", line);

            let response = match self.handle_request(&line).await {
                Ok(resp) => resp,
                Err(e) => {
                    error!("Error handling request: {}", e);
                    McpResponse::error(json!(null), -32603, e.to_string())
                }
            };

            let response_json = serde_json::to_string(&response)?;
            debug!("Sending MCP response: {}", response_json);

            stdout.write_all(response_json.as_bytes()).await?;
            stdout.write_all(b"\n").await?;
            stdout.flush().await?;
        }

        info!("MCP server shutting down");
        Ok(())
    }

    /// Handles a single MCP request and returns the appropriate response.
    ///
    /// This method implements the core MCP request processing logic, including
    /// JSON-RPC validation, method routing, and response generation. Critical for
    /// maintaining MCP protocol compliance and method stability.
    ///
    /// # Parameters
    ///
    /// * `line` - Raw JSON-RPC request string from stdin
    ///
    /// # Returns
    ///
    /// * `Ok(McpResponse)` - Valid MCP response (success or error)
    /// * `Err(Box<dyn std::error::Error>)` - Parse error or handler failure
    ///
    /// # Protocol Validation
    ///
    /// 1. **JSON Parsing**: Validate request is valid JSON
    /// 2. **JSON-RPC Validation**: Check jsonrpc field is "2.0"
    /// 3. **Method Resolution**: Route to appropriate handler
    /// 4. **Parameter Validation**: Validate method-specific parameters
    /// 5. **Response Generation**: Create success or error response
    ///
    /// # Supported MCP Methods
    ///
    /// - `initialize` - MCP session initialization
    /// - `refactor.start` - Start new refactoring session
    /// - `refactor.nextIteration` - Advance state machine
    /// - `refactor.getState` - Query current state
    /// - `refactor.stop` - Stop refactoring session
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmat::mcp_server::server::McpServer;
    ///
    /// # tokio_test::block_on(async {
    /// let server = McpServer::new();
    ///
    /// // Initialize request example
    /// let init_request = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#;
    /// // The handle_request method is private and used internally
    /// // This demonstrates the expected JSON-RPC format
    /// assert!(init_request.contains("jsonrpc"));
    /// assert!(init_request.contains("2.0"));
    /// assert!(init_request.contains("initialize"));
    ///
    /// // Invalid JSON-RPC version example
    /// let bad_request = r#"{"jsonrpc":"1.0","id":2,"method":"test"}"#;
    /// // Should be rejected due to invalid version
    /// assert!(bad_request.contains("1.0"));
    /// # });
    /// ```
    ///
    /// # Request/Response Examples
    ///
    /// ## Initialize Method
    /// ```json
    /// // Request
    /// {
    ///   "jsonrpc": "2.0",
    ///   "id": 1,
    ///   "method": "initialize",
    ///   "params": {
    ///     "protocolVersion": "2024-11-05"
    ///   }
    /// }
    ///
    /// // Response
    /// {
    ///   "jsonrpc": "2.0",
    ///   "id": 1,
    ///   "result": {
    ///     "protocolVersion": "2024-11-05",
    ///     "capabilities": {
    ///       "refactor": {
    ///         "start": true,
    ///         "nextIteration": true,
    ///         "getState": true,
    ///         "stop": true
    ///       }
    ///     }
    ///   }
    /// }
    /// ```
    ///
    /// ## Refactor Start Method
    /// ```json
    /// // Request
    /// {
    ///   "jsonrpc": "2.0",
    ///   "id": 2,
    ///   "method": "refactor.start",
    ///   "params": {
    ///     "targets": ["/path/to/file.rs"],
    ///     "config": {
    ///       "target_complexity": 15,
    ///       "remove_satd": true
    ///     }
    ///   }
    /// }
    ///
    /// // Response
    /// {
    ///   "jsonrpc": "2.0",
    ///   "id": 2,
    ///   "result": {
    ///     "session_id": "uuid-string",
    ///     "state": {
    ///       "current": "Scan",
    ///       "targets": ["/path/to/file.rs"]
    ///     }
    ///   }
    /// }
    /// ```
    ///
    /// ## Error Response
    /// ```json
    /// {
    ///   "jsonrpc": "2.0",
    ///   "id": 3,
    ///   "error": {
    ///     "code": -32601,
    ///     "message": "Method not found: unknown.method"
    ///   }
    /// }
    /// ```
    async fn handle_request(&self, line: &str) -> Result<McpResponse, Box<dyn std::error::Error>> {
        let request: McpRequest = serde_json::from_str(line)?;

        // Validate JSON-RPC version
        if request.jsonrpc != "2.0" {
            return Ok(McpResponse::error(
                request.id,
                -32600,
                "Invalid JSON-RPC version".to_string(),
            ));
        }

        // Check cache for read-only operations
        let cache_key = if matches!(request.method.as_str(), "refactor.getState" | "initialize") {
            let mut hasher = DefaultHasher::new();
            request.method.hash(&mut hasher);
            request.params.hash(&mut hasher);
            Some(CacheKeyBuilder::method_result_key(
                &request.method,
                hasher.finish(),
            ))
        } else {
            None
        };

        // Try to get from cache
        if let Some(key) = &cache_key {
            if let Some(cached_value) = self.cache.get(key).await {
                debug!("Cache hit for method: {}", request.method);
                return Ok(McpResponse::success(request.id, cached_value));
            }
        }

        // Route to appropriate handler
        let result = match request.method.as_str() {
            "initialize" => {
                json!({
                    "protocolVersion": "2024-11-05",
                    "capabilities": {
                        "refactor": {
                            "start": true,
                            "nextIteration": true,
                            "getState": true,
                            "stop": true
                        }
                    },
                    "serverInfo": {
                        "name": "pmat-mcp-server",
                        "version": env!("CARGO_PKG_VERSION")
                    }
                })
            }
            "refactor.start" => {
                handlers::handle_refactor_start(
                    &self.state_manager,
                    request.params.unwrap_or(json!({})),
                )
                .await?
            }
            "refactor.nextIteration" => {
                handlers::handle_refactor_next_iteration(&self.state_manager).await?
            }
            "refactor.getState" => handlers::handle_refactor_get_state(&self.state_manager).await?,
            "refactor.stop" => handlers::handle_refactor_stop(&self.state_manager).await?,
            _ => {
                return Ok(McpResponse::error(
                    request.id,
                    -32601,
                    format!("Method not found: {}", request.method),
                ));
            }
        };

        // Cache the result for read-only operations
        if let Some(key) = cache_key {
            self.cache.set(key, result.clone()).await;
            debug!("Cached result for method: {}", request.method);
        }

        Ok(McpResponse::success(request.id, result))
    }

    /// Get cache metrics for monitoring
    pub async fn cache_metrics(&self) -> String {
        let metrics = self.cache.metrics().await;
        format!(
            "Cache Metrics - Hits: {}, Misses: {}, Hit Ratio: {:.2}%, Size: {}",
            metrics.hits,
            metrics.misses,
            metrics.hit_ratio() * 100.0,
            self.cache.size().await
        )
    }
}

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

#[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);
        }
    }
}