mcpkit-server 0.6.0

Server implementation for mcpkit
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
//! Typestate connection management for MCP servers.
//!
//! This module implements the typestate pattern for managing
//! connection lifecycle, ensuring compile-time correctness of
//! state transitions.
//!
//! # Connection Lifecycle
//!
//! ```text
//! Disconnected -> Connected -> Initializing -> Ready -> Closing
//! ```
//!
//! Each state transition is enforced at compile time through
//! different types, preventing invalid state transitions.

use mcpkit_core::capability::{ClientCapabilities, ServerCapabilities, ServerInfo};
use mcpkit_core::error::McpError;
use mcpkit_core::protocol_version::ProtocolVersion;
use std::marker::PhantomData;
use std::sync::Arc;

/// Connection state markers.
///
/// These types represent different states in the connection lifecycle.
/// They contain no data and are used purely for type-level state tracking.
pub mod markers {
    // Note: The types in this module are also re-exported as `state::state::*`
    // for backwards compatibility with v0.2.5.
    /// Connection is disconnected (initial state).
    #[derive(Debug, Clone, Copy)]
    pub struct Disconnected;

    /// Connection is established but not initialized.
    #[derive(Debug, Clone, Copy)]
    pub struct Connected;

    /// Connection is in the initialization handshake.
    #[derive(Debug, Clone, Copy)]
    pub struct Initializing;

    /// Connection is fully initialized and ready for requests.
    #[derive(Debug, Clone, Copy)]
    pub struct Ready;

    /// Connection is closing down.
    #[derive(Debug, Clone, Copy)]
    pub struct Closing;
}

/// Backwards compatibility alias for the `markers` module.
///
/// This module was renamed from `state` to `markers` in v0.2.6.
/// This alias is provided for backwards compatibility with v0.2.5.
#[doc(hidden)]
#[deprecated(since = "0.2.6", note = "Use `markers` module instead")]
pub mod state {
    pub use super::markers::*;
}

/// Internal connection data shared across states.
#[derive(Debug)]
pub struct ConnectionData {
    /// Client capabilities (set after initialization).
    pub client_capabilities: Option<ClientCapabilities>,
    /// Server capabilities advertised.
    pub server_capabilities: ServerCapabilities,
    /// Server information.
    pub server_info: ServerInfo,
    /// Protocol version negotiated.
    ///
    /// Stored as a type-safe [`ProtocolVersion`] enum for feature detection.
    pub protocol_version: Option<ProtocolVersion>,
    /// Session ID if applicable.
    pub session_id: Option<String>,
}

impl ConnectionData {
    /// Create new connection data.
    #[must_use]
    pub const fn new(server_info: ServerInfo, server_capabilities: ServerCapabilities) -> Self {
        Self {
            client_capabilities: None,
            server_capabilities,
            server_info,
            protocol_version: None,
            session_id: None,
        }
    }
}

/// A typestate connection that tracks lifecycle state at the type level.
///
/// The state parameter `S` ensures that only valid operations are
/// available for each connection state.
///
/// # Example
///
/// ```rust
/// use mcpkit_server::state::{Connection, markers};
/// use mcpkit_core::capability::{ServerInfo, ServerCapabilities};
///
/// // Start disconnected
/// let conn: Connection<markers::Disconnected> = Connection::new(
///     ServerInfo::new("my-server", "1.0.0"),
///     ServerCapabilities::new().with_tools(),
/// );
///
/// // The typestate pattern ensures compile-time safety:
/// // - A Disconnected connection can only call connect()
/// // - A Connected connection can only call initialize() or close()
/// // - A Ready connection can access capabilities
/// ```
pub struct Connection<S> {
    /// Shared connection data.
    inner: Arc<ConnectionData>,
    /// Phantom data to track state type.
    _state: PhantomData<S>,
}

impl<S> Clone for Connection<S> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            _state: PhantomData,
        }
    }
}

impl<S> std::fmt::Debug for Connection<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Connection")
            .field("inner", &self.inner)
            .field("state", &std::any::type_name::<S>())
            .finish()
    }
}

