turbomcp-protocol 3.1.3

Complete MCP protocol implementation with types, traits, context management, and message handling
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
//! Generic shared wrapper traits and utilities
//!
//! This module provides reusable patterns for creating thread-safe wrappers
//! around types that need to be shared across multiple async tasks while
//! encapsulating Arc/Mutex complexity.

use std::sync::Arc;
use tokio::sync::Mutex;

/// Trait for types that can be wrapped in a thread-safe shared wrapper
///
/// This trait defines the interface for creating shared wrappers that encapsulate
/// Arc/Mutex complexity and provide clean APIs for concurrent access.
///
/// # Design Principles
///
/// - **Hide complexity**: Encapsulate Arc/Mutex details from users
/// - **Preserve semantics**: Maintain original API behavior as much as possible
/// - **Enable sharing**: Allow multiple tasks to access the same instance safely
/// - **Async-first**: Design for async/await patterns
///
/// # Implementation Guidelines
///
/// When implementing this trait, consider:
/// - Methods requiring `&mut self` need special handling in shared contexts
/// - Reference-returning methods (`&T`) can't work directly with async mutexes
/// - Consuming methods (taking `self`) may need special consumption patterns
/// - Performance implications of mutex contention
///
/// # Examples
///
/// ```rust
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
/// use turbomcp_protocol::shared::Shareable;
///
/// struct MyService {
///     counter: u64,
/// }
///
/// impl MyService {
///     fn new() -> Self {
///         Self { counter: 0 }
///     }
///
///     fn increment(&mut self) {
///         self.counter += 1;
///     }
///
///     fn count(&self) -> u64 {
///         self.counter
///     }
/// }
///
/// // Shared wrapper
/// struct SharedMyService {
///     inner: Arc<Mutex<MyService>>,
/// }
///
/// impl Shareable<MyService> for SharedMyService {
///     fn new(inner: MyService) -> Self {
///         Self {
///             inner: Arc::new(Mutex::new(inner)),
///         }
///     }
/// }
///
/// impl Clone for SharedMyService {
///     fn clone(&self) -> Self {
///         Self {
///             inner: Arc::clone(&self.inner),
///         }
///     }
/// }
///
/// impl SharedMyService {
///     async fn increment(&self) {
///         self.inner.lock().await.increment();
///     }
///
///     async fn count(&self) -> u64 {
///         self.inner.lock().await.count()
///     }
/// }
/// ```
pub trait Shareable<T>: Clone + Send + Sync + 'static {
    /// Create a new shared wrapper around the inner type
    fn new(inner: T) -> Self;
}

/// A generic shared wrapper that implements the Shareable pattern
///
/// This provides a concrete implementation of the sharing pattern that can
/// be used directly for simple cases where no custom behavior is needed.
///
/// # Examples
///
/// ```rust
/// use turbomcp_protocol::shared::{Shared, Shareable};
///
/// #[derive(Debug)]
/// struct Counter {
///     value: u64,
/// }
///
/// impl Counter {
///     fn new() -> Self {
///         Self { value: 0 }
///     }
///
///     fn increment(&mut self) {
///         self.value += 1;
///     }
///
///     fn get(&self) -> u64 {
///         self.value
///     }
/// }
///
/// # async fn example() {
/// // Create a shared counter
/// let counter = Counter::new();
/// let shared = Shared::new(counter);
///
/// // Clone for use in multiple tasks
/// let shared1 = shared.clone();
/// let shared2 = shared.clone();
///
/// // Use in concurrent tasks
/// let handle1 = tokio::spawn(async move {
///     shared1.with_mut(|c| c.increment()).await;
/// });
///
/// let handle2 = tokio::spawn(async move {
///     shared2.with(|c| c.get()).await
/// });
/// # }
/// ```
#[derive(Debug)]
pub struct Shared<T> {
    inner: Arc<Mutex<T>>,
}

impl<T> Shared<T>
where
    T: Send + 'static,
{
    /// Execute a closure with read access to the inner value
    pub async fn with<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&T) -> R + Send,
    {
        let guard = self.inner.lock().await;
        f(&*guard)
    }

    /// Execute a closure with mutable access to the inner value
    pub async fn with_mut<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut T) -> R + Send,
    {
        let mut guard = self.inner.lock().await;
        f(&mut *guard)
    }

    /// Execute an async closure with read access to the inner value
    pub async fn with_async<F, Fut, R>(&self, f: F) -> R
    where
        F: FnOnce(&T) -> Fut + Send,
        Fut: std::future::Future<Output = R> + Send,
    {
        let guard = self.inner.lock().await;
        f(&*guard).await
    }

    /// Execute an async closure with mutable access to the inner value
    pub async fn with_mut_async<F, Fut, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut T) -> Fut + Send,
        Fut: std::future::Future<Output = R> + Send,
    {
        let mut guard = self.inner.lock().await;
        f(&mut *guard).await
    }

    /// Try to execute a closure with read access, returning None if the lock is busy
    pub fn try_with<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&T) -> R + Send,
    {
        let guard = self.inner.try_lock().ok()?;
        Some(f(&*guard))
    }

    /// Try to execute a closure with mutable access, returning None if the lock is busy
    pub fn try_with_mut<F, R>(&self, f: F) -> Option<R>
    where
        F: FnOnce(&mut T) -> R + Send,
    {
        let mut guard = self.inner.try_lock().ok()?;
        Some(f(&mut *guard))
    }
}

