remote-mcp-kernel 0.1.0-alpha.4

A microkernel-based MCP (Model Context Protocol) server with OAuth authentication and multiple transport protocols
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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! Custom MCP Server Example with OAuth 2.0 and DynamoDB
//!
//! This example demonstrates how to create a custom MCP server implementation
//! and use it with the microkernel architecture. It shows how users can extend
//! the framework by implementing their own MCP servers with custom tools and
//! capabilities while leveraging the existing OAuth and storage infrastructure.
//!
//! # Features
//! - Custom MCP server implementation with specialized tools
//! - AWS Cognito OAuth 2.0 authentication
//! - DynamoDB persistent storage for OAuth tokens and client data
//! - MCP over HTTP (streamable)
//! - MCP over Server-Sent Events (SSE)
//! - Microkernel architecture with independent, composable handlers
//!
//! # Custom MCP Server Features
//! The custom server implements:
//! - File system operations (list, read, write files)
//! - System information tools (CPU, memory, disk usage)
//! - Text processing utilities (word count, text search)
//! - Time and date utilities
//!
//! # Required Environment Variables
//! ## Cognito Configuration
//! - `COGNITO_CLIENT_ID`: Your Cognito app client ID
//! - `COGNITO_CLIENT_SECRET`: Your Cognito app client secret (optional for public clients)
//! - `COGNITO_DOMAIN`: Your Cognito domain (e.g., mydomain.auth.us-east-1.amazoncognito.com)
//! - `COGNITO_REGION`: AWS region (e.g., us-east-1)
//! - `COGNITO_USER_POOL_ID`: Your Cognito user pool ID (e.g., us-east-1_XXXXXXXXX)
//! - `COGNITO_SCOPE`: OAuth scopes (default: 'openid email profile phone')
//!
//! ## AWS Configuration (for DynamoDB)
//! - `AWS_ACCESS_KEY_ID`: Your AWS access key ID
//! - `AWS_SECRET_ACCESS_KEY`: Your AWS secret access key
//! - `AWS_REGION`: AWS region (should match COGNITO_REGION)
//!
//! ## Server Configuration
//! - `MCP_HOST`: Server host (default: localhost)
//! - `MCP_PORT`: Server port (default: 8080)
//! - `DYNAMODB_TABLE_NAME`: DynamoDB table name (default: oauth-storage)
//! - `DYNAMODB_CREATE_TABLE`: Whether to auto-create table (default: true)
//!
//! # Usage
//! ```bash
//! # Set environment variables
//! export COGNITO_CLIENT_ID="your_client_id"
//! export COGNITO_CLIENT_SECRET="your_client_secret"
//! export COGNITO_DOMAIN="mydomain.auth.us-east-1.amazoncognito.com"
//! export COGNITO_REGION="us-east-1"
//! export COGNITO_USER_POOL_ID="us-east-1_XXXXXXXXX"
//! export AWS_ACCESS_KEY_ID="your_aws_access_key"
//! export AWS_SECRET_ACCESS_KEY="your_aws_secret_key"
//! export AWS_REGION="us-east-1"
//!
//! # Run the server
//! cargo run --example custom_mcp_server_example
//! ```