impl Connection<markers::Disconnected> {
    /// Create a new disconnected connection.
    #[must_use]
    pub fn new(server_info: ServerInfo, server_capabilities: ServerCapabilities) -> Self {
        Self {
            inner: Arc::new(ConnectionData::new(server_info, server_capabilities)),
            _state: PhantomData,
        }
    }

    /// Connect to establish a transport connection.
    ///
    /// This transitions from `Disconnected` to `Connected` state.
    pub async fn connect(self) -> Result<Connection<markers::Connected>, McpError> {
        // In a real implementation, this would establish the transport
        Ok(Connection {
            inner: self.inner,
            _state: PhantomData,
        })
    }
}

impl Connection<markers::Connected> {
    /// Start the initialization handshake.
    ///
    /// This transitions from `Connected` to `Initializing` state.
    pub async fn initialize(
        self,
        _protocol_version: ProtocolVersion,
    ) -> Result<Connection<markers::Initializing>, McpError> {
        // In a real implementation, this would send the initialize request
        Ok(Connection {
            inner: self.inner,
            _state: PhantomData,
        })
    }

    /// Close the connection before initialization.
    pub async fn close(self) -> Result<(), McpError> {
        // Clean up resources
        Ok(())
    }
}

impl Connection<markers::Initializing> {
    /// Complete the initialization handshake.
    ///
    /// This transitions from `Initializing` to `Ready` state.
    pub async fn complete(
        self,
        client_capabilities: ClientCapabilities,
        protocol_version: ProtocolVersion,
    ) -> Result<Connection<markers::Ready>, McpError> {
        // Update the connection data with negotiated values
        // In a real implementation, we'd use interior mutability
        let mut data = ConnectionData::new(
            self.inner.server_info.clone(),
            self.inner.server_capabilities.clone(),
        );
        data.client_capabilities = Some(client_capabilities);
        data.protocol_version = Some(protocol_version);

        Ok(Connection {
            inner: Arc::new(data),
            _state: PhantomData,
        })
    }

    /// Abort initialization.
    pub async fn abort(self) -> Result<Connection<markers::Disconnected>, McpError> {
        Ok(Connection {
            inner: self.inner,
            _state: PhantomData,
        })
    }
}

impl Connection<markers::Ready> {
    /// Get the client capabilities.
    ///
    /// # Panics
    ///
    /// This should never panic if the connection was properly initialized
    /// through the typestate transitions. Use `try_client_capabilities()`
    /// for a fallible version.
    #[must_use]
    pub fn client_capabilities(&self) -> &ClientCapabilities {
        self.inner
            .client_capabilities
            .as_ref()
            .expect("Ready connection must have client capabilities")
    }

    /// Try to get the client capabilities.
    ///
    /// Returns `None` if capabilities were not set (should not happen in normal use).
    #[must_use]
    pub fn try_client_capabilities(&self) -> Option<&ClientCapabilities> {
        self.inner.client_capabilities.as_ref()
    }

    /// Get the server capabilities.
    #[must_use]
    pub fn server_capabilities(&self) -> &ServerCapabilities {
        &self.inner.server_capabilities
    }

    /// Get the server info.
    #[must_use]
    pub fn server_info(&self) -> &ServerInfo {
        &self.inner.server_info
    }

    /// Get the negotiated protocol version.
    ///
    /// # Panics
    ///
    /// This should never panic if the connection was properly initialized
    /// through the typestate transitions. Use `try_protocol_version()`
    /// for a fallible version.
    #[must_use]
    pub fn protocol_version(&self) -> ProtocolVersion {
        self.inner
            .protocol_version
            .expect("Ready connection must have protocol version")
    }

    /// Try to get the negotiated protocol version.
    ///
    /// Returns `None` if version was not set (should not happen in normal use).
    #[must_use]
    pub fn try_protocol_version(&self) -> Option<ProtocolVersion> {
        self.inner.protocol_version
    }

    /// Start graceful shutdown.
    ///
    /// This transitions from `Ready` to `Closing` state.
    pub async fn shutdown(self) -> Result<Connection<markers::Closing>, McpError> {
        Ok(Connection {
            inner: self.inner,
            _state: PhantomData,
        })
    }
}