impl<T> Shareable<T> for Shared<T>
where
    T: Send + 'static,
{
    fn new(inner: T) -> Self {
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }
}

impl<T> Clone for Shared<T>
where
    T: Send + 'static,
{
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

/// Specialized shared wrapper for types that can be consumed (like servers)
///
/// This wrapper allows the inner value to be extracted for consumption
/// (such as running a server), after which the wrapper becomes unusable.
///
/// # Examples
///
/// ```rust
/// use turbomcp_protocol::shared::{ConsumableShared, Shareable};
///
/// struct Server {
///     name: String,
/// }
///
/// impl Server {
///     fn new(name: String) -> Self {
///         Self { name }
///     }
///
///     fn run(self) -> String {
///         format!("Running server: {}", self.name)
///     }
///
///     fn status(&self) -> String {
///         format!("Server {} is ready", self.name)
///     }
/// }
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let server = Server::new("test".to_string());
/// let shared = ConsumableShared::new(server);
/// let shared_clone = shared.clone();
///
/// // Check status before consumption
/// let status = shared.with(|s| s.status()).await?;
/// assert_eq!(status, "Server test is ready");
///
/// // Consume the server
/// let server = shared.consume().await?;
/// let result = server.run();
/// assert_eq!(result, "Running server: test");
///
/// // Wrapper is now unusable (using clone)
/// assert!(shared_clone.with(|s| s.status()).await.is_err());
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ConsumableShared<T> {
    inner: Arc<Mutex<Option<T>>>,
}

impl<T> ConsumableShared<T>
where
    T: Send + 'static,
{
    /// Execute a closure with read access to the inner value
    ///
    /// Returns an error if the value has been consumed.
    pub async fn with<F, R>(&self, f: F) -> Result<R, SharedError>
    where
        F: FnOnce(&T) -> R + Send,
    {
        let guard = self.inner.lock().await;
        match guard.as_ref() {
            Some(value) => Ok(f(value)),
            None => Err(SharedError::Consumed),
        }
    }

    /// Execute a closure with mutable access to the inner value
    ///
    /// Returns an error if the value has been consumed.
    pub async fn with_mut<F, R>(&self, f: F) -> Result<R, SharedError>
    where
        F: FnOnce(&mut T) -> R + Send,
    {
        let mut guard = self.inner.lock().await;
        match guard.as_mut() {
            Some(value) => Ok(f(value)),
            None => Err(SharedError::Consumed),
        }
    }

    /// Execute an async closure with read access to the inner value
    ///
    /// Returns an error if the value has been consumed.
    pub async fn with_async<F, Fut, R>(&self, f: F) -> Result<R, SharedError>
    where
        F: FnOnce(&T) -> Fut + Send,
        Fut: std::future::Future<Output = R> + Send,
    {
        let guard = self.inner.lock().await;
        match guard.as_ref() {
            Some(value) => Ok(f(value).await),
            None => Err(SharedError::Consumed),
        }
    }

    /// Execute an async closure with mutable access to the inner value
    ///
    /// Returns an error if the value has been consumed.
    pub async fn with_mut_async<F, Fut, R>(&self, f: F) -> Result<R, SharedError>
    where
        F: FnOnce(&mut T) -> Fut + Send,
        Fut: std::future::Future<Output = R> + Send,
    {
        let mut guard = self.inner.lock().await;
        match guard.as_mut() {
            Some(value) => Ok(f(value).await),
            None => Err(SharedError::Consumed),
        }
    }

    /// Consume the inner value, making the wrapper unusable
    ///
    /// This extracts the value from the wrapper, after which all other
    /// operations will return `SharedError::Consumed`.
    pub async fn consume(self) -> Result<T, SharedError> {
        let mut guard = self.inner.lock().await;
        guard.take().ok_or(SharedError::Consumed)
    }

    /// Check if the value is still available (not consumed)
    pub async fn is_available(&self) -> bool {
        self.inner.lock().await.is_some()
    }
}

impl<T> Shareable<T> for ConsumableShared<T>
where
    T: Send + 'static,
{
    fn new(inner: T) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Some(inner))),
        }
    }
}

