do-memory-mcp 0.1.46

Model Context Protocol (MCP) server for AI agents
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
//! Rate limiter for MCP server
//!
//! This module provides token bucket-based rate limiting to prevent DoS attacks.
//! Features:
//! - Per-principal rate limiting (validated token subject, or one process-scoped
//!   bucket for unauthenticated stdio transports)
//! - Token bucket algorithm for smooth rate limiting
//! - Different limits for read vs write operations
//! - Bounded bucket cardinality (overflow identities share one bucket)
//! - Configurable via environment variables
//! - Rate limit headers in responses
//!
//! Identities are supplied by the caller from a *trusted* principal only; request
//! payload fields such as `client_id` MUST NOT be used (issue #1084).

use parking_lot::RwLock;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use tracing::{debug, trace, warn};

mod types;
pub use types::*;

/// Token bucket for rate limiting
#[derive(Debug)]
struct TokenBucket {
    /// Current number of tokens
    tokens: f64,
    /// Maximum burst size
    capacity: u32,
    /// Tokens added per second
    refill_rate: f64,
    /// Last time tokens were refilled
    last_refill: Instant,
    /// Last time this bucket was accessed
    last_accessed: Instant,
}

impl TokenBucket {
    /// Create a new token bucket
    fn new(requests_per_second: u32, burst_size: u32) -> Self {
        let now = Instant::now();
        Self {
            tokens: burst_size as f64,
            capacity: burst_size,
            refill_rate: requests_per_second as f64,
            last_refill: now,
            last_accessed: now,
        }
    }

    /// Refill tokens based on elapsed time
    fn refill(&mut self) {
        let now = Instant::now();
        let elapsed = now.duration_since(self.last_refill).as_secs_f64();
        let tokens_to_add = elapsed * self.refill_rate;

        self.tokens = (self.tokens + tokens_to_add).min(self.capacity as f64);
        self.last_refill = now;
        self.last_accessed = now;
    }

    /// Try to consume tokens from the bucket
    /// Returns true if tokens were consumed, false if rate limited
    fn try_consume(&mut self, tokens: u32) -> bool {
        self.refill();

        if self.tokens >= tokens as f64 {
            self.tokens -= tokens as f64;
            true
        } else {
            false
        }
    }

    /// Get current token count
    fn tokens(&mut self) -> u32 {
        self.refill();
        self.tokens as u32
    }

    /// Check if this bucket is stale (not accessed for a while)
    fn is_stale(&self, timeout: Duration) -> bool {
        Instant::now().duration_since(self.last_accessed) > timeout
    }

    /// Get time until next token is available
    fn time_until_next_token(&self) -> Duration {
        if self.tokens >= 1.0 {
            Duration::from_secs(0)
        } else {
            let tokens_needed = 1.0 - self.tokens;
            let seconds = tokens_needed / self.refill_rate;
            Duration::from_secs_f64(seconds)
        }
    }
}

/// Rate limiter using token bucket algorithm
#[derive(Debug)]
pub struct RateLimiter {
    /// Configuration
    pub config: RateLimitConfig,
    /// Token buckets for read operations per client
    read_buckets: RwLock<HashMap<ClientId, TokenBucket>>,
    /// Token buckets for write operations per client
    write_buckets: RwLock<HashMap<ClientId, TokenBucket>>,
    /// Monotonically increasing call count for periodic cleanup
    call_count: AtomicU64,
}

impl RateLimiter {
    /// Create a new rate limiter with the given configuration
    pub fn new(config: RateLimitConfig) -> Self {
        let limiter = Self {
            config,
            read_buckets: RwLock::new(HashMap::new()),
            write_buckets: RwLock::new(HashMap::new()),
            call_count: AtomicU64::new(0),
        };

        // Spawn cleanup task if enabled
        if limiter.config.enabled {
            limiter.spawn_cleanup_task();
        }

        limiter
    }

    /// Create a rate limiter from environment configuration
    pub fn from_env() -> Self {
        Self::new(RateLimitConfig::from_env())
    }

