tower-mcp 0.17.1

Tower-native Model Context Protocol (MCP) implementation
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
603
604
605
606
607
608
609
610
611
612
613
614
//! Client-side response caching for SEP-2549 cacheable results.

use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use std::time::{Duration, Instant};

use tokio::sync::Mutex;

use crate::protocol::CacheScope;

/// Default upper bound for a server-provided cache TTL (24 hours).
pub const DEFAULT_MAX_CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60);

/// Configuration for the MCP client's SEP-2549 response cache.
///
/// Caching is consulted only after the 2026-07-28 lifecycle has been selected.
/// A result with no `ttlMs` uses [`default_ttl`](Self::default_ttl), which is
/// zero by default, and is therefore immediately stale.
#[derive(Debug, Clone)]
pub struct ClientCacheConfig {
    /// Enable the response cache. Default: `true`.
    pub enabled: bool,
    /// TTL used when a cacheable result omits `ttlMs`. Default: zero.
    pub default_ttl: Duration,
    /// Maximum server-provided or default TTL the client will honor.
    /// Default: 24 hours.
    pub max_ttl: Duration,
    /// Maximum number of distinct `resources/read` entries retained.
    ///
    /// List and discovery entries are exempt because their key space is
    /// bounded. Zero removes the resource-entry bound. Default: 512.
    pub max_resource_entries: usize,
    /// Return an expired entry when refreshing it fails. Default: `false`.
    pub serve_stale_on_error: bool,
    /// Opaque authorization-context partition for private entries.
    ///
    /// Use a stable principal identifier rather than an access token. Public
    /// entries remain reusable if this partition changes.
    pub partition: String,
}

impl ClientCacheConfig {
    /// Disable response caching while retaining the other defaults.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Self::default()
        }
    }

    /// Set the fallback TTL for results that omit `ttlMs`.
    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
        self.default_ttl = ttl;
        self
    }

    /// Set the upper bound applied to every cache TTL.
    pub fn with_max_ttl(mut self, ttl: Duration) -> Self {
        self.max_ttl = ttl;
        self
    }

    /// Set the maximum retained `resources/read` entries.
    pub fn with_max_resource_entries(mut self, max_entries: usize) -> Self {
        self.max_resource_entries = max_entries;
        self
    }

    /// Allow an expired entry to be returned when a refresh fails.
    pub fn with_serve_stale_on_error(mut self, enabled: bool) -> Self {
        self.serve_stale_on_error = enabled;
        self
    }

    /// Set the authorization-context partition for private entries.
    pub fn with_partition(mut self, partition: impl Into<String>) -> Self {
        self.partition = partition.into();
        self
    }
}

impl Default for ClientCacheConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            default_ttl: Duration::ZERO,
            max_ttl: DEFAULT_MAX_CACHE_TTL,
            max_resource_entries: 512,
            serve_stale_on_error: false,
            partition: String::new(),
        }
    }
}

#[derive(Debug, Clone, Eq)]
struct CacheKey {
    method: String,
    params: String,
    partition: CachePartition,
}

impl PartialEq for CacheKey {
    fn eq(&self, other: &Self) -> bool {
        self.method == other.method
            && self.params == other.params
            && self.partition == other.partition
    }
}

impl Hash for CacheKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.method.hash(state);
        self.params.hash(state);
        self.partition.hash(state);
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum CachePartition {
    Public,
    Private(String),
}

#[derive(Debug, Clone)]
struct CacheEntry {
    value: serde_json::Value,
    expires_at: Instant,
    scope: CacheScope,
}

#[derive(Debug, Clone)]
pub(crate) enum CacheLookup {
    Fresh(serde_json::Value),
    Stale(serde_json::Value),
    Miss,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct LogicalKey {
    method: String,
    params: Option<String>,
}

#[derive(Debug, Default)]
struct CacheState {
    entries: HashMap<CacheKey, CacheEntry>,
    resource_order: VecDeque<CacheKey>,
    generations: HashMap<LogicalKey, GenerationSlot>,
    partition: String,
}

#[derive(Debug, Default)]
struct GenerationSlot {
    generation: u64,
    in_flight: usize,
}

#[derive(Debug)]
pub(crate) struct ClientResponseCache {
    config: ClientCacheConfig,
    state: Mutex<CacheState>,
}

impl ClientResponseCache {
    pub(crate) fn new(config: ClientCacheConfig) -> Arc<Self> {
        Arc::new(Self {
            state: Mutex::new(CacheState {
                partition: config.partition.clone(),
                ..CacheState::default()
            }),
            config,
        })
    }

    pub(crate) fn enabled(&self) -> bool {
        self.config.enabled
    }

    pub(crate) fn serve_stale_on_error(&self) -> bool {
        self.config.serve_stale_on_error
    }

    pub(crate) async fn set_partition(&self, partition: String) {
        let mut state = self.state.lock().await;
        if state.partition == partition {
            return;
        }
        for slot in state.generations.values_mut() {
            slot.generation = slot.generation.wrapping_add(1);
        }
        state
            .entries
            .retain(|key, _| key.partition == CachePartition::Public);
        state
            .resource_order
            .retain(|key| key.partition == CachePartition::Public);
        state.partition = partition;
    }

