mcp-cpp-server 0.2.2

A high-performance Model Context Protocol (MCP) server for C++ code analysis using clangd LSP integration
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
//! JSON-RPC 2.0 protocol layer
//!
//! Implements JSON-RPC 2.0 protocol with request/response matching,
//! notification handling, and proper error management.

use crate::io::transport::Transport;
use crate::lsp::framing::LspFraming;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::sync::{Mutex, mpsc};
use tracing::{debug, error, trace};

// ============================================================================
// JSON-RPC Types
// ============================================================================

/// JSON-RPC 2.0 request message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcRequest {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,

    /// Request identifier
    pub id: serde_json::Value,

    /// Method name
    pub method: String,

    /// Optional parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

/// JSON-RPC 2.0 response message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcResponse {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,

    /// Request identifier (matches the request)
    pub id: serde_json::Value,

    /// Result (present if successful)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,

    /// Error (present if failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcErrorObject>,
}

/// JSON-RPC 2.0 notification message (no response expected)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcNotification {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,

    /// Method name
    pub method: String,

    /// Optional parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

/// JSON-RPC error object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonRpcErrorObject {
    /// Error code
    pub code: i32,

    /// Error message
    pub message: String,

    /// Optional additional data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

// ============================================================================
// JSON-RPC Errors
// ============================================================================

/// JSON-RPC error codes as defined in the specification
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i32)]
pub enum JsonRpcErrorCode {
    InternalError = -32603,
}

impl JsonRpcErrorCode {}

/// JSON-RPC error type
#[derive(Debug, thiserror::Error)]

pub enum JsonRpcError {
    #[error("JSON-RPC server error ({code}): {message}")]
    Server {
        code: i32,
        message: String,
        data: Option<serde_json::Value>,
    },

    #[error("Transport error: {0}")]
    Transport(String),

    #[error("Serialization error: {0}")]
    Serialization(serde_json::Error),

    #[error("Deserialization error: {0}")]
    Deserialization(serde_json::Error),

    #[error("Request timeout")]
    Timeout,

    #[error("Request was cancelled")]
    RequestCancelled,

    #[error("Missing result in response")]
    MissingResult,
}

// ============================================================================
// JSON-RPC Client
// ============================================================================

/// Type alias for notification handler to reduce complexity
type NotificationHandler = Arc<dyn Fn(JsonRpcNotification) + Send + Sync>;

/// Type alias for request handler to reduce complexity
type RequestHandler = Arc<dyn Fn(JsonRpcRequest) -> JsonRpcResponse + Send + Sync>;

// ============================================================================
// Message Classification
// ============================================================================

/// Properly classified JSON-RPC message according to specification
#[derive(Debug, Clone)]
enum JsonRpcMessage {
    /// Request from client to server (has method + non-null id)
    Request {
        method: String,
        id: serde_json::Value,
        params: Option<serde_json::Value>,
    },
    /// Notification (has method, id is null or missing)
    Notification {
        method: String,
        params: Option<serde_json::Value>,
    },
    /// Response to our request (no method, has non-null id)
    Response {
        id: serde_json::Value,
        result: Option<serde_json::Value>,
        error: Option<JsonRpcErrorObject>,
    },
    /// Invalid message that couldn't be classified
    Invalid(String),
}

impl JsonRpcMessage {
    /// Classify a JSON-RPC message according to JSON-RPC 2.0 specification
    fn classify(message: &str) -> Self {
        let parsed = match serde_json::from_str::<serde_json::Value>(message) {
            Ok(value) => value,
            Err(e) => return Self::Invalid(format!("JSON parse error: {e}")),
        };

        let method = parsed
            .get("method")
            .and_then(|m| m.as_str())
            .map(|s| s.to_string());
        let id = parsed.get("id").cloned();
        let params = parsed.get("params").cloned();

        match (method, id) {
            // Request: has method + non-null id
            (Some(method), Some(id)) if !id.is_null() => Self::Request { method, id, params },
            // Notification: has method, id is null or missing
            (Some(method), _) => Self::Notification { method, params },
            // Response: no method, has non-null id
            (None, Some(id)) if !id.is_null() => {
                let result = parsed.get("result").cloned();
                let error = parsed
                    .get("error")
                    .and_then(|e| serde_json::from_value::<JsonRpcErrorObject>(e.clone()).ok());
                Self::Response { id, result, error }
            }
            // Invalid: doesn't match any pattern
            _ => Self::Invalid("Missing required fields or invalid structure".to_string()),
        }
    }
}

// ============================================================================
// Client State Management
// ============================================================================

/// Unified client state to eliminate cloning and multiple mutexes
#[derive(Default)]
struct ClientState {
    /// Handler for incoming notifications
    notification_handler: Option<NotificationHandler>,
    /// Handler for incoming requests from server
    request_handler: Option<RequestHandler>,
    /// Pending requests waiting for responses
    pending_requests: HashMap<u64, mpsc::UnboundedSender<JsonRpcResponse>>,
}