use oauth_provider_rs::storage::create_dynamodb_storage;
use oauth_provider_rs::OAuthProvider;
use remote_mcp_kernel::{
    config::{get_cognito_oauth_provider_config, get_cognito_domain, get_cognito_region, get_cognito_user_pool_id, get_bind_socket_addr, get_logging_level, get_server_host, get_server_port, get_server_version, get_cognito_client_id, get_cognito_client_secret, get_cognito_scope}, 
    error::AppResult, 
    handlers::SseHandlerConfig, 
    microkernel::MicrokernelServer,
};
use rmcp::{
    Error as McpError, ServerHandler,
    handler::server::router::tool::ToolRouter,
    handler::server::tool::Parameters,
    model::{CallToolResult, Content, Implementation, ServerCapabilities, ServerInfo},
    tool, tool_handler, tool_router,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::env;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

// Custom MCP Server Implementation
// =============================================================================

/// Custom MCP server with specialized tools for file operations and system utilities
#[derive(Debug, Clone)]
pub struct CustomMcpServer {
    /// MCP tool router for handling tool calls
    tool_router: ToolRouter<Self>,
    /// Server name for identification
    name: String,
}

// Tool parameter definitions
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ListFilesRequest {
    #[schemars(description = "Directory path to list files from")]
    pub path: String,
    #[schemars(description = "Include hidden files")]
    pub include_hidden: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ReadFileRequest {
    #[schemars(description = "File path to read")]
    pub path: String,
    #[schemars(description = "Maximum number of lines to read")]
    pub max_lines: Option<usize>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct WriteFileRequest {
    #[schemars(description = "File path to write to")]
    pub path: String,
    #[schemars(description = "Content to write")]
    pub content: String,
    #[schemars(description = "Append to file instead of overwriting")]
    pub append: Option<bool>,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct WordCountRequest {
    #[schemars(description = "Text to count words in")]
    pub text: String,
}

#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct TextSearchRequest {
    #[schemars(description = "Text to search in")]
    pub text: String,
    #[schemars(description = "Pattern to search for")]
    pub pattern: String,
    #[schemars(description = "Case sensitive search")]
    pub case_sensitive: Option<bool>,
}

// Tool implementations using the tool_router macro
#[tool_router]
impl CustomMcpServer {
    /// Create a new custom MCP server
    pub fn new(name: String) -> Self {
        Self {
            tool_router: Self::tool_router(),
            name,
        }
    }

    /// List files in a directory
    #[tool(description = "List files and directories in the specified path")]
    async fn list_files(
        &self,
        Parameters(req): Parameters<ListFilesRequest>,
    ) -> Result<CallToolResult, McpError> {
        let path = std::path::Path::new(&req.path);

        if !path.exists() {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "Path does not exist: {}",
                req.path
            ))]));
        }

        if !path.is_dir() {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "Path is not a directory: {}",
                req.path
            ))]));
        }

        let mut files = Vec::new();
        let include_hidden = req.include_hidden.unwrap_or(false);

        match std::fs::read_dir(path) {
            Ok(entries) => {
                for entry in entries {
                    match entry {
                        Ok(entry) => {
                            let file_name = entry.file_name().to_string_lossy().to_string();
                            let is_hidden = file_name.starts_with('.');

                            if include_hidden || !is_hidden {
                                let file_type = if entry.path().is_dir() {
                                    "directory"
                                } else {
                                    "file"
                                };
                                files.push(format!("{} ({})", file_name, file_type));
                            }
                        }
                        Err(e) => {
                            return Ok(CallToolResult::error(vec![Content::text(format!(
                                "Error reading directory entry: {}",
                                e
                            ))]));
                        }
                    }
                }
            }
            Err(e) => {
                return Ok(CallToolResult::error(vec![Content::text(format!(
                    "Error reading directory: {}",
                    e
                ))]));
            }
        }

        files.sort();
        let result = files.join("\n");
        Ok(CallToolResult::success(vec![Content::text(result)]))
    }

    /// Read contents of a file
    #[tool(description = "Read the contents of a file")]
    async fn read_file(
        &self,
        Parameters(req): Parameters<ReadFileRequest>,
    ) -> Result<CallToolResult, McpError> {
        let path = std::path::Path::new(&req.path);

        if !path.exists() {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "File does not exist: {}",
                req.path
            ))]));
        }

        if !path.is_file() {
            return Ok(CallToolResult::error(vec![Content::text(format!(
                "Path is not a file: {}",
                req.path
            ))]));
        }

        match std::fs::read_to_string(path) {
            Ok(content) => {
                let result = if let Some(max_lines) = req.max_lines {
                    content
                        .lines()
                        .take(max_lines)
                        .collect::<Vec<_>>()
                        .join("\n")
                } else {
                    content
                };
                Ok(CallToolResult::success(vec![Content::text(result)]))
            }
            Err(e) => Ok(CallToolResult::error(vec![Content::text(format!(
                "Error reading file: {}",
                e
            ))])),
        }
    }

    /// Write content to a file
    #[tool(description = "Write content to a file")]
    async fn write_file(
        &self,
        Parameters(req): Parameters<WriteFileRequest>,
    ) -> Result<CallToolResult, McpError> {
        let path = std::path::Path::new(&req.path);

        // Create parent directories if they don't exist
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                if let Err(e) = std::fs::create_dir_all(parent) {
                    return Ok(CallToolResult::error(vec![Content::text(format!(
                        "Error creating parent directories: {}",
                        e
                    ))]));
                }
            }
        }

        let result = if req.append.unwrap_or(false) {
            std::fs::write(path, &req.content)
        } else {
            std::fs::write(path, &req.content)
        };

        match result {
            Ok(()) => Ok(CallToolResult::success(vec![Content::text(format!(
                "Successfully wrote {} bytes to {}",
                req.content.len(),
                req.path
            ))])),
            Err(e) => Ok(CallToolResult::error(vec![Content::text(format!(
                "Error writing file: {}",
                e
            ))])),
        }
    }

    /// Get system information
    #[tool(description = "Get system information including CPU, memory, and disk usage")]
    async fn get_system_info(&self) -> Result<CallToolResult, McpError> {
        let mut info = Vec::new();

        // Get current timestamp
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        info.push(format!("Timestamp: {}", now));

        // Get current working directory
        if let Ok(cwd) = std::env::current_dir() {
            info.push(format!("Working Directory: {}", cwd.display()));
        }

        // Get environment variables count
        let env_count = std::env::vars().count();
        info.push(format!("Environment Variables: {}", env_count));

        // Get OS information
        info.push(format!("OS: {}", std::env::consts::OS));
        info.push(format!("Architecture: {}", std::env::consts::ARCH));

        let result = info.join("\n");
        Ok(CallToolResult::success(vec![Content::text(result)]))
    }

    /// Count words in text
    #[tool(description = "Count words, lines, and characters in text")]
    async fn count_words(
        &self,
        Parameters(req): Parameters<WordCountRequest>,
    ) -> Result<CallToolResult, McpError> {
        let text = &req.text;
        let lines = text.lines().count();
        let words = text.split_whitespace().count();
        let chars = text.chars().count();
        let bytes = text.len();

        let result = format!(
            "Lines: {}\nWords: {}\nCharacters: {}\nBytes: {}",
            lines, words, chars, bytes
        );

        Ok(CallToolResult::success(vec![Content::text(result)]))
    }

    /// Search for text patterns
    #[tool(description = "Search for patterns in text")]
    async fn search_text(
        &self,
        Parameters(req): Parameters<TextSearchRequest>,
    ) -> Result<CallToolResult, McpError> {
        let text = &req.text;
        let pattern = &req.pattern;
        let case_sensitive = req.case_sensitive.unwrap_or(false);

        let (search_text, search_pattern) = if case_sensitive {
            (text.to_string(), pattern.to_string())
        } else {
            (text.to_lowercase(), pattern.to_lowercase())
        };

        let mut matches = Vec::new();
        for (line_num, line) in search_text.lines().enumerate() {
            if line.contains(&search_pattern) {
                matches.push(format!(
                    "Line {}: {}",
                    line_num + 1,
                    text.lines().nth(line_num).unwrap_or("")
                ));
            }
        }

        let result = if matches.is_empty() {
            format!("No matches found for pattern: {}", pattern)
        } else {
            format!("Found {} matches:\n{}", matches.len(), matches.join("\n"))
        };

        Ok(CallToolResult::success(vec![Content::text(result)]))
    }

    /// Get current date and time
    #[tool(description = "Get current date and time in various formats")]
    async fn get_datetime(&self) -> Result<CallToolResult, McpError> {
        let now = std::time::SystemTime::now();
        let unix_timestamp = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();

        let result = format!(
            "Unix Timestamp: {}\nISO 8601 (approx): {}",
            unix_timestamp,
            // Simple ISO 8601 approximation (not perfect but sufficient for demo)
            chrono::DateTime::from_timestamp(unix_timestamp as i64, 0)
                .unwrap_or_default()
                .format("%Y-%m-%dT%H:%M:%SZ")
        );

        Ok(CallToolResult::success(vec![Content::text(result)]))
    }
}

