tcl-mcp-server 0.1.2

A Model Context Protocol (MCP) server that provides TCL (Tool Command Language) execution capabilities with namespace-based tool management and versioning.
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
# MCP Server Registration Security & Performance Analysis

## 🔐 Security Analysis

### Threat Model

#### Attack Vectors
1. **Malicious MCP Server Registration**
   - Unauthorized server registration
   - Server impersonation
   - Credential theft/exposure

2. **Tool Execution Attacks**
   - Command injection via parameters
   - Resource exhaustion (DoS)
   - Privilege escalation

3. **Network-Based Attacks**
   - Man-in-the-middle (MITM)
   - Certificate manipulation
   - Protocol downgrade attacks

4. **Data Persistence Attacks**
   - Registry corruption
   - Credential extraction
   - Metadata manipulation

### Security Controls

#### 1. Authentication & Authorization

```rust
// Strong authentication framework
#[derive(Debug, Clone)]
pub struct McpSecurityPolicy {
    /// Require authentication for all MCP operations
    pub require_auth: bool,
    /// Minimum credential strength requirements
    pub credential_policy: CredentialPolicy,
    /// Rate limiting configuration
    pub rate_limits: RateLimitConfig,
    /// Allowed connection types
    pub allowed_transports: Vec<TransportType>,
    /// Certificate validation requirements
    pub cert_validation: CertValidationPolicy,
}

#[derive(Debug, Clone)]
pub struct CredentialPolicy {
    /// Minimum API key length
    pub min_key_length: usize,
    /// Require HTTPS for credential transmission
    pub require_secure_transport: bool,
    /// Credential rotation interval
    pub rotation_interval: Option<Duration>,
    /// Allowed authentication methods
    pub allowed_methods: Vec<AuthMethod>,
}

impl McpSecurityPolicy {
    /// Validate MCP server registration request
    pub fn validate_registration(&self, request: &McpAddRequest) -> Result<()> {
        // 1. Validate server ID format and uniqueness
        self.validate_server_id(&request.server_id)?;
        
        // 2. Validate connection security
        self.validate_connection_security(&request.connection)?;
        
        // 3. Validate authentication configuration
        if let Some(ref auth) = request.auth {
            self.validate_auth_config(auth)?;
        } else if self.require_auth {
            return Err(anyhow!("Authentication required but not provided"));
        }
        
        // 4. Validate transport security
        self.validate_transport_security(&request.connection)?;
        
        Ok(())
    }
    
    fn validate_server_id(&self, server_id: &str) -> Result<()> {
        // Server ID security validation
        if server_id.len() < 3 || server_id.len() > 64 {
            return Err(anyhow!("Server ID must be 3-64 characters"));
        }
        
        // Alphanumeric with hyphens/underscores only
        if !server_id.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_') {
            return Err(anyhow!("Server ID contains invalid characters"));
        }
        
        // Prevent reserved names
        let reserved = ["system", "admin", "root", "bin", "sbin", "mcp"];
        if reserved.contains(&server_id) {
            return Err(anyhow!("Server ID '{}' is reserved", server_id));
        }
        
        Ok(())
    }
    
    fn validate_connection_security(&self, config: &McpConnectionConfig) -> Result<()> {
        match config {
            McpConnectionConfig::Http { url, verify_ssl, .. } => {
                if url.starts_with("http://") && *verify_ssl {
                    return Err(anyhow!("HTTP connections not allowed with SSL verification"));
                }
                if !url.starts_with("https://") && self.require_auth {
                    return Err(anyhow!("HTTPS required for authenticated connections"));
                }
            }
            McpConnectionConfig::WebSocket { url, verify_ssl, .. } => {
                if url.starts_with("ws://") && *verify_ssl {
                    return Err(anyhow!("WS connections not allowed with SSL verification"));
                }
                if !url.starts_with("wss://") && self.require_auth {
                    return Err(anyhow!("WSS required for authenticated connections"));
                }
            }
            McpConnectionConfig::Stdio { command, .. } => {
                // Validate command path to prevent execution of arbitrary binaries
                self.validate_stdio_command(command)?;
            }
        }
        Ok(())
    }
    
    fn validate_stdio_command(&self, command: &str) -> Result<()> {
        use std::path::Path;
        
        let path = Path::new(command);
        
        // Must be absolute path or whitelisted command
        if !path.is_absolute() {
            let allowed_commands = ["node", "python", "python3", "npm", "npx"];
            if !allowed_commands.contains(&command) {
                return Err(anyhow!("Relative command paths not allowed: {}", command));
            }
        }
        
        // Check if command exists and is executable
        if path.is_absolute() && !path.exists() {
            return Err(anyhow!("Command not found: {}", command));
        }
        
        Ok(())
    }
}
```

