turbomcp-protocol 3.1.1

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
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
//! # Protocol Versioning
//!
//! TurboMCP v3 targets the latest MCP release only.
//!
//! ```rust
//! use turbomcp_protocol::versioning::Version;
//!
//! let version = Version::latest();
//! assert_eq!(version.to_string(), "2025-11-25");
//! ```
//!
//! ## Feature Flags vs Runtime Negotiation
//!
//! Most MCP 2025-11-25 features are now **always available** (no feature flag needed).
//! Only experimental features like the Tasks API require a feature flag:
//! ```toml
//! # Enable experimental Tasks API
//! turbomcp-protocol = { version = "3.0", features = ["experimental-tasks"] }
//! ```
//!
//! Runtime negotiation is exact-match only:
//! ```rust,ignore
//! use turbomcp_protocol::{InitializeRequest, InitializeResult};
//!
//! // Client asks for the current spec
//! let request = InitializeRequest { protocol_version: "2025-11-25".into(), ..Default::default() };
//!
//! // Server responds with the same version or rejects the request.
//! let response = InitializeResult { protocol_version: "2025-11-25".into(), ..Default::default() };
//! ```

pub mod adapter;

use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt;
use std::str::FromStr;

/// Version manager for handling protocol versions
#[derive(Debug, Clone)]
pub struct VersionManager {
    /// Supported versions in order of preference
    supported_versions: Vec<Version>,
    /// Current protocol version
    current_version: Version,
}

/// Semantic version representation
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Version {
    /// Year component
    pub year: u16,
    /// Month component  
    pub month: u8,
    /// Day component
    pub day: u8,
}

/// Version compatibility result
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VersionCompatibility {
    /// Versions are fully compatible
    Compatible,
    /// Versions are incompatible
    Incompatible(String),
}

/// Version requirement specification
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VersionRequirement {
    /// Exact version match
    Exact(Version),
    /// Minimum version required
    Minimum(Version),
    /// Maximum version supported
    Maximum(Version),
    /// Version range (inclusive)
    Range(Version, Version),
    /// Any version from the list
    Any(Vec<Version>),
}

impl Version {
    /// Create a new version
    ///
    /// # Errors
    ///
    /// Returns [`VersionError::InvalidMonth`] if month is not in range 1-12.
    /// Returns [`VersionError::InvalidDay`] if day is invalid for the given month.
    pub fn new(year: u16, month: u8, day: u8) -> Result<Self, VersionError> {
        if !(1..=12).contains(&month) {
            return Err(VersionError::InvalidMonth(month.to_string()));
        }

        if !(1..=31).contains(&day) {
            return Err(VersionError::InvalidDay(day.to_string()));
        }

        // Basic month/day validation
        if month == 2 && day > 29 {
            return Err(VersionError::InvalidDay(format!(
                "{} (invalid for February)",
                day
            )));
        }

        if matches!(month, 4 | 6 | 9 | 11) && day > 30 {
            return Err(VersionError::InvalidDay(format!(
                "{} (month {} only has 30 days)",
                day, month
            )));
        }

        Ok(Self { year, month, day })
    }

    /// Get the latest MCP protocol version (2025-11-25)
    pub fn latest() -> Self {
        Self {
            year: 2025,
            month: 11,
            day: 25,
        }
    }

    /// Get the current MCP protocol version.
    pub fn current() -> Self {
        Self::latest()
    }

    /// Check if this version is newer than another
    pub fn is_newer_than(&self, other: &Version) -> bool {
        self > other
    }

    /// Check if this version is older than another
    pub fn is_older_than(&self, other: &Version) -> bool {
        self < other
    }

    /// Check if this version is compatible with another
    pub fn is_compatible_with(&self, other: &Version) -> bool {
        self == other
    }

    /// Get version as a date string (YYYY-MM-DD)
    pub fn to_date_string(&self) -> String {
        format!("{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }

    /// Parse version from date string
    ///
    /// # Errors
    ///
    /// Returns [`VersionError`] if the string is not in `YYYY-MM-DD` format
    /// or contains invalid date components.
    pub fn from_date_string(s: &str) -> Result<Self, VersionError> {
        s.parse()
    }

    /// Get all known MCP versions
    pub fn known_versions() -> Vec<Version> {
        vec![Version::latest()]
    }
}

impl fmt::Display for Version {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_date_string())
    }
}

impl FromStr for Version {
    type Err = VersionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('-').collect();

        if parts.len() != 3 {
            return Err(VersionError::InvalidFormat(s.to_string()));
        }

        let year = parts[0]
            .parse::<u16>()
            .map_err(|_| VersionError::InvalidYear(parts[0].to_string()))?;

