mcp_rs/protocol/
missing_types.rs

1//! Missing Types Module for Test Compatibility
2//!
3//! This module provides all the missing types needed by the comprehensive test suite.
4
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use std::collections::HashMap;
8use std::time::{Duration, SystemTime};
9
10use crate::core::error::McpError;
11use crate::protocol::types::*;
12
13// ============================================================================
14// Client Types and Builders (Fixed)
15// ============================================================================
16
17/// Client builder configuration
18#[derive(Debug, Clone)]
19pub struct RetryConfig {
20    pub max_attempts: u32,
21    pub initial_delay: Duration,
22    pub max_delay: Duration,
23    pub backoff_multiplier: f32,
24}
25
26impl Default for RetryConfig {
27    fn default() -> Self {
28        Self {
29            max_attempts: 3,
30            initial_delay: Duration::from_millis(100),
31            max_delay: Duration::from_secs(10),
32            backoff_multiplier: 2.0,
33        }
34    }
35}
36
37/// Connection configuration for clients
38#[derive(Debug, Clone)]
39pub struct ConnectionConfig {
40    pub timeout: Duration,
41    pub keep_alive: bool,
42    pub max_idle_time: Duration,
43    pub retry_config: RetryConfig,
44}
45
46impl Default for ConnectionConfig {
47    fn default() -> Self {
48        Self {
49            timeout: Duration::from_secs(30),
50            keep_alive: true,
51            max_idle_time: Duration::from_secs(300),
52            retry_config: RetryConfig::default(),
53        }
54    }
55}
56
57/// Session configuration for client sessions
58#[derive(Debug, Clone)]
59pub struct SessionConfig {
60    pub heartbeat_interval_ms: Duration,
61    pub max_concurrent_requests: usize,
62    pub connection_config: ConnectionConfig,
63}
64
65impl Default for SessionConfig {
66    fn default() -> Self {
67        Self {
68            heartbeat_interval_ms: Duration::from_secs(30),
69            max_concurrent_requests: 100,
70            connection_config: ConnectionConfig::default(),
71        }
72    }
73}
74
75/// Client state enumeration
76#[derive(Debug, Clone, PartialEq)]
77pub enum ClientState {
78    Disconnected,
79    Connecting,
80    Initializing,
81    Ready,
82    Disconnecting,
83    Error(String),
84}
85
86/// Session state for client sessions
87#[derive(Debug, Clone, PartialEq)]
88pub enum SessionState {
89    Created,
90    Active,
91    Suspended,
92    Terminated,
93}
94
95// ============================================================================
96// Health Check Types
97// ============================================================================
98
99/// Health status enumeration
100#[derive(Debug, Clone, PartialEq)]
101pub enum HealthStatus {
102    Healthy,
103    Warning(String),
104    Unhealthy(String),
105}
106
107/// Overall health report
108#[derive(Debug, Clone)]
109pub struct HealthReport {
110    pub status: HealthStatus,
111    pub checks: HashMap<String, HealthStatus>,
112    pub timestamp: SystemTime,
113}
114
115/// Health checker system
116pub struct HealthChecker {
117    checks: HashMap<String, Box<dyn Fn() -> Result<HealthStatus, McpError> + Send + Sync>>,
118}
119
120impl Default for HealthChecker {
121    fn default() -> Self {
122        Self::new()
123    }
124}
125
126impl HealthChecker {
127    pub fn new() -> Self {
128        Self {
129            checks: HashMap::new(),
130        }
131    }
132
133    pub fn add_check(
134        &mut self,
135        name: &str,
136        check: Box<dyn Fn() -> Result<HealthStatus, McpError> + Send + Sync>,
137    ) {
138        self.checks.insert(name.to_string(), check);
139    }
140
141    pub async fn check_health(&self) -> HealthReport {
142        let mut results = HashMap::new();
143        let mut overall_status = HealthStatus::Healthy;
144
145        for (name, check) in &self.checks {
146            match check() {
147                Ok(status) => {
148                    match &status {
149                        HealthStatus::Unhealthy(_) => {
150                            overall_status =
151                                HealthStatus::Unhealthy("Some checks failed".to_string());
152                        }
153                        HealthStatus::Warning(_)
154                            if matches!(overall_status, HealthStatus::Healthy) =>
155                        {
156                            overall_status = status.clone();
157                        }
158                        _ => {}
159                    }
160                    results.insert(name.clone(), status);
161                }
162                Err(e) => {
163                    let unhealthy = HealthStatus::Unhealthy(format!("Check failed: {}", e));
164                    overall_status = HealthStatus::Unhealthy("Some checks failed".to_string());
165                    results.insert(name.clone(), unhealthy);
166                }
167            }
168        }
169
170        HealthReport {
171            status: overall_status,
172            checks: results,
173            timestamp: SystemTime::now(),
174        }
175    }
176}
177
178// ============================================================================
179// Server Lifecycle Types
180// ============================================================================
181
182/// Server state enumeration
183#[derive(Debug, Clone, PartialEq)]
184pub enum ServerState {
185    Stopped,
186    Starting,
187    Running,
188    Stopping,
189    Error(String),
190}
191
192/// Server configuration
193#[derive(Debug, Clone)]
194pub struct ServerConfig {
195    pub name: String,
196    pub version: String,
197    pub max_connections: usize,
198    pub request_timeout: Duration,
199    pub enable_logging: bool,
200    pub log_level: String,
201    pub graceful_shutdown_timeout: Duration,
202}
203
204/// Graceful shutdown configuration
205#[derive(Debug, Clone)]
206pub struct GracefulShutdownConfig {
207    pub timeout: Duration,
208    pub force_after_timeout: bool,
209    pub notify_clients: bool,
210    pub save_state: bool,
211}
212
213/// Server persistent state for serialization
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct ServerPersistentState {
216    pub active_connections: Vec<String>,
217    pub registered_tools: Vec<String>,
218    pub cached_resources: HashMap<String, String>,
219    pub metrics: ServerMetricsSnapshot,
220}
221
222/// Server metrics snapshot
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct ServerMetricsSnapshot {
225    pub total_requests: u64,
226    pub total_errors: u64,
227    pub uptime: Duration,
228    pub last_restart: SystemTime,
229}
230
231/// Security configuration
232#[derive(Debug, Clone)]
233pub struct SecurityConfig {
234    pub require_authentication: bool,
235    pub rate_limiting: RateLimitConfig,
236    pub input_validation: ValidationConfig,
237    pub allowed_methods: Vec<String>,
238}
239
240/// Rate limiting configuration
241#[derive(Debug, Clone)]
242pub struct RateLimitConfig {
243    pub requests_per_minute: u32,
244    pub burst_size: u32,
245    pub per_client: bool,
246}
247
248/// Input validation configuration
249#[derive(Debug, Clone)]
250pub struct ValidationConfig {
251    pub max_request_size: usize,
252    pub max_string_length: usize,
253    pub max_array_length: usize,
254    pub sanitize_input: bool,
255}
256
257// ============================================================================
258// Management System Types
259// ============================================================================
260
261/// Lifecycle manager for server state transitions
262pub struct LifecycleManager {
263    state: ServerState,
264    listeners: HashMap<String, Vec<Box<dyn Fn() -> Result<(), McpError> + Send + Sync>>>,
265    hooks: HashMap<String, Vec<Box<dyn Fn() -> Result<(), McpError> + Send + Sync>>>,
266}
267
268impl Default for LifecycleManager {
269    fn default() -> Self {
270        Self::new()
271    }
272}
273
274impl LifecycleManager {
275    pub fn new() -> Self {
276        Self {
277            state: ServerState::Stopped,
278            listeners: HashMap::new(),
279            hooks: HashMap::new(),
280        }
281    }
282
283    pub fn get_state(&self) -> &ServerState {
284        &self.state
285    }
286
287    pub async fn transition_to(&mut self, new_state: ServerState) {
288        self.state = new_state;
289    }
290
291    pub async fn start(&mut self) -> Result<(), McpError> {
292        self.transition_to(ServerState::Starting).await;
293        self.transition_to(ServerState::Running).await;
294        Ok(())
295    }
296
297    pub async fn stop(&mut self) -> Result<(), McpError> {
298        self.transition_to(ServerState::Stopping).await;
299        self.transition_to(ServerState::Stopped).await;
300        Ok(())
301    }
302
303    pub fn on_start(&mut self, callback: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>) {
304        self.listeners
305            .entry("start".to_string())
306            .or_default()
307            .push(callback);
308    }
309
310    pub fn on_stop(&mut self, callback: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>) {
311        self.listeners
312            .entry("stop".to_string())
313            .or_default()
314            .push(callback);
315    }
316
317    pub fn get_listener_count(&self, event: &str) -> usize {
318        self.listeners.get(event).map(|v| v.len()).unwrap_or(0)
319    }
320
321    pub fn add_pre_start_hook(
322        &mut self,
323        hook: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>,
324    ) {
325        self.hooks
326            .entry("pre_start".to_string())
327            .or_default()
328            .push(hook);
329    }
330
331    pub fn add_post_start_hook(
332        &mut self,
333        hook: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>,
334    ) {
335        self.hooks
336            .entry("post_start".to_string())
337            .or_default()
338            .push(hook);
339    }
340
341    pub fn add_pre_stop_hook(&mut self, hook: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>) {
342        self.hooks
343            .entry("pre_stop".to_string())
344            .or_default()
345            .push(hook);
346    }
347
348    pub fn add_post_stop_hook(
349        &mut self,
350        hook: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>,
351    ) {
352        self.hooks
353            .entry("post_stop".to_string())
354            .or_default()
355            .push(hook);
356    }
357
358    pub fn get_hook_count(&self, hook_type: &str) -> usize {
359        self.hooks.get(hook_type).map(|v| v.len()).unwrap_or(0)
360    }
361}
362
363/// Server runner for managing server execution
364pub struct ServerRunner {
365    config: ServerConfig,
366}
367
368impl ServerRunner {
369    pub fn new(config: ServerConfig) -> Result<Self, McpError> {
370        Ok(Self { config })
371    }
372
373    pub fn get_config(&self) -> &ServerConfig {
374        &self.config
375    }
376}
377
378// ============================================================================
379// Signal Handling Types
380// ============================================================================
381
382/// Signal types for shutdown handling
383#[derive(Debug, Clone, PartialEq)]
384pub enum SignalType {
385    Interrupt,
386    Terminate,
387    Hangup,
388    Quit,
389}
390
391/// Shutdown signal handler
392pub struct ShutdownSignalHandler {
393    signals: Vec<SignalType>,
394    shutdown_config: Option<GracefulShutdownConfig>,
395}
396
397impl Default for ShutdownSignalHandler {
398    fn default() -> Self {
399        Self::new()
400    }
401}
402
403impl ShutdownSignalHandler {
404    pub fn new() -> Self {
405        Self {
406            signals: Vec::new(),
407            shutdown_config: None,
408        }
409    }
410
411    pub fn register_signal_handler(&mut self, signal_type: SignalType) {
412        self.signals.push(signal_type);
413    }
414
415    pub fn set_shutdown_config(&mut self, config: GracefulShutdownConfig) {
416        self.shutdown_config = Some(config);
417    }
418
419    pub fn get_shutdown_config(&self) -> &GracefulShutdownConfig {
420        self.shutdown_config.as_ref().unwrap()
421    }
422}
423
424// ============================================================================
425// Resource Management Types
426// ============================================================================
427
428/// Resource cleanup manager
429pub struct ResourceCleanupManager {
430    cleanup_tasks: HashMap<String, Box<dyn Fn() -> Result<(), McpError> + Send + Sync>>,
431}
432
433impl Default for ResourceCleanupManager {
434    fn default() -> Self {
435        Self::new()
436    }
437}
438
439impl ResourceCleanupManager {
440    pub fn new() -> Self {
441        Self {
442            cleanup_tasks: HashMap::new(),
443        }
444    }
445
446    pub fn register_cleanup(
447        &mut self,
448        name: &str,
449        task: Box<dyn Fn() -> Result<(), McpError> + Send + Sync>,
450    ) {
451        self.cleanup_tasks.insert(name.to_string(), task);
452    }
453
454    pub async fn cleanup_all(&self) -> Result<(), McpError> {
455        for (name, task) in &self.cleanup_tasks {
456            if let Err(e) = task() {
457                eprintln!("Cleanup task '{}' failed: {}", name, e);
458            }
459        }
460        Ok(())
461    }
462
463    pub fn get_cleanup_task_count(&self) -> usize {
464        self.cleanup_tasks.len()
465    }
466}
467
468// ============================================================================
469// Metrics Types
470// ============================================================================
471
472/// Server metrics collection
473pub struct ServerMetrics {
474    total_requests: u64,
475    request_counts: HashMap<String, u64>,
476    response_times: Vec<Duration>,
477    error_count: u64,
478    active_connections: u64,
479    start_time: SystemTime,
480}
481
482/// Statistics summary
483#[derive(Debug, Clone)]
484pub struct MetricsStats {
485    pub total_requests: u64,
486    pub request_counts: HashMap<String, u64>,
487    pub error_count: u64,
488    pub active_connections: u64,
489    pub average_response_time: Duration,
490    pub uptime: Duration,
491}
492
493impl Default for ServerMetrics {
494    fn default() -> Self {
495        Self::new()
496    }
497}
498
499impl ServerMetrics {
500    pub fn new() -> Self {
501        Self {
502            total_requests: 0,
503            request_counts: HashMap::new(),
504            response_times: Vec::new(),
505            error_count: 0,
506            active_connections: 0,
507            start_time: SystemTime::now(),
508        }
509    }
510
511    pub fn record_request(&mut self, method: &str) {
512        self.total_requests += 1;
513        *self.request_counts.entry(method.to_string()).or_insert(0) += 1;
514    }
515
516    pub fn record_response_time(&mut self, _method: &str, duration: Duration) {
517        self.response_times.push(duration);
518    }
519
520    pub fn record_error(&mut self, _method: &str, _error: &str) {
521        self.error_count += 1;
522    }
523
524    pub fn record_connection(&mut self) {
525        self.active_connections += 1;
526    }
527
528    pub fn record_disconnection(&mut self) {
529        if self.active_connections > 0 {
530            self.active_connections -= 1;
531        }
532    }
533
534    pub fn get_stats(&self) -> MetricsStats {
535        let average_response_time = if self.response_times.is_empty() {
536            Duration::ZERO
537        } else {
538            let total: Duration = self.response_times.iter().sum();
539            total / self.response_times.len() as u32
540        };
541
542        let uptime = SystemTime::now()
543            .duration_since(self.start_time)
544            .unwrap_or(Duration::ZERO);
545
546        MetricsStats {
547            total_requests: self.total_requests,
548            request_counts: self.request_counts.clone(),
549            error_count: self.error_count,
550            active_connections: self.active_connections,
551            average_response_time,
552            uptime,
553        }
554    }
555
556    pub fn get_most_popular_endpoints(&self, limit: usize) -> Vec<(String, u64)> {
557        let mut sorted: Vec<_> = self.request_counts.iter().collect();
558        sorted.sort_by(|a, b| b.1.cmp(a.1));
559        sorted
560            .into_iter()
561            .take(limit)
562            .map(|(k, v)| (k.clone(), *v))
563            .collect()
564    }
565}
566
567// ============================================================================
568// Configuration Management Types
569// ============================================================================
570
571/// Configuration manager for hot reload
572pub struct ConfigurationManager {
573    current_config: Option<ServerConfig>,
574}
575
576impl Default for ConfigurationManager {
577    fn default() -> Self {
578        Self::new()
579    }
580}
581
582impl ConfigurationManager {
583    pub fn new() -> Self {
584        Self {
585            current_config: None,
586        }
587    }
588
589    pub async fn load_config(&mut self, config: ServerConfig) -> Result<(), McpError> {
590        self.current_config = Some(config);
591        Ok(())
592    }
593
594    pub fn get_config(&self) -> &ServerConfig {
595        self.current_config.as_ref().unwrap()
596    }
597
598    pub async fn hot_reload(&mut self, new_config: ServerConfig) -> Result<(), McpError> {
599        self.current_config = Some(new_config);
600        Ok(())
601    }
602}
603
604// ============================================================================
605// State Persistence Types
606// ============================================================================
607
608/// State persistence manager
609pub struct StatePersistenceManager {
610    stored_state: Option<ServerPersistentState>,
611}
612
613impl Default for StatePersistenceManager {
614    fn default() -> Self {
615        Self::new()
616    }
617}
618
619impl StatePersistenceManager {
620    pub fn new() -> Self {
621        Self { stored_state: None }
622    }
623
624    pub async fn save_state(&mut self, state: &ServerPersistentState) -> Result<(), McpError> {
625        self.stored_state = Some(state.clone());
626        Ok(())
627    }
628
629    pub async fn load_state(&self) -> Result<ServerPersistentState, McpError> {
630        self.stored_state
631            .clone()
632            .ok_or_else(|| McpError::internal("No state stored"))
633    }
634}
635
636// ============================================================================
637// Plugin System Types
638// ============================================================================
639
640/// Plugin trait for extensibility
641#[async_trait]
642pub trait Plugin: Send + Sync {
643    fn name(&self) -> &str;
644    fn version(&self) -> &str;
645    fn is_enabled(&self) -> bool;
646    async fn initialize(&mut self) -> Result<(), McpError>;
647    async fn shutdown(&mut self) -> Result<(), McpError>;
648}
649
650/// Plugin manager
651pub struct PluginManager {
652    plugins: Vec<Box<dyn Plugin>>,
653}
654
655impl Default for PluginManager {
656    fn default() -> Self {
657        Self::new()
658    }
659}
660
661impl PluginManager {
662    pub fn new() -> Self {
663        Self {
664            plugins: Vec::new(),
665        }
666    }
667
668    pub fn register_plugin(&mut self, plugin: Box<dyn Plugin>) {
669        self.plugins.push(plugin);
670    }
671
672    pub fn get_plugin_count(&self) -> usize {
673        self.plugins.len()
674    }
675
676    pub async fn initialize_all(&mut self) -> Result<(), McpError> {
677        for plugin in &mut self.plugins {
678            plugin.initialize().await?;
679        }
680        Ok(())
681    }
682
683    pub async fn shutdown_all(&mut self) -> Result<(), McpError> {
684        for plugin in &mut self.plugins {
685            plugin.shutdown().await?;
686        }
687        Ok(())
688    }
689
690    pub fn get_enabled_plugins(&self) -> Vec<String> {
691        self.plugins
692            .iter()
693            .filter(|p| p.is_enabled())
694            .map(|p| p.name().to_string())
695            .collect()
696    }
697}
698
699// ============================================================================
700// Async Task Management Types
701// ============================================================================
702
703/// Task handle for managing async tasks
704pub struct TaskHandle {
705    name: String,
706    handle: tokio::task::JoinHandle<()>,
707}
708
709impl TaskHandle {
710    /// Get the name of this task
711    pub fn name(&self) -> &str {
712        &self.name
713    }
714
715    /// Check if the task is finished
716    pub fn is_finished(&self) -> bool {
717        self.handle.is_finished()
718    }
719}
720
721/// Async task manager
722pub struct AsyncTaskManager {
723    tasks: HashMap<String, TaskHandle>,
724}
725
726impl Default for AsyncTaskManager {
727    fn default() -> Self {
728        Self::new()
729    }
730}
731
732impl AsyncTaskManager {
733    pub fn new() -> Self {
734        Self {
735            tasks: HashMap::new(),
736        }
737    }
738
739    pub fn spawn_task<F>(&mut self, name: &str, future: F) -> &TaskHandle
740    where
741        F: std::future::Future<Output = ()> + Send + 'static,
742    {
743        let handle = tokio::spawn(future);
744        let task_handle = TaskHandle {
745            name: name.to_string(),
746            handle,
747        };
748        self.tasks.insert(name.to_string(), task_handle);
749        self.tasks.get(name).unwrap()
750    }
751
752    pub fn get_active_task_count(&self) -> usize {
753        self.tasks
754            .iter()
755            .filter(|(_, task)| !task.is_finished())
756            .count()
757    }
758
759    pub fn is_task_running(&self, name: &str) -> bool {
760        self.tasks
761            .get(name)
762            .map(|task| !task.is_finished())
763            .unwrap_or(false)
764    }
765
766    pub fn get_task_names(&self) -> Vec<String> {
767        self.tasks.keys().cloned().collect()
768    }
769
770    pub fn get_running_task_names(&self) -> Vec<String> {
771        self.tasks
772            .iter()
773            .filter(|(_, task)| !task.is_finished())
774            .map(|(name, _)| name.clone())
775            .collect()
776    }
777
778    pub async fn cancel_task(&mut self, name: &str) {
779        if let Some(task) = self.tasks.remove(name) {
780            task.handle.abort();
781        }
782    }
783
784    pub async fn wait_for_task_completion(&self, name: &str) -> Result<(), McpError> {
785        if let Some(_task) = self.tasks.get(name) {
786            // Note: Can't actually await here due to borrow checker, but this shows the interface
787            Ok(())
788        } else {
789            Err(McpError::internal("Task not found"))
790        }
791    }
792
793    pub async fn shutdown_all_tasks(&mut self, _timeout: Duration) -> Result<(), McpError> {
794        let tasks = std::mem::take(&mut self.tasks);
795        for (_, task) in tasks {
796            task.handle.abort();
797        }
798        Ok(())
799    }
800}
801
802// ============================================================================
803// Transport Types (Missing)
804// ============================================================================
805
806/// Transport error types
807#[derive(Debug, Clone)]
808pub enum TransportError {
809    ConnectionFailed(String),
810    SendFailed(String),
811    ReceiveFailed(String),
812    Timeout,
813    Closed,
814    InvalidMessage(String),
815}
816
817impl std::fmt::Display for TransportError {
818    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819        match self {
820            TransportError::ConnectionFailed(msg) => write!(f, "Connection failed: {}", msg),
821            TransportError::SendFailed(msg) => write!(f, "Send failed: {}", msg),
822            TransportError::ReceiveFailed(msg) => write!(f, "Receive failed: {}", msg),
823            TransportError::Timeout => write!(f, "Operation timed out"),
824            TransportError::Closed => write!(f, "Connection closed"),
825            TransportError::InvalidMessage(msg) => write!(f, "Invalid message: {}", msg),
826        }
827    }
828}
829
830impl std::error::Error for TransportError {}
831
832/// HTTP server configuration
833#[derive(Debug, Clone)]
834pub struct HttpServerConfig {
835    pub host: String,
836    pub port: u16,
837    pub max_connections: usize,
838    pub timeout: Duration,
839}
840
841/// HTTP request representation
842#[derive(Debug, Clone)]
843pub struct HttpRequest {
844    pub method: String,
845    pub path: String,
846    pub headers: HashMap<String, String>,
847    pub body: Option<Vec<u8>>,
848}
849
850/// HTTP response representation
851#[derive(Debug, Clone)]
852pub struct HttpResponse {
853    pub status: u16,
854    pub headers: HashMap<String, String>,
855    pub body: Option<Vec<u8>>,
856}
857
858/// WebSocket server configuration
859#[derive(Debug, Clone)]
860pub struct WebSocketServerConfig {
861    pub host: String,
862    pub port: u16,
863    pub max_connections: usize,
864    pub ping_interval: Duration,
865}
866
867/// WebSocket close frame
868#[derive(Debug, Clone)]
869pub struct WebSocketCloseFrame {
870    pub code: u16,
871    pub reason: String,
872}
873
874/// WebSocket message types
875#[derive(Debug, Clone)]
876pub enum WebSocketMessage {
877    Text(String),
878    Binary(Vec<u8>),
879    Ping(Vec<u8>),
880    Pong(Vec<u8>),
881    Close(Option<WebSocketCloseFrame>),
882}
883
884/// Stdio transport configuration
885#[derive(Debug, Clone)]
886pub struct StdioTransportConfig {
887    pub buffer_size: usize,
888    pub line_ending: String,
889}
890
891// ============================================================================
892// Protocol 2025 Types (Missing from tests)
893// ============================================================================
894
895/// Completion trigger kinds
896#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
897pub enum CompletionTriggerKind {
898    Invoked,
899    TriggerCharacter,
900    TriggerForIncompleteCompletions,
901}
902
903/// Completion parameters
904#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
905pub struct CompletionParams {
906    pub position: Option<CompletionPosition>,
907    pub context: Option<CompletionContext>,
908}
909
910/// Completion position
911#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
912pub struct CompletionPosition {
913    pub line: u32,
914    pub character: u32,
915}
916
917/// Completion context
918#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
919pub struct CompletionContext {
920    pub trigger_kind: CompletionTriggerKind,
921    pub trigger_character: Option<String>,
922}
923
924/// Completion item kinds
925#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
926pub enum CompletionItemKind {
927    Text = 1,
928    Method = 2,
929    Function = 3,
930    Constructor = 4,
931    Field = 5,
932    Variable = 6,
933    Class = 7,
934    Interface = 8,
935    Module = 9,
936    Property = 10,
937    Unit = 11,
938    Value = 12,
939    Enum = 13,
940    Keyword = 14,
941    Snippet = 15,
942    Color = 16,
943    File = 17,
944    Reference = 18,
945    Folder = 19,
946    EnumMember = 20,
947    Constant = 21,
948    Struct = 22,
949    Event = 23,
950    Operator = 24,
951    TypeParameter = 25,
952}
953
954/// Text edit for completions
955#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
956pub struct TextEdit {
957    pub range: Range,
958    pub new_text: String,
959}
960
961/// Range for text edits
962#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
963pub struct Range {
964    pub start: Position,
965    pub end: Position,
966}
967
968/// Position in text
969#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
970pub struct Position {
971    pub line: u32,
972    pub character: u32,
973}
974
975/// Command for completion items
976#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
977pub struct Command {
978    pub title: String,
979    pub command: String,
980    pub arguments: Option<Vec<serde_json::Value>>,
981}
982
983/// Completion item
984#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
985pub struct CompletionItem {
986    pub label: String,
987    pub kind: Option<CompletionItemKind>,
988    pub detail: Option<String>,
989    pub documentation: Option<String>,
990    pub sort_text: Option<String>,
991    pub filter_text: Option<String>,
992    pub insert_text: Option<String>,
993    pub text_edit: Option<TextEdit>,
994    pub command: Option<Command>,
995}
996
997/// Completion result
998#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
999pub struct CompletionResult {
1000    pub items: Vec<CompletionItem>,
1001    pub is_incomplete: Option<bool>,
1002}
1003
1004/// Embedded resource content (2025)
1005#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1006pub struct EmbeddedResourceContent {
1007    pub uri: String,
1008    pub mime_type: Option<String>,
1009    pub content: String,
1010}
1011
1012/// Enhanced progress notification
1013#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1014pub struct EnhancedProgressNotification {
1015    pub token: ProgressToken,
1016    pub message: Option<String>,
1017    pub percentage: Option<f32>,
1018    pub total: Option<u64>,
1019    pub current: u64,
1020}
1021
1022/// Enhanced server capabilities
1023#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1024pub struct EnhancedServerCapabilities {
1025    pub completion: Option<CompletionCapabilities>,
1026    pub streaming: Option<StreamingCapabilities>,
1027    pub batch_operations: Option<BatchCapabilities>,
1028}
1029
1030/// Completion capabilities (corrected name)
1031#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
1032pub struct CompletionCapabilities {
1033    pub trigger_characters: Option<Vec<String>>,
1034    pub all_commit_characters: Option<Vec<String>>,
1035}
1036
1037/// Streaming capabilities
1038#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
1039pub struct StreamingCapabilities {
1040    pub supported: bool,
1041    pub max_chunk_size: Option<usize>,
1042}
1043
1044/// Batch operation capabilities
1045#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
1046pub struct BatchCapabilities {
1047    pub max_operations: Option<usize>,
1048    pub supported_operations: Option<Vec<String>>,
1049}
1050
1051/// Batch operation request
1052#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1053pub struct BatchOperationRequest {
1054    pub operations: Vec<BatchOperation>,
1055}
1056
1057/// Individual batch operation
1058#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1059pub struct BatchOperation {
1060    pub id: String,
1061    pub method: String,
1062    pub params: Option<serde_json::Value>,
1063}
1064
1065/// Batch operation response
1066#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1067pub struct BatchOperationResponse {
1068    pub results: Vec<BatchOperationResult>,
1069}
1070
1071/// Individual batch operation result
1072#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1073pub struct BatchOperationResult {
1074    pub id: String,
1075    pub result: Option<serde_json::Value>,
1076    pub error: Option<JsonRpcError>,
1077}
1078
1079/// Streaming response
1080#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1081pub struct StreamingResponse {
1082    pub chunk_id: u64,
1083    pub total_chunks: Option<u64>,
1084    pub is_final: bool,
1085    pub data: serde_json::Value,
1086}
1087
1088// ============================================================================
1089// Legacy Type Aliases for Test Compatibility
1090// ============================================================================
1091
1092pub type RootsCapabilities = RootsCapability;
1093pub type PromptsCapabilities = PromptsCapability;
1094pub type ResourcesCapabilities = ResourcesCapability;
1095pub type ToolsCapabilities = ToolsCapability;
1096pub type LoggingCapabilities = LoggingCapability;