#### 2. Credential Protection

```rust
// Secure credential storage
pub struct CredentialManager {
    keyring: Box<dyn KeyringProvider>,
    encryption: Box<dyn EncryptionProvider>,
}

impl CredentialManager {
    /// Store credentials securely
    pub async fn store_credentials(
        &self, 
        server_id: &str, 
        auth: &McpAuthConfig
    ) -> Result<()> {
        let credential_key = format!("mcp_server_{}", server_id);
        
        match auth {
            McpAuthConfig::ApiKey { key, .. } => {
                let encrypted = self.encryption.encrypt(key.as_bytes())?;
                self.keyring.store(&credential_key, &encrypted).await?;
            }
            McpAuthConfig::BasicAuth { username, password } => {
                let credentials = format!("{}:{}", username, password);
                let encrypted = self.encryption.encrypt(credentials.as_bytes())?;
                self.keyring.store(&credential_key, &encrypted).await?;
            }
            McpAuthConfig::Bearer { token } => {
                let encrypted = self.encryption.encrypt(token.as_bytes())?;
                self.keyring.store(&credential_key, &encrypted).await?;
            }
            McpAuthConfig::OAuth2 { client_secret, refresh_token, .. } => {
                let secrets = serde_json::json!({
                    "client_secret": client_secret,
                    "refresh_token": refresh_token
                });
                let encrypted = self.encryption.encrypt(secrets.to_string().as_bytes())?;
                self.keyring.store(&credential_key, &encrypted).await?;
            }
            McpAuthConfig::None => {
                // No credentials to store
            }
        }
        
        Ok(())
    }
    
    /// Retrieve credentials securely
    pub async fn retrieve_credentials(&self, server_id: &str) -> Result<Option<McpAuthConfig>> {
        let credential_key = format!("mcp_server_{}", server_id);
        
        if let Some(encrypted) = self.keyring.retrieve(&credential_key).await? {
            let decrypted = self.encryption.decrypt(&encrypted)?;
            // Reconstruct auth config from decrypted data
            // Implementation depends on storage format
            todo!("Implement credential reconstruction")
        } else {
            Ok(None)
        }
    }
}

// Platform-specific keyring providers
trait KeyringProvider: Send + Sync {
    async fn store(&self, key: &str, value: &[u8]) -> Result<()>;
    async fn retrieve(&self, key: &str) -> Result<Option<Vec<u8>>>;
    async fn delete(&self, key: &str) -> Result<bool>;
}

trait EncryptionProvider: Send + Sync {
    fn encrypt(&self, data: &[u8]) -> Result<Vec<u8>>;
    fn decrypt(&self, encrypted: &[u8]) -> Result<Vec<u8>>;
}
```

#### 3. Parameter Sanitization

```rust
// Input validation and sanitization
pub struct ParameterSanitizer {
    max_string_length: usize,
    max_array_size: usize,
    max_object_depth: usize,
    allowed_types: HashSet<String>,
}

impl ParameterSanitizer {
    /// Sanitize parameters before sending to MCP server
    pub fn sanitize_params(&self, params: &mut serde_json::Value) -> Result<()> {
        self.sanitize_value(params, 0)?;
        Ok(())
    }
    
    fn sanitize_value(&self, value: &mut serde_json::Value, depth: usize) -> Result<()> {
        if depth > self.max_object_depth {
            return Err(anyhow!("Maximum object depth exceeded"));
        }
        
        match value {
            serde_json::Value::String(s) => {
                if s.len() > self.max_string_length {
                    *s = s.chars().take(self.max_string_length).collect();
                }
                // Remove potentially dangerous characters
                *s = s.replace(['\0', '\x01'..='\x08', '\x0B', '\x0C', '\x0E'..='\x1F'], "");
            }
            serde_json::Value::Array(arr) => {
                if arr.len() > self.max_array_size {
                    arr.truncate(self.max_array_size);
                }
                for item in arr.iter_mut() {
                    self.sanitize_value(item, depth + 1)?;
                }
            }
            serde_json::Value::Object(obj) => {
                for value in obj.values_mut() {
                    self.sanitize_value(value, depth + 1)?;
                }
            }
            _ => {} // Numbers, booleans, null are safe as-is
        }
        
        Ok(())
    }
}
```

