mcp-protocol-sdk 0.5.1

Production-ready Rust SDK for the Model Context Protocol (MCP) with multiple transport support
Documentation
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
//! Simple MCP Server Example
//!
//! This example demonstrates how to create a basic MCP server with a few tools,
//! resources, and prompts. It uses STDIO transport for communication.

use async_trait::async_trait;
use serde_json::{Value, json};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

use mcp_protocol_sdk::{
    core::{
        error::{McpError, McpResult},
        prompt::PromptHandler,
        resource::ResourceHandler,
        tool::ToolHandler,
    },
    protocol::types::{
        Content, GetPromptResult as PromptResult, Prompt as PromptInfo, PromptArgument,
        PromptMessage, Resource as ResourceInfo, ResourceContents, Role, ToolResult,
    },
    server::McpServer,
    server::mcp_server::ServerConfig,
    transport::stdio::StdioServerTransport,
};

// ============================================================================
// Tool Handlers
// ============================================================================

/// A simple calculator tool that adds two numbers
struct CalculatorHandler;

#[async_trait]
impl ToolHandler for CalculatorHandler {
    async fn call(&self, arguments: HashMap<String, Value>) -> McpResult<ToolResult> {
        let a = arguments
            .get("a")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| McpError::Validation("Missing or invalid 'a' parameter".to_string()))?;

        let b = arguments
            .get("b")
            .and_then(|v| v.as_f64())
            .ok_or_else(|| McpError::Validation("Missing or invalid 'b' parameter".to_string()))?;

        let operation = arguments
            .get("operation")
            .and_then(|v| v.as_str())
            .unwrap_or("add");

        let result = match operation {
            "add" => a + b,
            "subtract" => a - b,
            "multiply" => a * b,
            "divide" => {
                if b == 0.0 {
                    return Ok(ToolResult {
                        content: vec![Content::text("Error: Division by zero")],
                        is_error: Some(true),
                        structured_content: None,
                        meta: None,
                    });
                }
                a / b
            }
            _ => {
                return Ok(ToolResult {
                    content: vec![Content::text(format!(
                        "Error: Unknown operation '{operation}'"
                    ))],
                    is_error: Some(true),
                    structured_content: None,
                    meta: None,
                });
            }
        };

        Ok(ToolResult {
            content: vec![Content::text(format!("{a} {operation} {b} = {result}"))],
            is_error: None,
            structured_content: None,
            meta: None,
        })
    }
}

/// A tool that echoes back the input with some formatting
struct EchoHandler;

#[async_trait]
impl ToolHandler for EchoHandler {
    async fn call(&self, arguments: HashMap<String, Value>) -> McpResult<ToolResult> {
        let message = arguments
            .get("message")
            .and_then(|v| v.as_str())
            .unwrap_or("Hello, World!");

        let uppercase = arguments
            .get("uppercase")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let prefix = arguments
            .get("prefix")
            .and_then(|v| v.as_str())
            .unwrap_or("Echo");

        let formatted_message = if uppercase {
            format!("{}: {}", prefix, message.to_uppercase())
        } else {
            format!("{prefix}: {message}")
        };

        Ok(ToolResult {
            content: vec![Content::text(formatted_message)],
            is_error: None,
            structured_content: None,
            meta: None,
        })
    }
}

// ============================================================================
// Resource Handlers
// ============================================================================

/// A simple file system resource handler (simplified for demo)
struct FileSystemHandler {
    files: Arc<RwLock<HashMap<String, String>>>,
}

impl FileSystemHandler {
    fn new() -> Self {
        let mut files = HashMap::new();
        files.insert(
            "file:///demo.txt".to_string(),
            "This is a demo file!".to_string(),
        );
        files.insert(
            "file:///config.json".to_string(),
            r#"{"name": "demo", "version": "1.0"}"#.to_string(),
        );
        files.insert(
            "file:///data.csv".to_string(),
            "name,age\nAlice,30\nBob,25\n".to_string(),
        );

        Self {
            files: Arc::new(RwLock::new(files)),
        }
    }
}

#[async_trait]
impl ResourceHandler for FileSystemHandler {
    async fn read(
        &self,
        uri: &str,
        _params: &HashMap<String, String>,
    ) -> McpResult<Vec<ResourceContents>> {
        let files = self.files.read().await;

        if let Some(content) = files.get(uri) {
            let mime_type = if uri.ends_with(".json") {
                Some("application/json".to_string())
            } else if uri.ends_with(".csv") {
                Some("text/csv".to_string())
            } else {
                Some("text/plain".to_string())
            };

            Ok(vec![ResourceContents::Text {
                uri: uri.to_string(),
                mime_type,
                text: content.clone(),
                meta: None,
            }])
        } else {
            Err(McpError::ResourceNotFound(uri.to_string()))
        }
    }