impl Connection<markers::Closing> {
    /// Complete the shutdown and disconnect.
    pub async fn disconnect(self) -> Result<(), McpError> {
        // Clean up resources
        Ok(())
    }
}

/// A state machine wrapper for connections that allows runtime state tracking.
///
/// This provides an alternative to the pure typestate approach when
/// runtime state inspection is needed.
#[derive(Debug)]
pub enum ConnectionState {
    /// Not connected.
    Disconnected(Connection<markers::Disconnected>),
    /// Connected but not initialized.
    Connected(Connection<markers::Connected>),
    /// In initialization handshake.
    Initializing(Connection<markers::Initializing>),
    /// Ready for requests.
    Ready(Connection<markers::Ready>),
    /// Closing down.
    Closing(Connection<markers::Closing>),
}

impl ConnectionState {
    /// Create a new disconnected connection state.
    #[must_use]
    pub fn new(server_info: ServerInfo, server_capabilities: ServerCapabilities) -> Self {
        Self::Disconnected(Connection::new(server_info, server_capabilities))
    }

    /// Check if the connection is ready for requests.
    #[must_use]
    pub const fn is_ready(&self) -> bool {
        matches!(self, Self::Ready(_))
    }

    /// Check if the connection is disconnected.
    #[must_use]
    pub const fn is_disconnected(&self) -> bool {
        matches!(self, Self::Disconnected(_))
    }

    /// Get the current state name.
    #[must_use]
    pub const fn state_name(&self) -> &'static str {
        match self {
            Self::Disconnected(_) => "Disconnected",
            Self::Connected(_) => "Connected",
            Self::Initializing(_) => "Initializing",
            Self::Ready(_) => "Ready",
            Self::Closing(_) => "Closing",
        }
    }
}

/// Transition events for connection state changes.
#[derive(Debug, Clone)]
pub enum ConnectionEvent {
    /// Connection established.
    Connected,
    /// Initialization started.
    InitializeStarted,
    /// Initialization completed successfully.
    InitializeCompleted {
        /// Negotiated protocol version.
        protocol_version: ProtocolVersion,
    },
    /// Initialization failed.
    InitializeFailed {
        /// Error message.
        error: String,
    },
    /// Shutdown requested.
    ShutdownRequested,
    /// Connection closed.
    Disconnected,
}

#[cfg(test)]
mod tests {
    use super::*;
    use mcpkit_core::capability::{ServerCapabilities, ServerInfo};
    use mcpkit_core::protocol_version::ProtocolVersion;

    #[test]
    fn test_connection_creation() {
        let info = ServerInfo::new("test", "1.0.0");
        let caps = ServerCapabilities::default();
        let conn: Connection<markers::Disconnected> = Connection::new(info, caps);

        assert!(std::any::type_name_of_val(&conn._state).contains("Disconnected"));
    }

    #[tokio::test]
    async fn test_connection_lifecycle() -> Result<(), Box<dyn std::error::Error>> {
        let info = ServerInfo::new("test", "1.0.0");
        let caps = ServerCapabilities::default();

        // Start disconnected
        let conn = Connection::new(info, caps);

        // Connect
        let conn = conn.connect().await?;

        // Initialize
        let conn = conn.initialize(ProtocolVersion::V2025_11_25).await?;

        // Complete
        let conn = conn
            .complete(ClientCapabilities::default(), ProtocolVersion::V2025_11_25)
            .await?;

        // Verify ready state
        assert_eq!(conn.protocol_version(), ProtocolVersion::V2025_11_25);

        // Shutdown
        let conn = conn.shutdown().await?;

        // Disconnect
        conn.disconnect().await?;

        Ok(())
    }

    #[test]
    fn test_connection_state_enum() {
        let info = ServerInfo::new("test", "1.0.0");
        let caps = ServerCapabilities::default();

        let state = ConnectionState::new(info, caps);
        assert!(state.is_disconnected());
        assert!(!state.is_ready());
        assert_eq!(state.state_name(), "Disconnected");
    }
}