#### 4. Audit Logging

```rust
// Comprehensive audit logging
#[derive(Debug, Serialize)]
pub struct AuditEvent {
    pub timestamp: DateTime<Utc>,
    pub event_type: AuditEventType,
    pub server_id: Option<String>,
    pub tool_name: Option<String>,
    pub user_context: Option<String>,
    pub source_ip: Option<String>,
    pub success: bool,
    pub error_message: Option<String>,
    pub execution_time_ms: Option<u64>,
    pub parameters_hash: Option<String>, // Hash of parameters, not actual values
}

#[derive(Debug, Serialize)]
pub enum AuditEventType {
    ServerRegistration,
    ServerDeregistration,
    ToolExecution,
    ToolDiscovery,
    HealthCheck,
    AuthenticationFailure,
    RateLimitExceeded,
    ConnectionError,
}

pub struct AuditLogger {
    log_file: Arc<Mutex<File>>,
    buffer: Arc<Mutex<Vec<AuditEvent>>>,
    flush_interval: Duration,
}

impl AuditLogger {
    pub async fn log_event(&self, event: AuditEvent) {
        let mut buffer = self.buffer.lock().await;
        buffer.push(event);
        
        // Flush if buffer is full
        if buffer.len() >= 100 {
            self.flush_buffer(&mut buffer).await;
        }
    }
    
    async fn flush_buffer(&self, buffer: &mut Vec<AuditEvent>) {
        let mut log_file = self.log_file.lock().await;
        for event in buffer.drain(..) {
            if let Ok(json) = serde_json::to_string(&event) {
                writeln!(log_file, "{}", json).ok();
            }
        }
        log_file.flush().ok();
    }
}
```

## ⚡ Performance Analysis

### Connection Pool Performance

#### Metrics Collection