    /// Check if rate limiting is enabled
    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Check if a request should be rate limited
    pub fn check_rate_limit(
        &self,
        client_id: &ClientId,
        operation: OperationType,
    ) -> RateLimitResult {
        if !self.config.enabled {
            return RateLimitResult {
                allowed: true,
                remaining: u32::MAX,
                reset_after: Duration::from_secs(0),
                limit: u32::MAX,
                retry_after: None,
            };
        }

        // Periodic stale bucket cleanup (every ~1000 calls)
        let count = self.call_count.fetch_add(1, Ordering::Relaxed) + 1;
        if count % 1000 == 0 {
            self.cleanup_stale_buckets(self.config.stale_threshold);
        }

        let (rps, burst) = match operation {
            OperationType::Read => (
                self.config.read_requests_per_second,
                self.config.read_burst_size,
            ),
            OperationType::Write => (
                self.config.write_requests_per_second,
                self.config.write_burst_size,
            ),
        };

        let buckets = match operation {
            OperationType::Read => &self.read_buckets,
            OperationType::Write => &self.write_buckets,
        };

        let mut buckets_guard = buckets.write();

        // Bound bucket cardinality: once the identity capacity is reached, new
        // identities share one overflow bucket instead of growing the map.
        // Trusted principals make this a safety net, not an attacker-controlled path.
        let identity = if buckets_guard.contains_key(client_id)
            || buckets_guard.len() < self.config.max_identities
        {
            client_id.clone()
        } else {
            warn!(
                "Rate limit identity capacity ({}) reached; new identities share one bucket",
                self.config.max_identities
            );
            ClientId::Shared
        };

        // Get or create bucket for this client
        let bucket = buckets_guard.entry(identity.clone()).or_insert_with(|| {
            trace!("Creating new rate limit bucket for client: {}", identity);
            TokenBucket::new(rps, burst)
        });

        // Try to consume one token
        let allowed = bucket.try_consume(1);
        let remaining = bucket.tokens();
        let reset_after = bucket.time_until_next_token();

        if allowed {
            trace!(
                "Rate limit check passed for client: {} (op: {:?}, remaining: {})",
                client_id, operation, remaining
            );
            RateLimitResult {
                allowed: true,
                remaining,
                reset_after,
                limit: burst,
                retry_after: None,
            }
        } else {
            let retry_after = bucket.time_until_next_token();
            warn!(
                "Rate limit exceeded for client: {} (op: {:?}, retry_after: {:?})",
                client_id, operation, retry_after
            );
            RateLimitResult {
                allowed: false,
                remaining: 0,
                reset_after,
                limit: burst,
                retry_after: Some(retry_after),
            }
        }
    }

    /// Get rate limit headers for a successful request
    pub fn get_headers(&self, result: &RateLimitResult) -> Vec<(String, String)> {
        vec![
            ("X-RateLimit-Limit".to_string(), result.limit.to_string()),
            (
                "X-RateLimit-Remaining".to_string(),
                result.remaining.to_string(),
            ),
            (
                "X-RateLimit-Reset".to_string(),
                result.reset_after.as_secs().to_string(),
            ),
        ]
    }

    /// Get rate limit headers for a rate-limited response
    pub fn get_rate_limited_headers(&self, result: &RateLimitResult) -> Vec<(String, String)> {
        let mut headers = self.get_headers(result);
        if let Some(retry_after) = result.retry_after {
            headers.push(("Retry-After".to_string(), retry_after.as_secs().to_string()));
        }
        headers
    }

    /// Spawn a background task to clean up stale buckets
    fn spawn_cleanup_task(&self) {
        // Periodic cleanup is triggered by check_rate_limit (every ~1000 calls)
        // using the call_count atomic counter. Also run once at startup to
        // establish the pattern for any pre-existing buckets.
        self.cleanup_stale_buckets(self.config.stale_threshold);
        debug!("Rate limiter cleanup: periodic eviction via check_rate_limit");
    }

    /// Get current statistics about the rate limiter
    pub fn get_stats(&self) -> RateLimiterStats {
        RateLimiterStats {
            read_buckets_count: self.read_buckets.read().len(),
            write_buckets_count: self.write_buckets.read().len(),
            enabled: self.config.enabled,
            read_config: (
                self.config.read_requests_per_second,
                self.config.read_burst_size,
            ),
            write_config: (
                self.config.write_requests_per_second,
                self.config.write_burst_size,
            ),
            max_identities: self.config.max_identities,
        }
    }

