mcp_core/server/
mod.rs

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
use config::ServerConfig;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{sync::Arc, time::Duration};
use tokio::sync::watch;
use tokio::sync::RwLock;
use tracing::info;

use crate::prompts::{GetPromptRequest, ListPromptsRequest, PromptCapabilities, PromptManager};
use crate::tools::{ToolCapabilities, ToolManager};
use crate::{
    client::types::ServerCapabilities,
    error::McpError,
    logging::{LoggingCapabilities, LoggingManager, SetLevelRequest},
    protocol::types::*,
    protocol::{
        BasicRequestHandler, JsonRpcNotification, Protocol, ProtocolBuilder, ProtocolOptions,
        RequestHandler,
    },
    resource::{ListResourcesRequest, ReadResourceRequest, ResourceCapabilities, ResourceManager},
    tools::{CallToolRequest, ListToolsRequest},
    transport::{stdio::StdioTransport, SseServerTransport, Transport},
};
use tokio::sync::mpsc;

pub mod config;

// Add initialization types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeParams {
    pub protocol_version: String,
    pub capabilities: ClientCapabilities,
    pub client_info: ClientInfo,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeResult {
    pub protocol_version: String,
    pub capabilities: ServerCapabilities,
    pub server_info: InitializeServerInfo,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct InitializeServerInfo {
    pub name: String,
    pub version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientCapabilities {
    pub roots: Option<RootsCapabilities>,
    pub sampling: Option<SamplingCapabilities>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RootsCapabilities {
    pub list_changed: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SamplingCapabilities {}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientInfo {
    pub name: String,
    pub version: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerInfo {
    pub name: String,
    pub version: String,
}

// Add server state enum
#[derive(Debug, Clone, Copy, PartialEq)]
enum ServerState {
    Created,
    Initializing,
    Running,
    ShuttingDown,
}

pub struct McpServer<H>
where
    H: RequestHandler + Send + Sync + 'static,
{
    pub handler: Arc<H>,
    pub config: ServerConfig,
    pub resource_manager: Arc<ResourceManager>,
    pub tool_manager: Arc<ToolManager>,
    pub prompt_manager: Arc<PromptManager>,
    pub logging_manager: Arc<tokio::sync::Mutex<LoggingManager>>,
    notification_tx: mpsc::Sender<JsonRpcNotification>,
    notification_rx: Option<mpsc::Receiver<JsonRpcNotification>>, // Make this Option
    state: Arc<(watch::Sender<ServerState>, watch::Receiver<ServerState>)>,
    supported_versions: Vec<String>,
    client_capabilities: Arc<RwLock<Option<ClientCapabilities>>>,
}

impl<H> McpServer<H>
where
    H: RequestHandler + Send + Sync + 'static,
{
    pub fn new(config: ServerConfig, handler: H) -> Self {
        let (notification_tx, notification_rx) = mpsc::channel(100);
        let (state_tx, state_rx) = watch::channel(ServerState::Created);

        Self {
            handler: Arc::new(handler),
            config: config.clone(),
            resource_manager: Arc::new(ResourceManager::new(ResourceCapabilities {
                subscribe: false,
                list_changed: false,
            })),
            tool_manager: Arc::new(ToolManager::new(ToolCapabilities {
                list_changed: false,
            })),
            prompt_manager: Arc::new(PromptManager::new(PromptCapabilities {
                list_changed: false,
            })),
            logging_manager: Arc::new(tokio::sync::Mutex::new(LoggingManager::new())),
            notification_tx,
            notification_rx: Some(notification_rx),
            state: Arc::new((state_tx, state_rx)),
            supported_versions: vec!["1.0".to_string()],
            client_capabilities: Arc::new(RwLock::new(None)),
        }
    }

    pub async fn process_request(
        &self,
        method: &str,
        params: Option<Value>,
    ) -> Result<Value, McpError> {
        self.handler.handle_request(method, params).await
    }

    pub async fn run_stdio_transport(&mut self) -> Result<(), McpError> {
        let transport = StdioTransport::new(Some(1024));
        self.run_transport(transport).await
    }

    pub async fn run_sse_transport(&mut self) -> Result<(), McpError> {
        let transport = SseServerTransport::new_local(
            self.config.server.host.clone(),
            self.config.server.port,
            1024, // Buffer size
        );
        self.run_transport(transport).await
    }

    pub async fn run_unix_transport(&mut self) -> Result<(), McpError> {
        tracing::info!("Starting Unix transport");
        Ok(())
    }

    async fn run_transport<T: Transport>(&mut self, transport: T) -> Result<(), McpError> {
        // Take ownership of notification receiver
        let notification_rx = self.notification_rx.take().ok_or_else(|| {
            McpError::InternalError("Notification receiver already taken".to_string())
        })?;

        // Create shutdown channel
        let (shutdown_tx, mut shutdown_rx) = tokio::sync::mpsc::channel::<()>(1);

        // Clone Arc for shutdown handler
        let state = Arc::clone(&self.state);

        // Spawn task to watch server state and send shutdown signal
        tokio::spawn(async move {
            loop {
                if *state.1.borrow() == ServerState::ShuttingDown {
                    let _ = shutdown_tx.send(()).await;
                    break;
                }
                tokio::time::sleep(Duration::from_millis(100)).await;
            }
        });

        // Build protocol

        let resource_manager = Arc::clone(&self.resource_manager);
        let resource_manager2 = Arc::clone(&self.resource_manager);
        let resource_manager3 = Arc::clone(&self.resource_manager);
        let tool_manager = Arc::clone(&self.tool_manager);
        let tool_manager2 = Arc::clone(&self.tool_manager);
        let prompt_manager = Arc::clone(&self.prompt_manager);
        let prompt_manager2 = Arc::clone(&self.prompt_manager);

        let mut protocol = Protocol::builder(Some(ProtocolOptions {
            enforce_strict_capabilities: false,
        }))
        .with_request_handler(
            "initialize",
            Box::new(|req, _extra| {
                Box::pin(async move {
                    let params: InitializeParams =
                        serde_json::from_value(req.params.unwrap_or_default())
                            .map_err(|_| McpError::InvalidParams)?;

                    let result = InitializeResult {
                        protocol_version: "2024-11-05".to_string(),
                        capabilities: ServerCapabilities {
                            logging: Some(LoggingCapabilities {}),
                            prompts: Some(PromptCapabilities {
                                list_changed: false,
                            }),
                            resources: Some(ResourceCapabilities {
                                subscribe: false,
                                list_changed: false,
                            }),
                            tools: Some(ToolCapabilities {
                                list_changed: false,
                            }),
                        },
                        server_info: InitializeServerInfo {
                            name: "test-server".to_string(),
                            version: "1.0.0".to_string(),
                        },
                    };

                    Ok(serde_json::to_value(result).unwrap())
                })
            }),
        )
        .with_request_handler(
            "resources/list",
            Box::new(move |req, _extra| {
                let resource_manager = Arc::clone(&resource_manager);
                Box::pin(async move {
                    let params: ListResourcesRequest = req
                        .params
                        .map(|params| serde_json::from_value(params))
                        .transpose()
                        .map_err(|_| McpError::InvalidParams)?
                        .unwrap_or_default();

                    let resources_list = resource_manager.list_resources(params.cursor).await?;
                    Ok(serde_json::to_value(resources_list).unwrap())
                })
            }),
        )
        .with_request_handler(
            "resources/read",
            Box::new(move |req, _extra| {
                let resource_manager = Arc::clone(&resource_manager2);
                Box::pin(async move {
                    let params: ReadResourceRequest =
                        serde_json::from_value(req.params.unwrap_or_default())
                            .map_err(|_| McpError::InvalidParams)?;
                    let resource = resource_manager.read_resource(&params.uri).await?;
                    Ok(serde_json::to_value(resource).unwrap())
                })
            }),
        )
        .with_request_handler(
            "resources/templates/list",
            Box::new(move |_req, _extra| {
                let resource_manager = Arc::clone(&resource_manager3);
                Box::pin(async move {
                    let templates_list = resource_manager.list_templates().await?;
                    Ok(serde_json::to_value(templates_list).unwrap())
                })
            }),
        )
        .with_request_handler(
            "tools/list",
            Box::new(move |req, _extra| {
                let tool_manager = Arc::clone(&tool_manager);
                Box::pin(async move {
                    let params: ListToolsRequest = req
                        .params
                        .map(|params| serde_json::from_value(params))
                        .transpose()
                        .map_err(|_| McpError::InvalidParams)?
                        .unwrap_or_default();

                    let tools_list = tool_manager.list_tools(params.cursor).await?;
                    Ok(serde_json::to_value(tools_list).unwrap())
                })
            }),
        )
        .with_request_handler(
            "tools/call",
            Box::new(move |req, _extra| {
                let tool_manager = Arc::clone(&tool_manager2);
                Box::pin(async move {
                    let params: CallToolRequest =
                        serde_json::from_value(req.params.unwrap_or_default())
                            .map_err(|_| McpError::InvalidParams)?;
                    let result = tool_manager
                        .call_tool(&params.name, params.arguments)
                        .await?;
                    Ok(serde_json::to_value(result).unwrap())
                })
            }),
        )
        .with_request_handler(
            "prompts/list",
            Box::new(move |req, _extra| {
                let prompt_manager = Arc::clone(&prompt_manager);
                Box::pin(async move {
                    let params: ListPromptsRequest = req
                        .params
                        .map(|params| serde_json::from_value(params))
                        .transpose()
                        .map_err(|_| McpError::InvalidParams)?
                        .unwrap_or_default();

                    let prompts_list = prompt_manager.list_prompts(params.cursor).await?;
                    Ok(serde_json::to_value(prompts_list).unwrap())
                })
            }),
        )
        .with_request_handler(
            "prompts/get",
            Box::new(move |req, _extra| {
                let prompt_manager = Arc::clone(&prompt_manager2);
                Box::pin(async move {
                    let params: GetPromptRequest =
                        serde_json::from_value(req.params.unwrap_or_default())
                            .map_err(|_| McpError::InvalidParams)?;
                    let prompt = prompt_manager
                        .get_prompt(&params.name, params.arguments)
                        .await?;
                    Ok(serde_json::to_value(prompt).unwrap())
                })
            }),
        )
        .build();

        // Connect transport
        let protocol_handle = protocol.connect(transport).await?;

        info!("Server running and ready to handle requests");

        // Wait for shutdown signal
        shutdown_rx.recv().await;

        // Clean shutdown
        protocol_handle.close().await?;
        info!("Server shutting down");
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::transport::{TransportChannels, TransportCommand, TransportEvent};

    use super::*;
    use async_trait::async_trait;
    use serde_json::json;
    use std::time::Duration;
    use tokio::time::sleep;

    struct MockTransport {
        _channels: Option<TransportChannels>,
    }

    impl MockTransport {
        fn new() -> Self {
            Self { _channels: None }
        }
    }

    #[async_trait]
    impl Transport for MockTransport {
        async fn start(&mut self) -> Result<TransportChannels, McpError> {
            let (command_tx, mut command_rx) = mpsc::channel(32);
            let (event_tx, event_rx) = mpsc::channel(32);

            let channels = TransportChannels {
                cmd_tx: command_tx,
                event_rx: Arc::new(tokio::sync::Mutex::new(event_rx)),
            };

            // Spawn a task to handle commands
            tokio::spawn(async move {
                while let Some(cmd) = command_rx.recv().await {
                    match cmd {
                        TransportCommand::SendMessage(JsonRpcMessage::Request(req)) => {
                            if req.method == "initialize" {
                                // Simulate client responding to initialize request
                                let response = JsonRpcMessage::Response(JsonRpcResponse {
                                    jsonrpc: "2.0".to_string(),
                                    id: req.id,
                                    result: Some(json!({
                                        "protocol_version": "1.0",
                                        "capabilities": {
                                            "roots": { "listChanged": true }
                                        },
                                        "client_info": {
                                            "name": "test-client",
                                            "version": "1.0.0"
                                        }
                                    })),
                                    error: None,
                                });

                                event_tx
                                    .send(TransportEvent::Message(response))
                                    .await
                                    .unwrap();
                            }
                        }
                        TransportCommand::Close => break,
                        _ => {}
                    }
                }
                event_tx.send(TransportEvent::Closed).await.unwrap();
            });

            self._channels = Some(channels.clone());
            Ok(channels)
        }
    }

    struct MockHandler;

    #[async_trait]
    impl RequestHandler for MockHandler {
        async fn handle_request(
            &self,
            method: &str,
            params: Option<Value>,
        ) -> Result<Value, McpError> {
            match method {
                "test.echo" => Ok(params.unwrap_or(Value::Null)),
                _ => Ok(Value::Null),
            }
        }

        async fn handle_notification(
            &self,
            _method: &str,
            _params: Option<Value>,
        ) -> Result<(), McpError> {
            Ok(())
        }

        fn get_capabilities(&self) -> crate::protocol::ServerCapabilities {
            crate::protocol::ServerCapabilities {
                name: "test-server".to_string(),
                version: "1.0.0".to_string(),
                protocol_version: "1.0".to_string(),
                capabilities: vec!["test.echo".to_string()],
            }
        }
    }

    #[tokio::test]
    async fn test_run_transport() {
        let mut config = ServerConfig::default();
        config.server.host = "localhost".to_string();
        config.server.port = 8080;

        // Create server instance
        let mut server = McpServer::new(config, MockHandler);

        // Get state and notification sender before moving server
        let notification_tx = server.notification_tx.clone();
        let state = Arc::clone(&server.state);

        // Spawn server task
        let server_handle = tokio::spawn(async move {
            let transport = MockTransport::new();
            server.run_transport(transport).await
        });

        // Give the server a moment to start
        sleep(Duration::from_millis(100)).await;

        // Test sending a notification
        let test_notification = JsonRpcNotification {
            jsonrpc: "2.0".to_string(),
            method: "test.notification".to_string(),
            params: Some(json!({"message": "test"})),
        };
        notification_tx.send(test_notification).await.unwrap();

        // Give time for notification processing
        sleep(Duration::from_millis(100)).await;

        // Use the state we cloned earlier instead of trying to get it from server_handle
        let (state_tx, _): &(watch::Sender<ServerState>, watch::Receiver<ServerState>) = &*state;

        // Trigger shutdown
        state_tx.send(ServerState::ShuttingDown).unwrap();

        // Wait for server to shut down
        match tokio::time::timeout(Duration::from_secs(1), server_handle).await {
            Ok(result) => {
                assert!(result.unwrap().is_ok(), "Server should shut down cleanly");
            }
            Err(_) => panic!("Server did not shut down within timeout period"),
        }
    }

    #[tokio::test]
    async fn test_protocol_messages() {
        let mut config = ServerConfig::default();
        config.server.host = "localhost".to_string();
        config.server.port = 8080;

        let mut server = McpServer::new(config, MockHandler);

        // Get notification sender and state before moving server
        let notification_tx = server.notification_tx.clone();
        let state = Arc::clone(&server.state);

        // Spawn server with mock transport
        let server_handle = tokio::spawn(async move {
            let transport = MockTransport::new();
            server.run_transport(transport).await
        });

        // Wait for server to start
        sleep(Duration::from_millis(100)).await;

        // Test sending different types of notifications
        let notifications = vec![
            JsonRpcNotification {
                jsonrpc: "2.0".to_string(),
                method: "resource.changed".to_string(),
                params: Some(json!({
                    "path": "/test/resource",
                    "type": "modified"
                })),
            },
            JsonRpcNotification {
                jsonrpc: "2.0".to_string(),
                method: "tool.executed".to_string(),
                params: Some(json!({
                    "tool": "test-tool",
                    "status": "success"
                })),
            },
        ];

        for notification in notifications {
            notification_tx.send(notification).await.unwrap();
            sleep(Duration::from_millis(50)).await;
        }

        // Use cloned state
        let (state_tx, _): &(watch::Sender<ServerState>, watch::Receiver<ServerState>) = &*state;
        state_tx.send(ServerState::ShuttingDown).unwrap();

        // Verify clean shutdown
        match tokio::time::timeout(Duration::from_secs(1), server_handle).await {
            Ok(result) => {
                assert!(result.unwrap().is_ok(), "Server should shut down cleanly");
            }
            Err(_) => panic!("Server did not shut down within timeout period"),
        }
    }
}