```rust
#[derive(Debug, Clone)]
pub struct PerformanceMetrics {
    // Connection metrics
    pub connection_pool_size: usize,
    pub active_connections: usize,
    pub connection_create_time_ms: f64,
    pub connection_reuse_rate: f64,
    
    // Execution metrics
    pub avg_execution_time_ms: f64,
    pub p95_execution_time_ms: f64,
    pub p99_execution_time_ms: f64,
    pub success_rate: f64,
    pub error_rate: f64,
    pub timeout_rate: f64,
    
    // Resource metrics
    pub memory_usage_mb: f64,
    pub cpu_usage_percent: f64,
    pub network_bytes_sent: u64,
    pub network_bytes_received: u64,
    
    // Cache metrics
    pub cache_hit_rate: f64,
    pub cache_size_mb: f64,
    pub cache_eviction_rate: f64,
}

pub struct PerformanceMonitor {
    metrics_history: VecDeque<(DateTime<Utc>, PerformanceMetrics)>,
    execution_times: VecDeque<Duration>,
    connection_pool: Arc<McpClientPool>,
}

impl PerformanceMonitor {
    /// Collect current performance metrics
    pub async fn collect_metrics(&mut self) -> PerformanceMetrics {
        let pool_stats = self.connection_pool.get_statistics().await;
        let system_metrics = self.collect_system_metrics();
        
        // Calculate execution time percentiles
        let mut times: Vec<f64> = self.execution_times.iter()
            .map(|d| d.as_millis() as f64)
            .collect();
        times.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        
        let avg_time = if !times.is_empty() {
            times.iter().sum::<f64>() / times.len() as f64
        } else {
            0.0
        };
        
        let p95_time = if !times.is_empty() {
            let idx = (times.len() as f64 * 0.95) as usize;
            times.get(idx).copied().unwrap_or(0.0)
        } else {
            0.0
        };
        
        let p99_time = if !times.is_empty() {
            let idx = (times.len() as f64 * 0.99) as usize;
            times.get(idx).copied().unwrap_or(0.0)
        } else {
            0.0
        };
        
        let metrics = PerformanceMetrics {
            connection_pool_size: pool_stats.total_servers,
            active_connections: pool_stats.total_connections as usize,
            connection_create_time_ms: 0.0, // TODO: Track this
            connection_reuse_rate: self.calculate_reuse_rate(&pool_stats),
            
            avg_execution_time_ms: avg_time,
            p95_execution_time_ms: p95_time,
            p99_execution_time_ms: p99_time,
            success_rate: self.calculate_success_rate(&pool_stats),
            error_rate: self.calculate_error_rate(&pool_stats),
            timeout_rate: 0.0, // TODO: Track timeouts separately
            
            memory_usage_mb: system_metrics.memory_mb,
            cpu_usage_percent: system_metrics.cpu_percent,
            network_bytes_sent: system_metrics.network_sent,
            network_bytes_received: system_metrics.network_received,
            
            cache_hit_rate: 0.0, // TODO: Implement cache metrics
            cache_size_mb: 0.0,
            cache_eviction_rate: 0.0,
        };
        
        // Store in history
        self.metrics_history.push_back((Utc::now(), metrics.clone()));
        
        // Keep only last 1000 entries
        if self.metrics_history.len() > 1000 {
            self.metrics_history.pop_front();
        }
        
        metrics
    }
    
    fn calculate_reuse_rate(&self, stats: &McpPoolStatistics) -> f64 {
        if stats.total_connections > 0 {
            (stats.total_connections as f64 - stats.total_servers as f64) / stats.total_connections as f64
        } else {
            0.0
        }
    }
    
    fn calculate_success_rate(&self, stats: &McpPoolStatistics) -> f64 {
        let total = stats.total_successes + stats.total_errors;
        if total > 0 {
            stats.total_successes as f64 / total as f64
        } else {
            1.0
        }
    }
    
    fn calculate_error_rate(&self, stats: &McpPoolStatistics) -> f64 {
        let total = stats.total_successes + stats.total_errors;
        if total > 0 {
            stats.total_errors as f64 / total as f64
        } else {
            0.0
        }
    }
    
    fn collect_system_metrics(&self) -> SystemMetrics {
        // Platform-specific system metrics collection
        SystemMetrics {
            memory_mb: 0.0, // TODO: Implement
            cpu_percent: 0.0, // TODO: Implement
            network_sent: 0, // TODO: Implement
            network_received: 0, // TODO: Implement
        }
    }
}

struct SystemMetrics {
    memory_mb: f64,
    cpu_percent: f64,
    network_sent: u64,
    network_received: u64,
}
```

### Performance Optimization Strategies

#### 1. Connection Pooling Optimization

```rust
impl McpClientPool {
    /// Optimize pool based on usage patterns
    pub async fn optimize_pool(&mut self) {
        let stats = self.get_statistics().await;
        
        // Adjust pool sizes based on usage
        for entry in self.metadata.iter() {
            let server_id = entry.key();
            let metadata = entry.value();
            
            let usage_rate = metadata.connection_count.load(Ordering::Relaxed) as f64 
                / (Utc::now().signed_duration_since(metadata.created_at).num_seconds() as f64 + 1.0);
            
            // If usage is low, consider reducing pool size
            if usage_rate < 0.1 {
                // Mark for potential cleanup
                self.schedule_connection_cleanup(server_id).await;
            }
            
            // If error rate is high, implement circuit breaker
            let error_rate = metadata.error_count.load(Ordering::Relaxed) as f64 
                / (metadata.connection_count.load(Ordering::Relaxed) as f64 + 1.0);
            
            if error_rate > 0.5 {
                self.activate_circuit_breaker(server_id).await;
            }
        }
    }
    
    async fn schedule_connection_cleanup(&self, server_id: &str) {
        // Implementation for cleaning up underused connections
    }
    
    async fn activate_circuit_breaker(&self, server_id: &str) {
        // Implementation for circuit breaker pattern
    }
}
```

#### 2. Caching Strategy