    pub(crate) async fn clear(&self) {
        let mut state = self.state.lock().await;
        for slot in state.generations.values_mut() {
            slot.generation = slot.generation.wrapping_add(1);
        }
        state.entries.clear();
        state.resource_order.clear();
    }

    pub(crate) async fn len(&self) -> usize {
        self.state.lock().await.entries.len()
    }

    pub(crate) async fn capture_generation(&self, method: &str, params: &str) -> u64 {
        let mut state = self.state.lock().await;
        let key = generation_key(method, params);
        let slot = state.generations.entry(key).or_default();
        slot.in_flight = slot.in_flight.saturating_add(1);
        slot.generation
    }

    pub(crate) async fn release_generation(&self, method: &str, params: &str) {
        let mut state = self.state.lock().await;
        finish_generation(&mut state, &generation_key(method, params), None);
    }

    pub(crate) async fn lookup(&self, method: &str, params: &str) -> CacheLookup {
        if !self.config.enabled {
            return CacheLookup::Miss;
        }

        let state = self.state.lock().await;
        let private_key = CacheKey {
            method: method.to_string(),
            params: params.to_string(),
            partition: CachePartition::Private(state.partition.clone()),
        };
        if let Some(entry) = state.entries.get(&private_key) {
            return classify_entry(entry);
        }

        let public_key = CacheKey {
            method: method.to_string(),
            params: params.to_string(),
            partition: CachePartition::Public,
        };
        match state.entries.get(&public_key) {
            Some(entry) if entry.scope == CacheScope::Public => classify_entry(entry),
            _ => CacheLookup::Miss,
        }
    }

    pub(crate) async fn write(
        &self,
        method: &str,
        params: &str,
        captured_generation: u64,
        value: serde_json::Value,
        ttl_ms: Option<u64>,
        scope: Option<CacheScope>,
    ) {
        if !self.config.enabled {
            return;
        }

        let mut state = self.state.lock().await;
        let logical = generation_key(method, params);
        if !finish_generation(&mut state, &logical, Some(captured_generation)) {
            tracing::debug!(
                method,
                "Skipping cache write invalidated while the request was in flight"
            );
            return;
        }

        remove_logical_entries(&mut state, method, params);

        let ttl = Duration::from_millis(ttl_ms.unwrap_or_else(|| {
            u64::try_from(self.config.default_ttl.as_millis()).unwrap_or(u64::MAX)
        }))
        .min(self.config.max_ttl);
        if ttl.is_zero() {
            return;
        }

        let scope = scope.unwrap_or(CacheScope::Private);
        let partition = match scope {
            CacheScope::Public => CachePartition::Public,
            CacheScope::Private => CachePartition::Private(state.partition.clone()),
            _ => CachePartition::Private(state.partition.clone()),
        };
        let key = CacheKey {
            method: method.to_string(),
            params: params.to_string(),
            partition,
        };
        let now = Instant::now();
        let Some(expires_at) = now.checked_add(ttl) else {
            tracing::warn!(
                method,
                "Skipping response-cache TTL that exceeds clock range"
            );
            return;
        };
        state.entries.insert(
            key.clone(),
            CacheEntry {
                value,
                expires_at,
                scope,
            },
        );

        if method == "resources/read" {
            state.resource_order.retain(|existing| existing != &key);
            state.resource_order.push_back(key);
            enforce_resource_bound(&mut state, self.config.max_resource_entries);
        }
    }

    pub(crate) async fn evict_method(&self, method: &str) {
        let mut state = self.state.lock().await;
        let logical = generation_key(method, "");
        if let Some(slot) = state.generations.get_mut(&logical) {
            slot.generation = slot.generation.wrapping_add(1);
        }
        state.entries.retain(|key, _| key.method != method);
        state.resource_order.retain(|key| key.method != method);
    }

    pub(crate) async fn evict_resource(&self, uri: &str) {
        let mut state = self.state.lock().await;
        let logical = generation_key("resources/read", uri);
        if let Some(slot) = state.generations.get_mut(&logical) {
            slot.generation = slot.generation.wrapping_add(1);
        }
        remove_logical_entries(&mut state, "resources/read", uri);
    }
}

fn finish_generation(state: &mut CacheState, key: &LogicalKey, captured: Option<u64>) -> bool {
    let Some(slot) = state.generations.get_mut(key) else {
        return false;
    };
    let valid = captured.is_none_or(|captured| slot.generation == captured);
    slot.in_flight = slot.in_flight.saturating_sub(1);
    if slot.in_flight == 0 {
        state.generations.remove(key);
    }
    valid
}

fn generation_key(method: &str, params: &str) -> LogicalKey {
    let params = (method == "resources/read").then(|| params.to_string());
    LogicalKey {
        method: method.to_string(),
        params,
    }
}

fn classify_entry(entry: &CacheEntry) -> CacheLookup {
    if entry.expires_at > Instant::now() {
        CacheLookup::Fresh(entry.value.clone())
    } else {
        CacheLookup::Stale(entry.value.clone())
    }
}

fn remove_logical_entries(state: &mut CacheState, method: &str, params: &str) {
    state
        .entries
        .retain(|key, _| key.method != method || key.params != params);
    state
        .resource_order
        .retain(|key| key.method != method || key.params != params);
}

fn enforce_resource_bound(state: &mut CacheState, max_entries: usize) {
    if max_entries == 0 {
        return;
    }
    while state.resource_order.len() > max_entries {
        if let Some(oldest) = state.resource_order.pop_front() {
            state.entries.remove(&oldest);
        }
    }
}

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