/// JSON-RPC client with request/response correlation
pub struct JsonRpcClient<T: Transport> {
    /// Channel for sending outbound messages (requests and notifications)
    outbound_sender: mpsc::UnboundedSender<String>,

    /// Request ID counter
    request_id: AtomicU64,

    /// Unified client state (single mutex instead of multiple)
    state: Arc<Mutex<ClientState>>,

    /// Type parameter marker
    _phantom: std::marker::PhantomData<T>,
}

impl<T: Transport + 'static> JsonRpcClient<T> {
    /// Create a new JSON-RPC client
    pub fn new(transport: T) -> Self {
        let framed_transport = LspFraming::new(transport);
        let transport_arc = Arc::new(Mutex::new(framed_transport));
        let (outbound_sender, mut outbound_receiver) = mpsc::unbounded_channel::<String>();

        // Unified state - single Arc instead of multiple
        let state = Arc::new(Mutex::new(ClientState::default()));

        // Transport handler task - only clone what we actually need
        let transport_for_task = Arc::clone(&transport_arc);
        let state_for_task = Arc::clone(&state);
        let outbound_sender_for_task = outbound_sender.clone();

        tokio::spawn(async move {
            loop {
                tokio::select! {
                    // Outbound messages (prioritized)
                    Some(message) = outbound_receiver.recv() => {
                        let mut transport = transport_for_task.lock().await;
                        if let Err(e) = transport.send(&message).await {
                            error!("Failed to send message: {}", e);
                            break;
                        }
                        // Release lock immediately
                        drop(transport);
                    }
                    // Inbound messages
                    result = async {
                        let mut transport = transport_for_task.lock().await;
                        transport.receive().await
                    } => {
                        match result {
                            Ok(message) => {
                                Self::process_inbound_message(message, &state_for_task, &outbound_sender_for_task).await;
                            }
                            Err(e) => {
                                error!("Failed to receive message: {}", e);
                                break;
                            }
                        }
                    }
                }
            }
            trace!("Transport handler task finished");
        });

        Self {
            outbound_sender,
            request_id: AtomicU64::new(1),
            state,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Set notification handler
    pub async fn on_notification<F>(&self, handler: F)
    where
        F: Fn(JsonRpcNotification) + Send + Sync + 'static,
    {
        let mut state = self.state.lock().await;
        state.notification_handler = Some(Arc::new(handler));
    }

    /// Set request handler
    pub async fn on_request<F>(&self, handler: F)
    where
        F: Fn(JsonRpcRequest) -> JsonRpcResponse + Send + Sync + 'static,
    {
        let mut state = self.state.lock().await;
        state.request_handler = Some(Arc::new(handler));
    }

    /// Process an inbound message (response, request, or notification)
    async fn process_inbound_message(
        message: String,
        state: &Arc<Mutex<ClientState>>,
        outbound_sender: &mpsc::UnboundedSender<String>,
    ) {
        trace!("JsonRpcClient: Received {} bytes", message.len());

        // Classify message using proper enum-based approach
        let classified_message = JsonRpcMessage::classify(&message);

        match classified_message {
            JsonRpcMessage::Request { method, id, params } => {
                debug!("Received request: {} with id: {:?}", method, id);

                // Get request handler (single lock acquisition)
                let request_handler = {
                    let state = state.lock().await;
                    state.request_handler.clone()
                };

                if let Some(handler) = request_handler {
                    let request = JsonRpcRequest {
                        jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
                        method,
                        id: id.clone(),
                        params,
                    };

                    let response = handler(request);
                    let response_json = match serde_json::to_string(&response) {
                        Ok(json) => json,
                        Err(e) => {
                            debug!("Failed to serialize response: {}", e);
                            return;
                        }
                    };

                    if outbound_sender.send(response_json).is_err() {
                        debug!("Failed to send response back to server");
                    }
                } else {
                    debug!("No request handler registered for method: {}", method);
                }
            }

            JsonRpcMessage::Notification { method, params } => {
                debug!("Received notification: {}", method);

                // Get notification handler (single lock acquisition)
                let notification_handler = {
                    let state = state.lock().await;
                    state.notification_handler.clone()
                };

                if let Some(handler) = notification_handler {
                    let notification = JsonRpcNotification {
                        jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
                        method,
                        params,
                    };
                    handler(notification);
                }
            }

            JsonRpcMessage::Response { id, result, error } => {
                // Try to match by ID (could be any JSON type, but we track as u64)
                if let Some(id_u64) = id.as_u64() {
                    let mut state = state.lock().await;
                    if let Some(sender) = state.pending_requests.remove(&id_u64) {
                        let response = JsonRpcResponse {
                            jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
                            id,
                            result,
                            error,
                        };
                        if sender.send(response).is_err() {
                            debug!("Response receiver dropped for request {}", id_u64);
                        }
                    } else {
                        debug!("Received response for unknown request {}", id_u64);
                    }
                } else {
                    debug!("Response has non-numeric ID, cannot match: {:?}", id);
                }
            }

            JsonRpcMessage::Invalid(reason) => {
                debug!("Received invalid JSON-RPC message: {}", reason);
            }
        }
    }

    /// Send a JSON-RPC request with default timeout (30 seconds)
    pub async fn request<P, R>(
        &mut self,
        method: &str,
        params: Option<P>,
    ) -> Result<R, JsonRpcError>
    where
        P: serde::Serialize,
        R: for<'de> serde::Deserialize<'de>,
    {
        self.request_with_timeout(method, params, std::time::Duration::from_secs(30))
            .await
    }

    /// Send a JSON-RPC request with custom timeout
    pub async fn request_with_timeout<P, R>(
        &mut self,
        method: &str,
        params: Option<P>,
        timeout: std::time::Duration,
    ) -> Result<R, JsonRpcError>
    where
        P: serde::Serialize,
        R: for<'de> serde::Deserialize<'de>,
    {
        let id = self.request_id.fetch_add(1, Ordering::SeqCst);
        let (response_sender, mut response_receiver) = mpsc::unbounded_channel();

        // Register pending request
        {
            let mut state = self.state.lock().await;
            state.pending_requests.insert(id, response_sender);
        }

        // Create request
        let request = JsonRpcRequest {
            jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
            id: Value::Number(serde_json::Number::from(id)),
            method: method.to_string(),
            params: params
                .map(|p| serde_json::to_value(p).map_err(JsonRpcError::Serialization))
                .transpose()?,
        };

        // Send request
        let request_json = serde_json::to_string(&request).map_err(JsonRpcError::Serialization)?;
        debug!("JsonRpcClient: Sending request: {}", request_json);

        // Send through the channel
        self.outbound_sender
            .send(request_json)
            .map_err(|_| JsonRpcError::Transport("Outbound channel closed".to_string()))?;

        // Wait for response with timeout
        let response_result = tokio::time::timeout(timeout, response_receiver.recv()).await;

        // Handle timeout - clean up pending request
        let response = match response_result {
            Ok(Some(response)) => response,
            Ok(None) => {
                // Channel closed - clean up pending request
                let mut state = self.state.lock().await;
                state.pending_requests.remove(&id);
                return Err(JsonRpcError::RequestCancelled);
            }
            Err(_) => {
                // Timeout - clean up pending request
                let mut state = self.state.lock().await;
                state.pending_requests.remove(&id);
                return Err(JsonRpcError::Timeout);
            }
        };

        // Handle response
        if let Some(error) = response.error {
            return Err(JsonRpcError::Server {
                code: error.code,
                message: error.message,
                data: error.data,
            });
        }

        match response.result {
            Some(Value::Null) => {
                // Handle null results (e.g., LSP shutdown) by trying to deserialize null as R
                serde_json::from_value(Value::Null).map_err(JsonRpcError::Deserialization)
            }
            Some(result) => serde_json::from_value(result).map_err(JsonRpcError::Deserialization),
            None => Err(JsonRpcError::MissingResult),
        }
    }

    /// Send a JSON-RPC notification
    pub async fn notify<P>(&mut self, method: &str, params: Option<P>) -> Result<(), JsonRpcError>
    where
        P: serde::Serialize,
    {
        let notification = JsonRpcNotification {
            jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
            method: method.to_string(),
            params: params
                .map(|p| serde_json::to_value(p).map_err(JsonRpcError::Serialization))
                .transpose()?,
        };

        let notification_json =
            serde_json::to_string(&notification).map_err(JsonRpcError::Serialization)?;
        debug!("JsonRpcClient: Sending notification: {}", notification_json);

        // Send via channel
        self.outbound_sender
            .send(notification_json)
            .map_err(|_| JsonRpcError::Transport("Outbound channel closed".to_string()))?;

        Ok(())
    }

    /// Clean up all pending requests (e.g., during restart)
    pub async fn cleanup_pending_requests(&mut self) {
        let mut state = self.state.lock().await;
        for (id, sender) in state.pending_requests.drain() {
            debug!("JsonRpcClient: Cleaning up pending request ID {}", id);
            // Try to send a cancellation, but don't wait if the receiver is gone
            let _ = sender.send(JsonRpcResponse {
                jsonrpc: crate::lsp::jsonrpc_utils::JSONRPC_VERSION.to_string(),
                id: Value::Number(serde_json::Number::from(id)),
                result: None,
                error: Some(JsonRpcErrorObject {
                    code: JsonRpcErrorCode::InternalError as i32,
                    message: "Request cancelled due to connection restart".to_string(),
                    data: None,
                }),
            });
        }
    }

    /// Close the connection
    pub async fn close(&mut self) -> Result<(), JsonRpcError> {
        // Clean up all pending requests first
        self.cleanup_pending_requests().await;

        // The transport handler will exit when the channel is closed
        // (which happens when this struct is dropped)
        Ok(())
    }
}