        let month = parts[1]
            .parse::<u8>()
            .map_err(|_| VersionError::InvalidMonth(parts[1].to_string()))?;

        let day = parts[2]
            .parse::<u8>()
            .map_err(|_| VersionError::InvalidDay(parts[2].to_string()))?;

        Self::new(year, month, day)
    }
}

impl PartialOrd for Version {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Version {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.year, self.month, self.day).cmp(&(other.year, other.month, other.day))
    }
}

impl VersionManager {
    /// Create a new version manager
    ///
    /// # Errors
    ///
    /// Returns [`VersionError::NoSupportedVersions`] if the provided vector is empty.
    pub fn new(supported_versions: Vec<Version>) -> Result<Self, VersionError> {
        if supported_versions.is_empty() {
            return Err(VersionError::NoSupportedVersions);
        }

        let mut versions = supported_versions;
        versions.sort_by(|a, b| b.cmp(a)); // Sort newest first

        let current_version = versions[0].clone();

        Ok(Self {
            supported_versions: versions,
            current_version,
        })
    }

    /// Create a version manager populated with every MCP version known to this build.
    ///
    /// `Version::known_versions()` is a const-built list maintained in this crate; an
    /// empty result would be a programming error in this crate, not a runtime
    /// condition, so the panic message identifies that as the contract.
    pub fn with_default_versions() -> Self {
        Self::new(Version::known_versions())
            .expect("Version::known_versions() is non-empty by const construction")
    }
    /// Get the current version
    pub fn current_version(&self) -> &Version {
        &self.current_version
    }

    /// Get all supported versions
    pub fn supported_versions(&self) -> &[Version] {
        &self.supported_versions
    }

    /// Check if a version is supported
    pub fn is_version_supported(&self, version: &Version) -> bool {
        self.supported_versions.contains(version)
    }

    /// Find the best compatible version for a client request
    pub fn negotiate_version(&self, client_versions: &[Version]) -> Option<Version> {
        // Find the newest version that both client and server support
        for server_version in &self.supported_versions {
            if client_versions.contains(server_version) {
                return Some(server_version.clone());
            }
        }

        None
    }

    /// Check compatibility between two versions
    pub fn check_compatibility(
        &self,
        client_version: &Version,
        server_version: &Version,
    ) -> VersionCompatibility {
        if client_version == server_version {
            return VersionCompatibility::Compatible;
        }

        let reason =
            format!("Incompatible versions: client={client_version}, server={server_version}");
        VersionCompatibility::Incompatible(reason)
    }

    /// Get the minimum supported version
    pub fn minimum_version(&self) -> &Version {
        // SAFETY: Constructor ensures non-empty via Result<T, VersionError::NoSupportedVersions>
        self.supported_versions
            .last()
            .expect("BUG: VersionManager has no versions (constructor should prevent this)")
    }

    /// Get the maximum supported version  
    pub fn maximum_version(&self) -> &Version {
        &self.supported_versions[0] // First because sorted newest first
    }

    /// Check if a version requirement is satisfied
    pub fn satisfies_requirement(
        &self,
        version: &Version,
        requirement: &VersionRequirement,
    ) -> bool {
        match requirement {
            VersionRequirement::Exact(required) => version == required,
            VersionRequirement::Minimum(min) => version >= min,
            VersionRequirement::Maximum(max) => version <= max,
            VersionRequirement::Range(min, max) => version >= min && version <= max,
            VersionRequirement::Any(versions) => versions.contains(version),
        }
    }
}

impl Default for VersionManager {
    fn default() -> Self {
        Self::with_default_versions()
    }
}

impl VersionRequirement {
    /// Create an exact version requirement
    pub fn exact(version: Version) -> Self {
        Self::Exact(version)
    }

    /// Create a minimum version requirement
    pub fn minimum(version: Version) -> Self {
        Self::Minimum(version)
    }

    /// Create a maximum version requirement
    pub fn maximum(version: Version) -> Self {
        Self::Maximum(version)
    }

    /// Create a version range requirement
    ///
    /// # Errors
    ///
    /// Returns [`VersionError::InvalidRange`] if `min` is greater than `max`.
    pub fn range(min: Version, max: Version) -> Result<Self, VersionError> {
        if min > max {
            return Err(VersionError::InvalidRange(min, max));
        }
        Ok(Self::Range(min, max))
    }

    /// Create an "any of" requirement
    ///
    /// # Errors
    ///
    /// Returns [`VersionError::EmptyVersionList`] if the provided vector is empty.
    pub fn any(versions: Vec<Version>) -> Result<Self, VersionError> {
        if versions.is_empty() {
            return Err(VersionError::EmptyVersionList);
        }
        Ok(Self::Any(versions))
    }

