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
// MCP protocol communication: run loop, request handling, and cache metrics.
// Included by server.rs - shares parent module scope (no `use` imports here).
impl McpServer {
/// 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"
/// }
/// }
/// }
/// ```
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
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
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
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
)
}
}