    async fn list(&self) -> McpResult<Vec<ResourceInfo>> {
        let files = self.files.read().await;

        Ok(files
            .keys()
            .map(|uri| {
                let name = uri.split('/').next_back().unwrap_or(uri);
                let mime_type = if uri.ends_with(".json") {
                    Some("application/json".to_string())
                } else if uri.ends_with(".csv") {
                    Some("text/csv".to_string())
                } else {
                    Some("text/plain".to_string())
                };

                ResourceInfo {
                    uri: uri.clone(),
                    name: name.to_string(),
                    title: Some(format!("Demo file: {name}")),
                    description: Some(format!("Demo file: {name}")),
                    mime_type,
                    annotations: None,
                    size: None,
                    meta: None,
                }
            })
            .collect())
    }

    async fn subscribe(&self, _uri: &str) -> McpResult<()> {
        // In a real implementation, this would set up file watching
        Ok(())
    }

    async fn unsubscribe(&self, _uri: &str) -> McpResult<()> {
        // In a real implementation, this would remove file watching
        Ok(())
    }
}

// ============================================================================
// Prompt Handlers
// ============================================================================

/// A prompt handler that generates code review prompts
struct CodeReviewPromptHandler;

#[async_trait]
impl PromptHandler for CodeReviewPromptHandler {
    async fn get(&self, arguments: HashMap<String, Value>) -> McpResult<PromptResult> {
        let language = arguments
            .get("language")
            .and_then(|v| v.as_str())
            .unwrap_or("any");

        let focus = arguments
            .get("focus")
            .and_then(|v| v.as_str())
            .unwrap_or("general");

        let system_prompt = format!(
            "You are an expert code reviewer specializing in {language} code. Focus on {focus} aspects of code quality."
        );

        let user_prompt = match focus {
            "security" => {
                "Please review this code for security vulnerabilities, potential exploits, and security best practices."
            }
            "performance" => {
                "Please review this code for performance issues, optimization opportunities, and efficiency improvements."
            }
            "style" => {
                "Please review this code for style consistency, readability, and adherence to coding standards."
            }
            _ => {
                "Please provide a comprehensive code review covering functionality, readability, maintainability, and best practices."
            }
        };

        Ok(PromptResult {
            description: Some(format!(
                "Code review prompt for {language} focusing on {focus}"
            )),
            messages: vec![
                PromptMessage {
                    role: Role::User,
                    content: Content::text(system_prompt),
                },
                PromptMessage {
                    role: Role::User,
                    content: Content::text(user_prompt),
                },
            ],
            meta: None,
        })
    }
}

/// A prompt handler that generates documentation prompts
struct DocumentationPromptHandler;

#[async_trait]
impl PromptHandler for DocumentationPromptHandler {
    async fn get(&self, arguments: HashMap<String, Value>) -> McpResult<PromptResult> {
        let doc_type = arguments
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("function");

        let language = arguments
            .get("language")
            .and_then(|v| v.as_str())
            .unwrap_or("any");

        let (system_prompt, user_prompt) = match doc_type {
            "api" => (
                format!(
                    "You are a technical writer specializing in API documentation for {language} applications."
                ),
                "Please generate comprehensive API documentation for the provided code, including endpoints, parameters, responses, and usage examples.",
            ),
            "class" => (
                format!(
                    "You are a technical writer specializing in {language} class documentation."
                ),
                "Please generate detailed class documentation including purpose, methods, properties, usage examples, and relationships with other classes.",
            ),
            "function" => (
                format!(
                    "You are a technical writer specializing in {language} function documentation."
                ),
                "Please generate comprehensive function documentation including purpose, parameters, return values, exceptions, and usage examples.",
            ),
            _ => (
                "You are a technical writer specializing in software documentation.".to_string(),
                "Please generate appropriate documentation for the provided code.",
            ),
        };

        Ok(PromptResult {
            description: Some(format!("Documentation prompt for {language} {doc_type}")),
            messages: vec![
                PromptMessage {
                    role: Role::User,
                    content: Content::text(system_prompt),
                },
                PromptMessage {
                    role: Role::User,
                    content: Content::text(user_prompt),
                },
            ],
            meta: None,
        })
    }
}