```rust
pub struct McpResponseCache {
    cache: Arc<Mutex<lru::LruCache<CacheKey, CacheEntry>>>,
    ttl: Duration,
    max_size: usize,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq)]
struct CacheKey {
    server_id: String,
    tool_name: String,
    params_hash: u64, // Hash of parameters for cache key
}

#[derive(Debug, Clone)]
struct CacheEntry {
    response: String,
    created_at: DateTime<Utc>,
    hit_count: AtomicU64,
}

impl McpResponseCache {
    /// Check if response can be cached (idempotent operations only)
    pub fn is_cacheable(&self, tool_name: &str, params: &serde_json::Value) -> bool {
        // Only cache read-only operations
        let readonly_tools = ["get", "list", "search", "query", "info", "status"];
        readonly_tools.iter().any(|&pattern| tool_name.contains(pattern)) &&
        !self.has_mutable_params(params)
    }
    
    fn has_mutable_params(&self, params: &serde_json::Value) -> bool {
        // Check for parameters that suggest mutation
        if let Some(obj) = params.as_object() {
            for key in obj.keys() {
                let key_lower = key.to_lowercase();
                if key_lower.contains("write") || 
                   key_lower.contains("update") || 
                   key_lower.contains("delete") || 
                   key_lower.contains("create") {
                    return true;
                }
            }
        }
        false
    }
    
    /// Get cached response if available and not expired
    pub async fn get(&self, key: &CacheKey) -> Option<String> {
        let mut cache = self.cache.lock().await;
        
        if let Some(entry) = cache.get(key) {
            if Utc::now().signed_duration_since(entry.created_at) < 
               chrono::Duration::from_std(self.ttl).unwrap() {
                entry.hit_count.fetch_add(1, Ordering::Relaxed);
                return Some(entry.response.clone());
            } else {
                // Expired, remove from cache
                cache.pop(key);
            }
        }
        
        None
    }
    
    /// Store response in cache
    pub async fn put(&self, key: CacheKey, response: String) {
        let mut cache = self.cache.lock().await;
        
        let entry = CacheEntry {
            response,
            created_at: Utc::now(),
            hit_count: AtomicU64::new(0),
        };
        
        cache.put(key, entry);
    }
}
```

### Performance Benchmarks

Expected performance characteristics based on design:

| Metric | Target | Acceptable | Poor |
|--------|--------|------------|------|
| Tool execution latency (P95) | < 100ms | < 500ms | > 1s |
| Connection establishment | < 50ms | < 200ms | > 500ms |
| Memory usage per connection | < 1MB | < 5MB | > 10MB |
| Cache hit rate (read operations) | > 80% | > 60% | < 40% |
| Error rate | < 1% | < 5% | > 10% |
| Connection reuse rate | > 90% | > 70% | < 50% |

### Load Testing Strategy

```rust
#[cfg(test)]
mod performance_tests {
    use super::*;
    
    #[tokio::test]
    async fn test_concurrent_tool_execution() {
        let pool = McpClientPool::new(McpPoolConfig::default());
        let server_id = "test-server";
        
        // Register test server
        // ... setup code ...
        
        // Execute 1000 concurrent tool calls
        let tasks: Vec<_> = (0..1000)
            .map(|i| {
                let pool = pool.clone();
                let server_id = server_id.to_string();
                tokio::spawn(async move {
                    let start = std::time::Instant::now();
                    let result = pool.execute_tool(
                        &server_id,
                        "test_tool",
                        serde_json::json!({"id": i})
                    ).await;
                    (result, start.elapsed())
                })
            })
            .collect();
        
        let mut results = Vec::new();
        for task in tasks {
            results.push(task.await.unwrap());
        }
        
        // Analyze results
        let success_count = results.iter().filter(|(r, _)| r.is_ok()).count();
        let avg_latency: Duration = results.iter()
            .map(|(_, duration)| *duration)
            .sum::<Duration>() / results.len() as u32;
        
        // Assert performance targets
        assert!(success_count as f64 / results.len() as f64 > 0.95, "Success rate too low");
        assert!(avg_latency < Duration::from_millis(200), "Average latency too high");
    }
    
    #[tokio::test]
    async fn test_connection_pool_scalability() {
        // Test pool behavior under various load patterns
        // ... implementation ...
    }
    
    #[tokio::test]
    async fn test_memory_usage_under_load() {
        // Monitor memory usage during sustained load
        // ... implementation ...
    }
}
```

This comprehensive security and performance analysis ensures the MCP server registration system is robust, secure, and performant under real-world conditions.