    /// Check if a version satisfies this requirement
    pub fn is_satisfied_by(&self, version: &Version) -> bool {
        match self {
            Self::Exact(required) => version == required,
            Self::Minimum(min) => version >= min,
            Self::Maximum(max) => version <= max,
            Self::Range(min, max) => version >= min && version <= max,
            Self::Any(versions) => versions.contains(version),
        }
    }
}

/// Version-related errors
#[derive(Debug, Clone, thiserror::Error)]
pub enum VersionError {
    /// Invalid version format
    #[error("Invalid version format: {0}")]
    InvalidFormat(String),
    /// Invalid year
    #[error("Invalid year: {0}")]
    InvalidYear(String),
    /// Invalid month
    #[error("Invalid month: {0} (must be 1-12)")]
    InvalidMonth(String),
    /// Invalid day
    #[error("Invalid day: {0} (must be 1-31)")]
    InvalidDay(String),
    /// No supported versions
    #[error("No supported versions provided")]
    NoSupportedVersions,
    /// Invalid version range
    #[error("Invalid version range: {0} > {1}")]
    InvalidRange(Version, Version),
    /// Empty version list
    #[error("Empty version list")]
    EmptyVersionList,
}

/// Utility functions for version management
pub mod utils {
    use super::*;

    /// Parse multiple versions from strings
    ///
    /// # Errors
    ///
    /// Returns [`VersionError`] if any version string cannot be parsed.
    pub fn parse_versions(version_strings: &[&str]) -> Result<Vec<Version>, VersionError> {
        version_strings.iter().map(|s| s.parse()).collect()
    }

    /// Find the newest version in a list
    pub fn newest_version(versions: &[Version]) -> Option<&Version> {
        versions.iter().max()
    }

    /// Find the oldest version in a list
    pub fn oldest_version(versions: &[Version]) -> Option<&Version> {
        versions.iter().min()
    }

    /// Check if all versions in a list are compatible with each other
    pub fn are_all_compatible(versions: &[Version]) -> bool {
        if versions.len() < 2 {
            return true;
        }

        let first = &versions[0];
        versions.iter().all(|v| first.is_compatible_with(v))
    }