// ============================================================================
// Main Server Setup
// ============================================================================

#[tokio::main]
async fn main() -> McpResult<()> {
    // Initialize logging
    #[cfg(feature = "tracing-subscriber")]
    tracing_subscriber::fmt::init();

    // Create server with custom configuration
    let config = ServerConfig {
        max_concurrent_requests: 50,
        request_timeout_ms: 30000,
        validate_requests: true,
        enable_logging: true,
    };

    let mut server = McpServer::with_config(
        "simple-demo-server".to_string(),
        "1.0.0".to_string(),
        config,
    );

    // Add tools
    tracing::info!("Adding tools...");

    server
        .add_tool(
            "calculator".to_string(),
            Some("Perform basic arithmetic operations".to_string()),
            json!({
                "type": "object",
                "properties": {
                    "a": {
                        "type": "number",
                        "description": "First number"
                    },
                    "b": {
                        "type": "number",
                        "description": "Second number"
                    },
                    "operation": {
                        "type": "string",
                        "enum": ["add", "subtract", "multiply", "divide"],
                        "description": "Operation to perform",
                        "default": "add"
                    }
                },
                "required": ["a", "b"]
            }),
            CalculatorHandler,
        )
        .await?;

    server
        .add_tool(
            "echo".to_string(),
            Some("Echo back a message with optional formatting".to_string()),
            json!({
                "type": "object",
                "properties": {
                    "message": {
                        "type": "string",
                        "description": "Message to echo back"
                    },
                    "uppercase": {
                        "type": "boolean",
                        "description": "Convert to uppercase",
                        "default": false
                    },
                    "prefix": {
                        "type": "string",
                        "description": "Prefix to add to the message",
                        "default": "Echo"
                    }
                }
            }),
            EchoHandler,
        )
        .await?;

    // Add resources
    tracing::info!("Adding resources...");

    let fs_handler = FileSystemHandler::new();
    server
        .add_resource_detailed(
            ResourceInfo {
                uri: "file:///".to_string(),
                name: "Demo File System".to_string(),
                title: Some("Demo File System".to_string()),
                description: Some("Demo file system with sample files".to_string()),
                mime_type: Some("inode/directory".to_string()),
                annotations: None,
                size: None,
                meta: None,
            },
            fs_handler,
        )
        .await?;

    // Add prompts
    tracing::info!("Adding prompts...");

    server
        .add_prompt(
            PromptInfo {
                name: "code-review".to_string(),
                description: Some("Generate code review prompts".to_string()),
                title: Some("Code Review Assistant".to_string()),
                meta: None,
                arguments: Some(vec![
                    PromptArgument {
                        name: "language".to_string(),
                        title: Some("Programming Language".to_string()),
                        description: Some("Programming language".to_string()),
                        required: Some(false),
                    },
                    PromptArgument {
                        name: "focus".to_string(),
                        title: Some("Review Focus".to_string()),
                        description: Some(
                            "Review focus (security, performance, style, general)".to_string(),
                        ),
                        required: Some(false),
                    },
                ]),
            },
            CodeReviewPromptHandler,
        )
        .await?;

    server
        .add_prompt(
            PromptInfo {
                name: "documentation".to_string(),
                description: Some("Generate documentation prompts".to_string()),
                title: Some("Documentation Generator".to_string()),
                meta: None,
                arguments: Some(vec![
                    PromptArgument {
                        name: "type".to_string(),
                        title: Some("Documentation Type".to_string()),
                        description: Some("Documentation type (api, class, function)".to_string()),
                        required: Some(false),
                    },
                    PromptArgument {
                        name: "language".to_string(),
                        title: Some("Programming Language".to_string()),
                        description: Some("Programming language".to_string()),
                        required: Some(false),
                    },
                ]),
            },
            DocumentationPromptHandler,
        )
        .await?;

    // Create and start the server with STDIO transport
    tracing::info!("Starting server...");

    let transport = StdioServerTransport::new();
    server.start(transport).await?;

    tracing::info!("Server started successfully! Listening for requests...");

    // Keep the server running until interrupted
    tokio::signal::ctrl_c()
        .await
        .expect("Failed to listen for ctrl+c");

    tracing::info!("Shutting down server...");
    server.stop().await?;
    tracing::info!("Server stopped");

    Ok(())
}