    fn value(id: u64) -> serde_json::Value {
        serde_json::json!({ "id": id })
    }

    #[tokio::test]
    async fn zero_ttl_is_not_cached() {
        let cache = ClientResponseCache::new(ClientCacheConfig::default());
        let generation = cache.capture_generation("tools/list", "").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(1),
                Some(0),
                Some(CacheScope::Public),
            )
            .await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Miss
        ));
    }

    #[tokio::test]
    async fn max_ttl_caps_server_ttl_and_retains_stale_value() {
        let cache = ClientResponseCache::new(
            ClientCacheConfig::default().with_max_ttl(Duration::from_millis(1)),
        );
        let generation = cache.capture_generation("tools/list", "").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(1),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Fresh(_)
        ));

        tokio::time::sleep(Duration::from_millis(5)).await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Stale(_)
        ));
    }

    #[tokio::test]
    async fn completed_requests_release_generation_slots() {
        let cache = ClientResponseCache::new(ClientCacheConfig::default());

        let generation = cache.capture_generation("tools/list", "").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(1),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        assert!(cache.state.lock().await.generations.is_empty());

        cache
            .capture_generation("resources/read", "resource://a")
            .await;
        cache
            .release_generation("resources/read", "resource://a")
            .await;
        assert!(cache.state.lock().await.generations.is_empty());
    }

    #[tokio::test]
    async fn private_entries_follow_partition_but_public_entries_do_not() {
        let cache =
            ClientResponseCache::new(ClientCacheConfig::default().with_partition("principal-a"));
        let generation = cache
            .capture_generation("resources/read", "config://a")
            .await;
        cache
            .write(
                "resources/read",
                "config://a",
                generation,
                value(1),
                Some(60_000),
                Some(CacheScope::Private),
            )
            .await;
        cache.set_partition("principal-b".to_string()).await;
        assert!(matches!(
            cache.lookup("resources/read", "config://a").await,
            CacheLookup::Miss
        ));

        let generation = cache.capture_generation("tools/list", "").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(2),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        cache.set_partition("principal-c".to_string()).await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Fresh(_)
        ));
    }

    #[tokio::test]
    async fn invalidation_wins_over_an_in_flight_write() {
        let cache = ClientResponseCache::new(ClientCacheConfig::default());
        let generation = cache.capture_generation("tools/list", "").await;
        cache.evict_method("tools/list").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(1),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Miss
        ));
    }

    #[tokio::test]
    async fn clear_and_partition_rotation_suppress_in_flight_writes() {
        let cache =
            ClientResponseCache::new(ClientCacheConfig::default().with_partition("principal-a"));

        let clear_generation = cache.capture_generation("tools/list", "").await;
        cache.clear().await;
        cache
            .write(
                "tools/list",
                "",
                clear_generation,
                value(1),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Miss
        ));

        let rotate_generation = cache
            .capture_generation("resources/read", "config://a")
            .await;
        cache.set_partition("principal-b".to_string()).await;
        cache
            .write(
                "resources/read",
                "config://a",
                rotate_generation,
                value(2),
                Some(60_000),
                Some(CacheScope::Private),
            )
            .await;
        assert!(matches!(
            cache.lookup("resources/read", "config://a").await,
            CacheLookup::Miss
        ));
    }

    #[tokio::test]
    async fn resource_cache_is_bounded_without_evicting_lists() {
        let cache =
            ClientResponseCache::new(ClientCacheConfig::default().with_max_resource_entries(2));
        let generation = cache.capture_generation("tools/list", "").await;
        cache
            .write(
                "tools/list",
                "",
                generation,
                value(0),
                Some(60_000),
                Some(CacheScope::Public),
            )
            .await;
        for index in 0..3 {
            let uri = format!("resource://{index}");
            let generation = cache.capture_generation("resources/read", &uri).await;
            cache
                .write(
                    "resources/read",
                    &uri,
                    generation,
                    value(index),
                    Some(60_000),
                    Some(CacheScope::Private),
                )
                .await;
        }
        assert_eq!(cache.len().await, 3);
        assert!(matches!(
            cache.lookup("resources/read", "resource://0").await,
            CacheLookup::Miss
        ));
        assert!(matches!(
            cache.lookup("tools/list", "").await,
            CacheLookup::Fresh(_)
        ));
    }
}