// Implement the ServerHandler trait for MCP protocol support
#[tool_handler]
impl ServerHandler for CustomMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: Default::default(),
            capabilities: ServerCapabilities::builder()
                .enable_tools()
                .build(),
            server_info: Implementation {
                name: self.name.clone(),
                version: "1.0.0".to_string(),
            },
            instructions: Some("A custom MCP server with file operations, system utilities, and text processing tools".to_string()),
        }
    }
}

// Main application
// =============================================================================

#[tokio::main]
async fn main() -> AppResult<()> {
    // Load environment variables
    dotenv::dotenv().ok();

    // Initialize tracing
    init_tracing()?;

    tracing::info!("Starting Custom MCP Server example with Cognito and DynamoDB storage...");

    // Create Cognito OAuth configuration
    let cognito_config = get_cognito_oauth_provider_config()?;

    // Get DynamoDB configuration
    let table_name =
        env::var("DYNAMODB_TABLE_NAME").unwrap_or_else(|_| "oauth-storage".to_string());
    let create_table = env::var("DYNAMODB_CREATE_TABLE")
        .unwrap_or_else(|_| "true".to_string())
        .parse::<bool>()
        .unwrap_or(true);

    // Log configuration
    log_startup_info(&table_name, create_table);

    // Create DynamoDB storage
    let (storage, client_manager) = create_dynamodb_storage(
        table_name.clone(),
        create_table,
        Some("expires_at".to_string()),
    )
    .await
    .map_err(|e| {
        remote_mcp_kernel::error::AppError::Internal(format!(
            "Failed to create DynamoDB storage: {}",
            e
        ))
    })?;

    // Create Cognito OAuth provider with DynamoDB storage
    let oauth_handler = oauth_provider_rs::CognitoOAuthHandler::new_simple(
        storage,
        client_manager,
        cognito_config,
        get_cognito_domain()?,
        get_cognito_region()?,
        get_cognito_user_pool_id()?,
    );

    let oauth_provider = OAuthProvider::new(oauth_handler, oauth_provider_rs::http_integration::config::OAuthProviderConfig::default());

    // Create custom MCP server
    let custom_mcp_server = CustomMcpServer::new("Custom File & System MCP Server".to_string());

    // Build microkernel with custom MCP server using convenience methods
    let microkernel = MicrokernelServer::new()
        .with_oauth_provider(oauth_provider)
        .with_mcp_streamable_handler(custom_mcp_server.clone())
        .with_mcp_sse_handler(custom_mcp_server, SseHandlerConfig::default());

    // Start the microkernel server
    let bind_address = get_bind_socket_addr()?;
    tracing::info!("🚀 Starting microkernel server on {}", bind_address);
    microkernel.serve(bind_address).await?;

    Ok(())
}