    /// Manually clean up stale buckets (for testing and runtime eviction)
    pub fn cleanup_stale_buckets(&self, stale_threshold: Duration) {
        // Clean up stale read buckets
        {
            let mut read_guard = self.read_buckets.write();
            let stale_clients: Vec<ClientId> = read_guard
                .iter()
                .filter(|(_, bucket)| bucket.is_stale(stale_threshold))
                .map(|(client_id, _)| client_id.clone())
                .collect();

            for client_id in stale_clients {
                debug!("Removing stale rate limit bucket for client: {}", client_id);
                read_guard.remove(&client_id);
            }
        }

        // Clean up stale write buckets
        {
            let mut write_guard = self.write_buckets.write();
            let stale_clients: Vec<ClientId> = write_guard
                .iter()
                .filter(|(_, bucket)| bucket.is_stale(stale_threshold))
                .map(|(client_id, _)| client_id.clone())
                .collect();

            for client_id in stale_clients {
                debug!("Removing stale rate limit bucket for client: {}", client_id);
                write_guard.remove(&client_id);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_token_bucket_basic() {
        let mut bucket = TokenBucket::new(10, 20);
        assert_eq!(bucket.tokens(), 20);

        // Consume some tokens
        assert!(bucket.try_consume(5));
        assert_eq!(bucket.tokens(), 15);

        // Consume all remaining
        assert!(bucket.try_consume(15));
        assert_eq!(bucket.tokens(), 0);

        // Should fail when empty
        assert!(!bucket.try_consume(1));
    }

    #[test]
    fn test_rate_limiter_disabled() {
        let config = RateLimitConfig {
            enabled: false,
            ..Default::default()
        };
        let limiter = RateLimiter::new(config);

        let client_id = ClientId::from_string("test");
        let result = limiter.check_rate_limit(&client_id, OperationType::Read);

        assert!(result.allowed);
        assert_eq!(result.remaining, u32::MAX);
    }

    #[test]
    fn test_rate_limiter_basic() {
        let config = RateLimitConfig {
            enabled: true,
            read_requests_per_second: 10,
            read_burst_size: 5,
            write_requests_per_second: 5,
            write_burst_size: 3,
            cleanup_interval: Duration::from_secs(60),
            stale_threshold: Duration::from_secs(300),
            max_identities: 10_000,
        };
        let limiter = RateLimiter::new(config);

        let client_id = ClientId::from_string("test");

        // Should allow burst size requests
        for i in 0..5 {
            let result = limiter.check_rate_limit(&client_id, OperationType::Read);
            assert!(result.allowed, "Request {} should be allowed", i);
        }

        // 6th request should be rate limited
        let result = limiter.check_rate_limit(&client_id, OperationType::Read);
        assert!(!result.allowed);
        assert!(result.retry_after.is_some());
    }

    #[test]
    fn test_rate_limit_headers() {
        let config = RateLimitConfig::default();
        let limiter = RateLimiter::new(config);

        let result = RateLimitResult {
            allowed: true,
            remaining: 50,
            reset_after: Duration::from_secs(30),
            limit: 100,
            retry_after: None,
        };

        let headers = limiter.get_headers(&result);
        assert!(
            headers
                .iter()
                .any(|(k, v)| k == "X-RateLimit-Limit" && v == "100")
        );
        assert!(
            headers
                .iter()
                .any(|(k, v)| k == "X-RateLimit-Remaining" && v == "50")
        );
        assert!(
            headers
                .iter()
                .any(|(k, v)| k == "X-RateLimit-Reset" && v == "30")
        );
    }

    #[test]
    fn test_rate_limited_headers() {
        let config = RateLimitConfig::default();
        let limiter = RateLimiter::new(config);

        let result = RateLimitResult {
            allowed: false,
            remaining: 0,
            reset_after: Duration::from_secs(60),
            limit: 100,
            retry_after: Some(Duration::from_secs(5)),
        };

        let headers = limiter.get_rate_limited_headers(&result);
        assert!(headers.iter().any(|(k, v)| k == "Retry-After" && v == "5"));
    }
}