impl<T> Clone for ConsumableShared<T>
where
    T: Send + 'static,
{
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

/// Errors that can occur when working with shared wrappers
///
/// These errors are domain-specific for shared wrapper operations and are converted
/// to the main [`Error`](crate::Error) type when crossing API boundaries.
#[derive(Debug, Clone, thiserror::Error)]
pub enum SharedError {
    /// The wrapped value has been consumed and is no longer available
    #[error("The shared value has been consumed")]
    Consumed,
}

// Conversion to McpError for API boundary crossing (v3.0)
impl From<SharedError> for crate::McpError {
    fn from(err: SharedError) -> Self {
        match err {
            SharedError::Consumed => {
                crate::McpError::invalid_params("Shared value has already been consumed")
                    .with_component("shared_wrapper")
            }
        }
    }
}

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

    #[derive(Debug)]
    struct TestCounter {
        value: u64,
    }

    impl TestCounter {
        fn new() -> Self {
            Self { value: 0 }
        }

        fn increment(&mut self) {
            self.value += 1;
        }

        fn get(&self) -> u64 {
            self.value
        }

        #[allow(dead_code)]
        async fn get_async(&self) -> u64 {
            self.value
        }
    }

    #[tokio::test]
    async fn test_shared_basic_operations() {
        let counter = TestCounter::new();
        let shared = Shared::new(counter);

        // Test read access
        let value = shared.with(|c| c.get()).await;
        assert_eq!(value, 0);

        // Test mutable access
        shared.with_mut(|c| c.increment()).await;
        let value = shared.with(|c| c.get()).await;
        assert_eq!(value, 1);
    }

    #[tokio::test]
    async fn test_shared_async_operations() {
        let counter = TestCounter::new();
        let shared = Shared::new(counter);

        // Test async operations by performing a synchronous operation
        // that we can wrap in a future
        let value = shared.with(|c| c.get()).await;
        assert_eq!(value, 0);
    }

    #[tokio::test]
    async fn test_shared_cloning() {
        let counter = TestCounter::new();
        let shared = Shared::new(counter);

        // Clone multiple times
        let clones: Vec<_> = (0..10).map(|_| shared.clone()).collect();
        assert_eq!(clones.len(), 10);

        // All clones should work
        for (i, shared_clone) in clones.into_iter().enumerate() {
            shared_clone.with_mut(|c| c.increment()).await;
            let value = shared_clone.with(|c| c.get()).await;
            assert_eq!(value, i as u64 + 1);
        }
    }

    #[tokio::test]
    async fn test_shared_concurrent_access() {
        let counter = TestCounter::new();
        let shared = Shared::new(counter);

        // Spawn multiple concurrent tasks
        let handles: Vec<_> = (0..10)
            .map(|_| {
                let shared_clone = shared.clone();
                tokio::spawn(async move {
                    shared_clone.with_mut(|c| c.increment()).await;
                })
            })
            .collect();

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }

        // Value should be 10
        let value = shared.with(|c| c.get()).await;
        assert_eq!(value, 10);
    }

    #[tokio::test]
    async fn test_consumable_shared() {
        let counter = TestCounter::new();
        let shared = ConsumableShared::new(counter);
        let shared_clone = shared.clone();

        // Test operations before consumption
        assert!(shared.is_available().await);
        let value = shared.with(|c| c.get()).await.unwrap();
        assert_eq!(value, 0);

        shared.with_mut(|c| c.increment()).await.unwrap();
        let value = shared.with(|c| c.get()).await.unwrap();
        assert_eq!(value, 1);

        // Consume the value
        let counter = shared.consume().await.unwrap();
        assert_eq!(counter.get(), 1);

        // Operations should fail after consumption (using the clone)
        assert!(!shared_clone.is_available().await);
        assert!(matches!(
            shared_clone.with(|c| c.get()).await,
            Err(SharedError::Consumed)
        ));
    }

    #[tokio::test]
    async fn test_consumable_shared_cloning() {
        let counter = TestCounter::new();
        let shared = ConsumableShared::new(counter);
        let shared_clone = shared.clone();

        // Both should work initially
        assert!(shared.is_available().await);
        assert!(shared_clone.is_available().await);

        // Consume from one
        let _counter = shared.consume().await.unwrap();

        // Both should be consumed
        assert!(!shared_clone.is_available().await);
        assert!(matches!(
            shared_clone.with(|c| c.get()).await,
            Err(SharedError::Consumed)
        ));
    }

    #[tokio::test]
    async fn test_try_operations() {
        let counter = TestCounter::new();
        let shared = Shared::new(counter);

        // Try operations should work when lock is available
        let value = shared.try_with(|c| c.get()).unwrap();
        assert_eq!(value, 0);

        shared.try_with_mut(|c| c.increment()).unwrap();
        let value = shared.try_with(|c| c.get()).unwrap();
        assert_eq!(value, 1);
    }
}