fn init_tracing() -> AppResult<()> {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| get_logging_level().as_str().into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    Ok(())
}

fn log_startup_info(table_name: &str, create_table: bool) {
    println!("🚀 Starting Custom MCP Server example with Cognito and DynamoDB storage...");
    println!("📋 Configuration:");
    println!("  - Architecture: Microkernel (independent handlers)");
    println!("  - MCP Server: Custom implementation with specialized tools");
    println!("  - OAuth Provider: AWS Cognito");
    println!("  - Storage Backend: DynamoDB");
    println!("  - Server: {}:{}", get_server_host(), get_server_port().unwrap_or(8080));
    println!("  - Version: {}", get_server_version());
    println!();

    println!("🔧 Custom MCP Server Tools:");
    println!("  - list_files: List files and directories");
    println!("  - read_file: Read file contents");
    println!("  - write_file: Write content to files");
    println!("  - get_system_info: Get system information");
    println!("  - count_words: Count words, lines, and characters");
    println!("  - search_text: Search for patterns in text");
    println!("  - get_datetime: Get current date and time");
    println!();

    println!("🔐 AWS Cognito Configuration:");
    println!(
        "  - Client ID: {}",
        if get_cognito_client_id().is_ok() {
            "Configured"
        } else {
            "Not configured"
        }
    );
    println!(
        "  - Client Secret: {}",
        match get_cognito_client_secret() {
            Some(secret) if !secret.is_empty() => "Configured",
            _ => "Not configured (Public Client)",
        }
    );
    println!(
        "  - Domain: {}",
        get_cognito_domain().unwrap_or_else(|_| "Not configured".to_string())
    );
    println!(
        "  - Region: {}",
        get_cognito_region().unwrap_or_else(|_| "Not configured".to_string())
    );
    println!(
        "  - User Pool ID: {}",
        get_cognito_user_pool_id().unwrap_or_else(|_| "Not configured".to_string())
    );
    println!("  - Scopes: {}", get_cognito_scope());
    println!();

    println!("🗄️  DynamoDB Storage Configuration:");
    println!("  - Table Name: {}", table_name);
    println!("  - Auto-create Table: {}", create_table);
    println!("  - TTL Attribute: expires_at");
    println!();

    println!("🔧 Handlers:");
    println!("  - OAuth Provider (Cognito authentication & authorization)");
    println!("  - Streamable HTTP Handler (MCP over HTTP with custom server)");
    println!("  - SSE Handler (MCP over SSE with custom server)");
    println!();

    println!("🏗️  Microkernel Architecture:");
    println!("  - Custom MCP server with specialized tools");
    println!("  - Independent handlers that can operate standalone");
    println!("  - Runtime composition of services");
    println!("  - Single responsibility per handler");
    println!("  - Easy testing and maintenance");
    println!();

    println!("🌐 MCP Protocol Endpoints:");
    let host = get_server_host();
    let port = get_server_port().unwrap_or(8080);
    println!(
        "  - HTTP (streamable): http://{}:{}/mcp/http",
        host, port
    );
    println!(
        "  - SSE: http://{}:{}/mcp/sse",
        host, port
    );
    println!(
        "  - SSE Messages: http://{}:{}/mcp/message",
        host, port
    );
    println!();

    println!("🔐 OAuth 2.0 Endpoints:");
    let cognito_domain = get_cognito_domain().unwrap_or_else(|_| "Not configured".to_string());
    println!(
        "  - Authorization: https://{}/oauth2/authorize",
        cognito_domain
    );
    println!(
        "  - Token: https://{}/oauth2/token",
        cognito_domain
    );
    println!(
        "  - JWKS: https://{}/oauth2/jwks",
        cognito_domain
    );
    println!(
        "  - UserInfo: https://{}/oauth2/userInfo",
        cognito_domain
    );
    println!();
}