    /// Get a human-readable description of version compatibility
    pub fn compatibility_description(compatibility: &VersionCompatibility) -> String {
        match compatibility {
            VersionCompatibility::Compatible => "Fully compatible".to_string(),
            VersionCompatibility::Incompatible(reason) => {
                format!("Incompatible: {reason}")
            }
        }
    }
}

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

    #[test]
    fn test_version_creation() {
        let version = Version::new(2025, 6, 18).unwrap();
        assert_eq!(version.year, 2025);
        assert_eq!(version.month, 6);
        assert_eq!(version.day, 18);

        // Invalid month should fail
        assert!(Version::new(2025, 13, 18).is_err());

        // Invalid day should fail
        assert!(Version::new(2025, 6, 32).is_err());
    }

    #[test]
    fn test_version_parsing() {
        let version: Version = "2025-11-25".parse().unwrap();
        assert_eq!(version, Version::new(2025, 11, 25).unwrap());

        // Invalid format should fail
        assert!("2025/06/18".parse::<Version>().is_err());
        assert!("invalid".parse::<Version>().is_err());
    }

    #[test]
    fn test_version_comparison() {
        let v1 = Version::new(2025, 11, 25).unwrap();
        let v2 = Version::new(2024, 11, 5).unwrap();
        let v3 = Version::new(2025, 11, 25).unwrap();

        assert!(v1 > v2);
        assert!(v1.is_newer_than(&v2));
        assert!(v2.is_older_than(&v1));
        assert_eq!(v1, v3);
    }

    #[test]
    fn test_version_compatibility() {
        let v1 = Version::new(2025, 11, 25).unwrap();
        let v2 = Version::new(2025, 12, 1).unwrap();
        let v3 = Version::new(2024, 6, 18).unwrap(); // Different year

        assert!(!v1.is_compatible_with(&v2));
        assert!(!v1.is_compatible_with(&v3));
    }

    #[test]
    fn test_version_manager() {
        let versions = vec![
            Version::new(2025, 11, 25).unwrap(),
            Version::new(2024, 11, 5).unwrap(),
        ];

        let manager = VersionManager::new(versions).unwrap();

        assert_eq!(
            manager.current_version(),
            &Version::new(2025, 11, 25).unwrap()
        );
        assert!(manager.is_version_supported(&Version::new(2024, 11, 5).unwrap()));
        assert!(!manager.is_version_supported(&Version::new(2023, 1, 1).unwrap()));
    }

    #[test]
    fn test_version_negotiation() {
        let manager = VersionManager::default();

        let client_versions = vec![
            Version::new(2024, 11, 5).unwrap(),
            Version::new(2025, 11, 25).unwrap(),
        ];

        let negotiated = manager.negotiate_version(&client_versions);
        assert_eq!(negotiated, Some(Version::new(2025, 11, 25).unwrap()));
    }

    #[test]
    fn test_version_requirements() {
        let version = Version::new(2025, 11, 25).unwrap();

        let exact_req = VersionRequirement::exact(version.clone());
        assert!(exact_req.is_satisfied_by(&version));

        let min_req = VersionRequirement::minimum(Version::new(2024, 1, 1).unwrap());
        assert!(min_req.is_satisfied_by(&version));

        let max_req = VersionRequirement::maximum(Version::new(2024, 1, 1).unwrap());
        assert!(!max_req.is_satisfied_by(&version));
    }

    #[test]
    fn test_compatibility_checking() {
        let manager = VersionManager::default();

        let v1 = Version::new(2025, 11, 25).unwrap();
        let v2 = Version::new(2025, 12, 1).unwrap();
        let v3 = Version::new(2024, 1, 1).unwrap();

        // Exact match only
        let compat = manager.check_compatibility(&v1, &v2);
        assert!(matches!(compat, VersionCompatibility::Incompatible(_)));

        // Different year - incompatible
        let compat = manager.check_compatibility(&v1, &v3);
        assert!(matches!(compat, VersionCompatibility::Incompatible(_)));

        // Exact match - compatible
        let compat = manager.check_compatibility(&v1, &v1);
        assert_eq!(compat, VersionCompatibility::Compatible);
    }

    #[test]
    fn test_utils() {
        let versions = utils::parse_versions(&["2025-11-25", "2024-11-05"]).unwrap();
        assert_eq!(versions.len(), 2);

        let newest = utils::newest_version(&versions);
        assert_eq!(newest, Some(&Version::new(2025, 11, 25).unwrap()));

        let oldest = utils::oldest_version(&versions);
        assert_eq!(oldest, Some(&Version::new(2024, 11, 5).unwrap()));
    }

    // Property-based tests for comprehensive coverage
    proptest! {
        #[test]
        fn test_version_parse_roundtrip(
            year in 2020u16..2030u16,
            month in 1u8..=12u8,
            day in 1u8..=28u8, // Use 28 to avoid month-specific day validation
        ) {
            let version = Version::new(year, month, day)?;
            let string = version.to_date_string();
            let parsed = Version::from_date_string(&string)?;
            prop_assert_eq!(version, parsed);
        }

        #[test]
        fn test_version_comparison_transitive(
            y1 in 2020u16..2030u16,
            m1 in 1u8..=12u8,
            d1 in 1u8..=28u8,
            y2 in 2020u16..2030u16,
            m2 in 1u8..=12u8,
            d2 in 1u8..=28u8,
            y3 in 2020u16..2030u16,
            m3 in 1u8..=12u8,
            d3 in 1u8..=28u8,
        ) {
            let v1 = Version::new(y1, m1, d1)?;
            let v2 = Version::new(y2, m2, d2)?;
            let v3 = Version::new(y3, m3, d3)?;

            // Transitivity: if v1 < v2 and v2 < v3, then v1 < v3
            if v1 < v2 && v2 < v3 {
                prop_assert!(v1 < v3);
            }
        }

        #[test]
        fn test_version_compatibility_symmetric(
            year in 2020u16..2030u16,
            m1 in 1u8..=12u8,
            d1 in 1u8..=28u8,
            m2 in 1u8..=12u8,
            d2 in 1u8..=28u8,
        ) {
            let v1 = Version::new(year, m1, d1)?;
            let v2 = Version::new(year, m2, d2)?;

            // Same-year versions should be compatible in both directions
            prop_assert_eq!(v1.is_compatible_with(&v2), v2.is_compatible_with(&v1));
        }

        #[test]
        fn test_invalid_month_rejected(
            year in 2020u16..2030u16,
            month in 13u8..=255u8,
            day in 1u8..=28u8,
        ) {
            prop_assert!(Version::new(year, month, day).is_err());
        }

        #[test]
        fn test_invalid_day_rejected(
            year in 2020u16..2030u16,
            month in 1u8..=12u8,
            day in 32u8..=255u8,
        ) {
            prop_assert!(Version::new(year, month, day).is_err());
        }
    }
}