turul-mcp-server 0.3.19

High-level framework for building Model Context Protocol (MCP) servers
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
//! MCP Server Implementation and Session-Aware Handlers
//!
//! This module contains the core MCP server implementation (`McpServer`) and
//! session-aware handlers that bridge MCP protocol requests with business logic.
//! Includes handlers for initialization, tool execution, and tool listing with
//! automatic session management and protocol compliance.

use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;

use async_trait::async_trait;
use tracing::{debug, error, info, warn};

use crate::handlers::McpHandler;
use crate::session::{SessionContext, SessionManager};
use crate::{McpServerBuilder, McpTool, Result, tool::tool_to_descriptor};
use turul_mcp_json_rpc_server::JsonRpcHandler;

use turul_mcp_protocol::McpError;
use turul_mcp_protocol::*;

/// Main MCP server
pub struct McpServer {
    /// Server implementation information
    pub implementation: Implementation,
    /// Server capabilities
    pub capabilities: ServerCapabilities,
    /// Registered tools
    tools: HashMap<String, Arc<dyn McpTool>>,
    /// Registered handlers
    handlers: HashMap<String, Arc<dyn McpHandler>>,
    /// Session manager for state persistence
    session_manager: Arc<SessionManager>,
    /// Session storage backend (shared between SessionManager and HTTP layer)
    session_storage: Option<Arc<turul_mcp_session_storage::BoxedSessionStorage>>,
    /// Optional client instructions
    instructions: Option<String>,
    /// Strict MCP lifecycle enforcement
    strict_lifecycle: bool,
    /// Middleware stack for request/response processing
    middleware_stack: crate::middleware::MiddlewareStack,
    /// Task runtime for long-running operations (None = tasks not supported)
    task_runtime: Option<Arc<crate::task::runtime::TaskRuntime>>,
    /// Custom HTTP route registry
    route_registry: Arc<turul_http_mcp_server::RouteRegistry>,

    // HTTP configuration (if enabled)
    #[cfg(feature = "http")]
    bind_address: SocketAddr,
    #[cfg(feature = "http")]
    mcp_path: String,
    #[cfg(feature = "http")]
    enable_cors: bool,
    #[cfg(feature = "http")]
    enable_sse: bool,
    #[cfg(feature = "http")]
    allow_unauthenticated_ping: Option<bool>,
}

impl McpServer {
    /// Create a new MCP server (use builder instead)
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        implementation: Implementation,
        capabilities: ServerCapabilities,
        tools: HashMap<String, Arc<dyn McpTool>>,
        handlers: HashMap<String, Arc<dyn McpHandler>>,
        instructions: Option<String>,
        session_timeout_minutes: Option<u64>,
        session_cleanup_interval_seconds: Option<u64>,
        session_storage: Option<Arc<turul_mcp_session_storage::BoxedSessionStorage>>,
        task_runtime: Option<Arc<crate::task::runtime::TaskRuntime>>,
        strict_lifecycle: bool,
        middleware_stack: crate::middleware::MiddlewareStack,
        route_registry: Arc<turul_http_mcp_server::RouteRegistry>,
        #[cfg(feature = "http")] bind_address: SocketAddr,
        #[cfg(feature = "http")] mcp_path: String,
        #[cfg(feature = "http")] enable_cors: bool,
        #[cfg(feature = "http")] enable_sse: bool,
        #[cfg(feature = "http")] allow_unauthenticated_ping: Option<bool>,
    ) -> Self {
        // Create session manager with server capabilities, custom timeouts, and storage
        let session_manager = match &session_storage {
            Some(storage) => {
                if let (Some(timeout_mins), Some(cleanup_secs)) =
                    (session_timeout_minutes, session_cleanup_interval_seconds)
                {
                    Arc::new(SessionManager::with_storage_and_timeouts(
                        Arc::clone(storage),
                        capabilities.clone(),
                        std::time::Duration::from_secs(timeout_mins * 60),
                        std::time::Duration::from_secs(cleanup_secs),
                    ))
                } else {
                    Arc::new(SessionManager::with_storage_and_timeouts(
                        Arc::clone(storage),
                        capabilities.clone(),
                        std::time::Duration::from_secs(30 * 60), // Default 30 minutes
                        std::time::Duration::from_secs(60),      // Default 1 minute
                    ))
                }
            }
            None => {
                // Default to InMemory storage
                if let (Some(timeout_mins), Some(cleanup_secs)) =
                    (session_timeout_minutes, session_cleanup_interval_seconds)
                {
                    Arc::new(SessionManager::with_timeouts(
                        capabilities.clone(),
                        std::time::Duration::from_secs(timeout_mins * 60),
                        std::time::Duration::from_secs(cleanup_secs),
                    ))
                } else {
                    Arc::new(SessionManager::new(capabilities.clone()))
                }
            }
        };

        // Debug: Log session storage configuration
        if let Some(storage) = &session_storage {
            debug!(
                "McpServer configured with session storage backend: {:p}",
                storage
            );
        } else {
            debug!("McpServer configured without session storage");
        }

        Self {
            implementation,
            capabilities,
            tools,
            handlers,
            session_manager,
            session_storage,
            task_runtime,
            instructions,
            strict_lifecycle,
            middleware_stack,
            route_registry,
            #[cfg(feature = "http")]
            bind_address,
            #[cfg(feature = "http")]
            mcp_path,
            #[cfg(feature = "http")]
            enable_cors,
            #[cfg(feature = "http")]
            enable_sse,
            #[cfg(feature = "http")]
            allow_unauthenticated_ping,
        }
    }

    /// Create a new builder
    ///
    /// # Example
    /// ```rust,no_run
    /// use turul_mcp_server::McpServer;
    ///
    /// let builder = McpServer::builder()
    ///     .name("my-server")
    ///     .version("1.0.0");
    /// ```
    pub fn builder() -> McpServerBuilder {
        McpServerBuilder::new()
    }

    /// Get the server's configured capabilities
    pub fn capabilities(&self) -> &turul_mcp_protocol::ServerCapabilities {
        &self.capabilities
    }

    /// Get the task runtime, if task support is configured.
    pub fn task_runtime(&self) -> Option<&Arc<crate::task::runtime::TaskRuntime>> {
        self.task_runtime.as_ref()
    }

    /// Run the server with the default transport (HTTP if available)
    pub async fn run(&self) -> Result<()> {
        #[cfg(feature = "http")]
        {
            self.run_http().await
        }
        #[cfg(not(feature = "http"))]
        {
            // If no HTTP feature, we can't run without transport
            Err(McpError::configuration(
                "No transport available. Enable the 'http' feature to use HTTP transport.",
            ))
        }
    }

    /// Run the server with HTTP transport (requires "http" feature)
    #[cfg(feature = "http")]
    pub async fn run_http(&self) -> Result<()> {
        info!(
            "Starting MCP server: {} v{}",
            self.implementation.name, self.implementation.version
        );
        info!("Session management: enabled with automatic cleanup");

        if self.enable_sse {
            info!("SSE notifications: enabled at GET {}", self.mcp_path);
        }

        // Start session cleanup task
        let _cleanup_task = self.session_manager.clone().start_cleanup_task();

        // Recover stuck tasks on startup (tasks stuck in Working/InputRequired after unclean shutdown)
        if let Some(ref runtime) = self.task_runtime {
            match runtime.recover_stuck_tasks().await {
                Ok(recovered) if !recovered.is_empty() => {
                    info!(
                        count = recovered.len(),
                        "Recovered stuck tasks from previous session"
                    );
                }
                Err(e) => {
                    warn!(error = %e, "Failed to recover stuck tasks on startup");
                }
                _ => {}
            }
        }

        // Create session-aware tool handler (with optional task runtime for async execution)
        let mut tool_handler = SessionAwareToolHandler::new(
            self.tools.clone(),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );
        if let Some(ref runtime) = self.task_runtime {
            tool_handler = tool_handler.with_task_runtime(Arc::clone(runtime));
        }

        // Create session-aware initialize handler
        let init_handler = SessionAwareInitializeHandler::new(
            self.implementation.clone(),
            self.capabilities.clone(),
            self.instructions.clone(),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );

        // Build HTTP server with shared session storage from SessionManager
        let session_storage = self.session_manager.get_storage();
        debug!("Configuring HTTP MCP server with session storage backend");
        let mut builder =
            turul_http_mcp_server::HttpMcpServer::builder_with_storage(session_storage)
                .bind_address(self.bind_address)
                .mcp_path(&self.mcp_path)
                .cors(self.enable_cors)
                .get_sse(self.enable_sse) // GET SSE controlled by main server enable_sse flag
                // POST SSE remains at default (false) for compatibility
                .server_capabilities(self.capabilities.clone()) // Pass server capabilities
                .with_middleware_stack(Arc::new(self.middleware_stack.clone())) // Pass middleware stack
                .route_registry(Arc::clone(&self.route_registry)) // Pass custom routes
                .register_handler(vec!["initialize".to_string()], init_handler)
                .register_handler(
                    vec!["tools/list".to_string()],
                    ListToolsHandler::new_with_session_manager(
                        self.tools.clone(),
                        self.session_manager.clone(),
                        self.strict_lifecycle,
                        self.task_runtime.is_some(),
                    ),
                )
                .register_handler(vec!["tools/call".to_string()], tool_handler);

        // Pass allow_unauthenticated_ping config to HTTP layer
        if let Some(allow) = self.allow_unauthenticated_ping {
            builder = builder.allow_unauthenticated_ping(allow);
        }

        // Register all MCP handlers with session awareness
        for (method, handler) in &self.handlers {
            let bridge_handler = SessionAwareMcpHandlerBridge::new(
                handler.clone(),
                self.session_manager.clone(),
                self.strict_lifecycle,
            );
            builder = builder.register_handler(vec![method.clone()], bridge_handler);
        }

        // Register special initialized notification handler that can mark sessions as initialized
        use crate::handlers::InitializedNotificationHandler;
        let initialized_handler = InitializedNotificationHandler::new(self.session_manager.clone());
        let initialized_bridge = SessionAwareMcpHandlerBridge::new(
            Arc::new(initialized_handler),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );
        builder = builder.register_handler(
            vec!["notifications/initialized".to_string()],
            initialized_bridge,
        );

        let http_server = builder.build();

        // SSE is now integrated directly into the session management
        if self.enable_sse {
            debug!("SSE support enabled with integrated session management");

            // Set up event forwarding bridge between SessionManager and StreamManager
            self.setup_sse_event_bridge(&http_server).await;
        }

        http_server.run().await.map_err(|http_err| match http_err {
            turul_http_mcp_server::HttpMcpError::Mcp(mcp_err) => mcp_err,
            turul_http_mcp_server::HttpMcpError::Http(http_err) => {
                McpError::transport(&http_err.to_string())
            }
            turul_http_mcp_server::HttpMcpError::JsonRpc(rpc_err) => {
                McpError::json_rpc_protocol(&rpc_err.to_string())
            }
            turul_http_mcp_server::HttpMcpError::Serialization(ser_err) => {
                McpError::SerializationError(ser_err)
            }
            turul_http_mcp_server::HttpMcpError::Io(io_err) => McpError::IoError(io_err),
            turul_http_mcp_server::HttpMcpError::InvalidRequest(msg) => {
                McpError::InvalidParameters(msg)
            }
        })?;
        Ok(())
    }

    /// Set up event forwarding bridge between SessionManager and StreamManager
    async fn setup_sse_event_bridge(&self, http_server: &turul_http_mcp_server::HttpMcpServer) {
        debug!("🌉 Setting up SSE event bridge between SessionManager and StreamManager");

        let stream_manager = http_server.get_stream_manager();
        let mut global_events = self.session_manager.subscribe_all_session_events();

        tokio::spawn(async move {
            debug!("🌐 SSE Event Bridge: Started listening for session events");

            while let Ok((session_id, event)) = global_events.recv().await {
                debug!(
                    "📡 SSE Bridge: Received event from session {}: {:?}",
                    session_id, event
                );

                // Convert SessionEvent to StreamManager event format
                match event {
                    crate::session::SessionEvent::Custom { event_type, data } => {
                        debug!(
                            "📤 SSE Bridge: Broadcasting custom event '{}' to StreamManager",
                            event_type
                        );

                        if let Err(e) = stream_manager
                            .broadcast_to_session(&session_id, event_type, data)
                            .await
                        {
                            error!(
                                "❌ SSE Bridge: Failed to broadcast to session {}: {}",
                                session_id, e
                            );
                        } else {
                            debug!(
                                "✅ SSE Bridge: Successfully broadcast to session {}",
                                session_id
                            );
                        }
                    }
                    other_event => {
                        debug!("⏭ SSE Bridge: Skipping non-custom event: {:?}", other_event);
                    }
                }
            }

            debug!("🚫 SSE Event Bridge: Global event receiver closed");
        });

        info!("✅ SSE event bridge established successfully");
    }

    /// Run the server and return the HTTP server handle for SSE access (requires "http" feature)
    #[cfg(feature = "http")]
    pub async fn run_with_sse_access(
        &self,
    ) -> Result<(
        turul_http_mcp_server::HttpMcpServer,
        tokio::task::JoinHandle<turul_http_mcp_server::Result<()>>,
    )> {
        info!(
            "Starting MCP server: {} v{}",
            self.implementation.name, self.implementation.version
        );
        info!("Session management: enabled with automatic cleanup");

        if self.enable_sse {
            info!("SSE notifications: enabled - SSE manager available for notifications");
        }

        // Start session cleanup task
        let _cleanup_task = self.session_manager.clone().start_cleanup_task();

        // Recover stuck tasks on startup (tasks stuck in Working/InputRequired after unclean shutdown)
        if let Some(ref runtime) = self.task_runtime {
            match runtime.recover_stuck_tasks().await {
                Ok(recovered) if !recovered.is_empty() => {
                    info!(
                        count = recovered.len(),
                        "Recovered stuck tasks from previous session"
                    );
                }
                Err(e) => {
                    warn!(error = %e, "Failed to recover stuck tasks on startup");
                }
                _ => {}
            }
        }

        // Create session-aware tool handler (with optional task runtime for async execution)
        let mut tool_handler = SessionAwareToolHandler::new(
            self.tools.clone(),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );
        if let Some(ref runtime) = self.task_runtime {
            tool_handler = tool_handler.with_task_runtime(Arc::clone(runtime));
        }

        // Create session-aware initialize handler
        let init_handler = SessionAwareInitializeHandler::new(
            self.implementation.clone(),
            self.capabilities.clone(),
            self.instructions.clone(),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );

        // Build HTTP server with shared session storage from SessionManager
        let session_storage = self.session_manager.get_storage();
        debug!("Configuring HTTP MCP server with session storage backend");
        let mut builder =
            turul_http_mcp_server::HttpMcpServer::builder_with_storage(session_storage)
                .bind_address(self.bind_address)
                .mcp_path(&self.mcp_path)
                .cors(self.enable_cors)
                .get_sse(self.enable_sse) // GET SSE controlled by main server enable_sse flag
                // POST SSE remains at default (false) for compatibility
                .server_capabilities(self.capabilities.clone()) // Pass server capabilities
                .with_middleware_stack(Arc::new(self.middleware_stack.clone())) // Pass middleware stack
                .route_registry(Arc::clone(&self.route_registry)) // Pass custom routes
                .register_handler(vec!["initialize".to_string()], init_handler)
                .register_handler(
                    vec!["tools/list".to_string()],
                    ListToolsHandler::new_with_session_manager(
                        self.tools.clone(),
                        self.session_manager.clone(),
                        self.strict_lifecycle,
                        self.task_runtime.is_some(),
                    ),
                )
                .register_handler(vec!["tools/call".to_string()], tool_handler);

        // Pass allow_unauthenticated_ping config to HTTP layer
        if let Some(allow) = self.allow_unauthenticated_ping {
            builder = builder.allow_unauthenticated_ping(allow);
        }

        // TODO investigate if this also adds the tools/list and tools/call handlers
        // Register all MCP handlers with session awareness
        for (method, handler) in &self.handlers {
            let bridge_handler = SessionAwareMcpHandlerBridge::new(
                handler.clone(),
                self.session_manager.clone(),
                self.strict_lifecycle,
            );
            builder = builder.register_handler(vec![method.clone()], bridge_handler);
        }

        // Register special initialized notification handler that can mark sessions as initialized
        use crate::handlers::InitializedNotificationHandler;
        let initialized_handler = InitializedNotificationHandler::new(self.session_manager.clone());
        let initialized_bridge = SessionAwareMcpHandlerBridge::new(
            Arc::new(initialized_handler),
            self.session_manager.clone(),
            self.strict_lifecycle,
        );
        builder = builder.register_handler(
            vec!["notifications/initialized".to_string()],
            initialized_bridge,
        );

        let http_server = builder.build();

        // Run server in background task
        let server_task = {
            let server = http_server.clone();
            tokio::spawn(async move { server.run().await })
        };

        Ok((http_server, server_task))
    }

    /// Get session storage configuration info
    pub fn session_storage_info(&self) -> &str {
        if let Some(storage) = &self.session_storage {
            debug!(
                "Accessing session storage for info - backend is configured: {:p}",
                storage
            );
            "Backend configured"
        } else {
            "No backend configured"
        }
    }
}

/// Session-aware bridge handler that adapts McpHandler to JsonRpcHandler
///
/// Provides session management and lifecycle enforcement for custom MCP handlers,
/// automatically injecting session context and enforcing initialization requirements.
pub struct SessionAwareMcpHandlerBridge {
    handler: Arc<dyn McpHandler>,
    session_manager: Arc<SessionManager>,
    strict_lifecycle: bool,
}

impl SessionAwareMcpHandlerBridge {
    /// Creates a new session-aware handler bridge
    pub fn new(
        handler: Arc<dyn McpHandler>,
        session_manager: Arc<SessionManager>,
        strict_lifecycle: bool,
    ) -> Self {
        Self {
            handler,
            session_manager,
            strict_lifecycle,
        }
    }
}

#[async_trait]
impl JsonRpcHandler for SessionAwareMcpHandlerBridge {
    type Error = McpError;

    async fn handle(
        &self,
        method: &str,
        params: Option<turul_mcp_json_rpc_server::RequestParams>,
        session_context: Option<turul_mcp_json_rpc_server::r#async::SessionContext>,
    ) -> std::result::Result<serde_json::Value, McpError> {
        debug!("Handling {} request via session-aware bridge", method);

        // Convert JSON-RPC SessionContext to MCP SessionContext
        let mcp_session_context = if let Some(json_rpc_ctx) = session_context {
            debug!(
                "Converting JSON-RPC session context: session_id={}",
                json_rpc_ctx.session_id
            );
            Some(SessionContext::from_json_rpc_with_broadcaster(
                json_rpc_ctx,
                self.session_manager.get_storage(),
            ))
        } else {
            // Fallback: extract session ID from params (legacy behavior)
            let session_id = extract_session_id_from_params(&params);
            if let Some(sid) = session_id {
                debug!("Fallback: extracted session_id from params: {}", sid);
                self.session_manager.create_session_context(&sid)
            } else {
                None
            }
        };

        // MCP Lifecycle Guard: Ensure session is initialized before allowing operations (if strict mode enabled)
        if self.strict_lifecycle
            && method != "initialize"
            && method != "notifications/initialized"
            && let Some(ref session_ctx) = mcp_session_context
        {
            let session_initialized = self
                .session_manager
                .is_session_initialized(&session_ctx.session_id)
                .await;
            if !session_initialized {
                debug!(
                    "🚫 STRICT MODE: Rejecting {} request for session {} - session not yet initialized (waiting for notifications/initialized)",
                    method, session_ctx.session_id
                );
                return Err(McpError::SessionError(
                        "Session not initialized - client must send notifications/initialized first (strict lifecycle mode)".to_string()
                    ));
            }
        }

        // Convert JSON-RPC params to Value
        let mcp_params = params.map(|p| p.to_value());

        // Call the MCP handler with session context - propagate errors directly
        match self
            .handler
            .handle_with_session(mcp_params, mcp_session_context)
            .await
        {
            Ok(result) => Ok(result),
            Err(error) => {
                error!("MCP handler error: {}", error);
                Err(error) // Propagate McpError directly, no double-wrapping!
            }
        }
    }

    async fn handle_notification(
        &self,
        method: &str,
        params: Option<turul_mcp_json_rpc_server::RequestParams>,
        session_context: Option<turul_mcp_json_rpc_server::r#async::SessionContext>,
    ) -> std::result::Result<(), McpError> {
        debug!("Handling {} notification via session-aware bridge", method);

        // Convert JSON-RPC SessionContext to MCP SessionContext
        let mcp_session_context = session_context.map(|json_rpc_ctx| {
            SessionContext::from_json_rpc_with_broadcaster(
                json_rpc_ctx,
                self.session_manager.get_storage(),
            )
        });

        // MCP Lifecycle Guard for notifications: Allow notifications/initialized to pass through
        // but enforce lifecycle for other notifications if strict mode is enabled
        if self.strict_lifecycle
            && method != "notifications/initialized"
            && let Some(ref session_ctx) = mcp_session_context
        {
            let session_initialized = self
                .session_manager
                .is_session_initialized(&session_ctx.session_id)
                .await;
            if !session_initialized {
                tracing::debug!(
                    "🚫 STRICT MODE: Rejecting notification {} for session {} - session not yet initialized",
                    method,
                    session_ctx.session_id
                );
                return Err(McpError::SessionError(
                    "Session not initialized - client must send notifications/initialized first (strict lifecycle mode)".to_string()
                ));
            }
        }

        // Convert JSON-RPC params to Value
        let mcp_params = params.map(|p| p.to_value());

        // Call the MCP handler's handle_with_session method for notifications
        match self
            .handler
            .handle_with_session(mcp_params, mcp_session_context)
            .await
        {
            Ok(_result) => Ok(()), // Notifications don't return values
            Err(error) => {
                tracing::error!("MCP notification handler error: {}", error);
                Err(error)
            }
        }
    }

    fn supported_methods(&self) -> Vec<String> {
        self.handler.supported_methods()
    }
}

/// Extract session ID from request parameters (placeholder implementation)
fn extract_session_id_from_params(
    _params: &Option<turul_mcp_json_rpc_server::RequestParams>,
) -> Option<String> {
    // In a real implementation, this would extract session ID from HTTP headers
    // For now, return None as we'll implement proper session extraction later
    None
}

/// Session-aware handler for initialize requests
pub struct SessionAwareInitializeHandler {
    implementation: Implementation,
    capabilities: ServerCapabilities,
    instructions: Option<String>,
    session_manager: Arc<SessionManager>,
    strict_lifecycle: bool,
}

impl SessionAwareInitializeHandler {
    pub fn new(
        implementation: Implementation,
        capabilities: ServerCapabilities,
        instructions: Option<String>,
        session_manager: Arc<SessionManager>,
        strict_lifecycle: bool,
    ) -> Self {
        Self {
            implementation,
            capabilities,
            instructions,
            session_manager,
            strict_lifecycle,
        }
    }

    /// Negotiate protocol version with client
    ///
    /// Server supports backward compatibility with older protocol versions.
    /// The negotiation follows this priority:
    /// 1. Use client's requested version if server supports it
    /// 2. Use the highest version both client and server support
    /// 3. Fall back to minimum compatible version
    fn negotiate_version(&self, client_version: &str) -> std::result::Result<McpVersion, String> {
        use turul_mcp_protocol::version::McpVersion;

        // Try to parse client's requested version
        let requested_version = match client_version.parse::<McpVersion>() {
            Ok(version) => version,
            Err(_) => {
                // Unknown version - check if it's newer than what we support
                // If it looks like a valid date format but we don't know it,
                // we need to check if it's likely newer or older than our range
                if client_version.matches('-').count() == 2 {
                    // Check if it's likely newer than our latest supported version
                    if client_version > McpVersion::LATEST.as_str() {
                        // Assume it's newer, use latest as fallback
                        McpVersion::LATEST
                    } else if client_version < "2024-11-05" {
                        // Too old, we don't support versions before our minimum
                        return Err(format!(
                            "Cannot negotiate compatible version with client version {} (server requires at least {})",
                            client_version, "2024-11-05"
                        ));
                    } else {
                        // Unknown version between our supported range - shouldn't happen
                        return Err(format!("Unknown protocol version: {}", client_version));
                    }
                } else {
                    return Err(format!(
                        "Invalid protocol version format: {}",
                        client_version
                    ));
                }
            }
        };

        // Define server's supported versions (all versions from 2024-11-05 to current)
        let supported_versions = [
            McpVersion::V2024_11_05,
            McpVersion::V2025_03_26,
            McpVersion::V2025_06_18,
            McpVersion::V2025_11_25,
        ];

        // Strategy 1: If server supports client's requested version, use it
        if supported_versions.contains(&requested_version) {
            return Ok(requested_version);
        }

        // Strategy 2: Find highest supported version ≤ client requested version
        // This allows clients to request newer versions while falling back gracefully
        let compatible_versions: Vec<_> = supported_versions
            .iter()
            .filter(|&&v| v <= requested_version)
            .collect();

        if let Some(&&best_version) = compatible_versions.iter().max() {
            Ok(best_version)
        } else {
            // Strategy 3: No compatible version found - client too old
            Err(format!(
                "Cannot negotiate compatible version with client version {} (server requires at least {})",
                client_version,
                supported_versions.iter().min().unwrap()
            ))
        }
    }

    /// Adjust server capabilities based on negotiated protocol version
    ///
    /// Some capabilities are only available in newer protocol versions.
    /// This method filters capabilities to match what the negotiated version supports.
    fn adjust_capabilities_for_version(&self, version: McpVersion) -> ServerCapabilities {
        let adjusted = self.capabilities.clone();

        // Before version 2025-06-18, _meta field support wasn't available
        // So we don't need to adjust capabilities for that specifically since it's
        // handled at the protocol level.

        // Before version 2025-03-26, streamable HTTP wasn't available
        // But HTTP transport capability isn't explicitly declared in ServerCapabilities,
        // so no adjustment needed here.

        // All other capabilities (tools, resources, prompts, etc.) are version-independent
        // in terms of their basic functionality.

        info!(
            "Server capabilities adjusted for protocol version {}",
            version
        );
        debug!(
            "Capabilities: logging={}, tools={}, resources={}, prompts={}",
            adjusted.logging.is_some(),
            adjusted.tools.is_some(),
            adjusted.resources.is_some(),
            adjusted.prompts.is_some()
        );

        adjusted
    }
}

#[async_trait]
impl JsonRpcHandler for SessionAwareInitializeHandler {
    type Error = McpError;

    async fn handle(
        &self,
        method: &str,
        params: Option<turul_mcp_json_rpc_server::RequestParams>,
        session_context: Option<turul_mcp_json_rpc_server::r#async::SessionContext>,
    ) -> std::result::Result<serde_json::Value, McpError> {
        debug!("Handling {} request with session support", method);

        if method != "initialize" {
            return Err(McpError::InvalidParameters(format!(
                "Method not supported: {}",
                method
            )));
        }

        // Parse initialize request
        let request = if let Some(params) = params {
            let params_value = params.to_value();
            serde_json::from_value::<InitializeRequest>(params_value).map_err(|e| {
                McpError::InvalidParameters(format!("Invalid initialize request: {}", e))
            })?
        } else {
            return Err(McpError::MissingParameter(
                "Missing parameters for initialize".to_string(),
            ));
        };

        // Perform protocol version negotiation
        let negotiated_version = match self.negotiate_version(&request.protocol_version) {
            Ok(version) => {
                info!(
                    "Protocol version negotiated: {} (client requested: {})",
                    version, request.protocol_version
                );
                version
            }
            Err(e) => {
                error!("Protocol version negotiation failed: {}", e);
                return Err(McpError::ConfigurationError(format!(
                    "Version negotiation failed: {}",
                    e
                )));
            }
        };

        // Use session ID provided by HTTP layer, or create new one if not provided
        let session_id = if let Some(ctx) = &session_context {
            debug!("Using session from context: {}", ctx.session_id);

            // Add session to cache if it doesn't exist there
            // This handles sessions created directly in storage by session_handler
            let cache_exists = self
                .session_manager
                .session_exists_in_cache(&ctx.session_id)
                .await;
            debug!(
                "Session {} exists in cache: {}",
                ctx.session_id, cache_exists
            );

            if !cache_exists {
                debug!("Session {} not in cache, checking storage", ctx.session_id);

                // Try to load session from storage with its actual capabilities
                match self
                    .session_manager
                    .load_session_from_storage(&ctx.session_id)
                    .await
                {
                    Ok(true) => {
                        debug!(
                            "Session {} loaded from storage with preserved capabilities",
                            ctx.session_id
                        );
                    }
                    Ok(false) => {
                        // Session doesn't exist in storage either - this shouldn't happen
                        // in normal flow but handle gracefully
                        warn!(
                            "Session {} not found in storage, creating with defaults",
                            ctx.session_id
                        );
                        self.session_manager
                            .add_session_to_cache(
                                ctx.session_id.clone(),
                                self.session_manager.get_default_capabilities(),
                            )
                            .await;
                    }
                    Err(e) => {
                        error!(
                            "Failed to load session {} from storage: {}",
                            ctx.session_id, e
                        );
                        // Fallback to defaults only on error
                        self.session_manager
                            .add_session_to_cache(
                                ctx.session_id.clone(),
                                self.session_manager.get_default_capabilities(),
                            )
                            .await;
                    }
                }
            } else {
                debug!("Session {} already exists in cache", ctx.session_id);
            }

            ctx.session_id.clone()
        } else {
            debug!("No session context provided, creating new session");
            self.session_manager.create_session().await
        };

        // Store client info and capabilities in session state for later initialization
        // Per MCP spec, session is NOT initialized until client sends notifications/initialized
        self.session_manager
            .set_session_state(
                &session_id,
                "client_info",
                serde_json::to_value(&request.client_info).map_err(McpError::SerializationError)?,
            )
            .await;

        self.session_manager
            .set_session_state(
                &session_id,
                "client_capabilities",
                serde_json::to_value(&request.capabilities)
                    .map_err(McpError::SerializationError)?,
            )
            .await;

        self.session_manager
            .set_session_state(
                &session_id,
                "negotiated_version",
                serde_json::to_value(negotiated_version).map_err(McpError::SerializationError)?,
            )
            .await;

        // Store negotiated version before initialization (differs by mode)

        // Store the negotiated version in session state for tools to access
        self.session_manager
            .set_session_state(
                &session_id,
                "mcp_version",
                serde_json::json!(negotiated_version.as_str()),
            )
            .await;

        // In lenient mode, immediately mark session as initialized
        // In strict mode, wait for notifications/initialized from client
        if !self.strict_lifecycle {
            debug!(
                "📝 LENIENT MODE: Immediately initializing session {} (strict_lifecycle=false)",
                session_id
            );
            if let Err(e) = self
                .session_manager
                .initialize_session_with_version(
                    &session_id,
                    request.client_info,
                    request.capabilities,
                    negotiated_version,
                )
                .await
            {
                error!("❌ Failed to initialize session {}: {}", session_id, e);
                return Err(McpError::SessionError(format!(
                    "Failed to initialize session: {}",
                    e
                )));
            }
            info!(
                "✅ Session {} created and immediately initialized with protocol version {} (lenient mode)",
                session_id, negotiated_version
            );
        } else {
            info!(
                "⏳ Session {} created and ready for client with protocol version {} (strict mode - waiting for notifications/initialized)",
                session_id, negotiated_version
            );
        }

        // Create response with negotiated version and adjusted capabilities
        let adjusted_capabilities = self.adjust_capabilities_for_version(negotiated_version);
        let mut response = InitializeResult::new(
            negotiated_version,
            adjusted_capabilities,
            self.implementation.clone(),
        );

        if let Some(instructions) = &self.instructions {
            response = response.with_instructions(instructions.clone());
        }

        // Session ID is communicated to HTTP layer via session manager

        serde_json::to_value(response).map_err(McpError::SerializationError)
    }

    fn supported_methods(&self) -> Vec<String> {
        vec!["initialize".to_string()]
    }
}

/// Handler for tools/list requests
pub struct ListToolsHandler {
    tools: HashMap<String, Arc<dyn McpTool>>,
    session_manager: Option<Arc<SessionManager>>,
    strict_lifecycle: bool,
    has_tasks: bool,
}

impl ListToolsHandler {
    pub fn new(tools: HashMap<String, Arc<dyn McpTool>>, has_tasks: bool) -> Self {
        Self {
            tools,
            session_manager: None,
            strict_lifecycle: false,
            has_tasks,
        }
    }

    pub fn new_with_session_manager(
        tools: HashMap<String, Arc<dyn McpTool>>,
        session_manager: Arc<SessionManager>,
        strict_lifecycle: bool,
        has_tasks: bool,
    ) -> Self {
        Self {
            tools,
            session_manager: Some(session_manager),
            strict_lifecycle,
            has_tasks,
        }
    }
}

#[async_trait]
impl JsonRpcHandler for ListToolsHandler {
    type Error = McpError;

    async fn handle(
        &self,
        method: &str,
        params: Option<turul_mcp_json_rpc_server::RequestParams>,
        session_context: Option<turul_mcp_json_rpc_server::r#async::SessionContext>,
    ) -> std::result::Result<serde_json::Value, McpError> {
        use turul_mcp_protocol::meta::{Cursor, PaginatedResponse};

        debug!("Handling {} request", method);

        // MCP Lifecycle Guard: Ensure session is initialized before allowing operations (if strict mode enabled)
        if self.strict_lifecycle
            && let (Some(session_manager), Some(session_ctx)) =
                (&self.session_manager, &session_context)
        {
            let session_initialized = session_manager
                .is_session_initialized(&session_ctx.session_id)
                .await;
            if !session_initialized {
                debug!(
                    "🚫 STRICT MODE: Rejecting {} request for session {} - session not yet initialized (waiting for notifications/initialized)",
                    method, session_ctx.session_id
                );
                return Err(McpError::SessionError(
                    "Session not initialized - client must send notifications/initialized first (strict lifecycle mode)".to_string()
                ));
            }
        }

        if method != "tools/list" {
            return Err(McpError::InvalidParameters(format!(
                "Method '{}' not supported by tools/list handler",
                method
            )));
        }

        // Parse typed parameters for cursor and meta propagation
        use turul_mcp_protocol::tools::{ListToolsParams, ListToolsResult};
        let list_params = if let Some(params_value) = params {
            serde_json::from_value::<ListToolsParams>(params_value.to_value()).map_err(|e| {
                McpError::InvalidParameters(format!("Invalid parameters for tools/list: {}", e))
            })?
        } else {
            ListToolsParams::new()
        };

        let cursor = list_params.cursor;
        debug!("Listing tools with cursor: {:?}", cursor);

        // Convert tools to descriptors and sort by name for stable pagination
        let mut tools: Vec<Tool> = self
            .tools
            .values()
            .map(|tool| tool_to_descriptor(tool.as_ref()))
            .collect();

        // Sort by tool name to ensure stable ordering for pagination
        tools.sort_by(|a, b| a.name.cmp(&b.name));

        // Strip execution field when server has no task capability (truthful advertisement)
        if !self.has_tasks {
            for tool in &mut tools {
                tool.execution = None;
            }
        }

        // Implement cursor-based pagination
        const DEFAULT_PAGE_SIZE: usize = 50; // MCP suggested default
        const MAX_LIMIT: u32 = 100; // Framework-specific DoS protection

        // Validate limit parameter - MCP spec requires positive integer
        if let Some(limit) = list_params.limit
            && limit == 0
        {
            return Err(McpError::InvalidParameters(
                "limit must be a positive integer (> 0)".to_string(),
            ));
        }

        // Apply limit clamping for DoS protection (framework extension)
        let page_size = list_params
            .limit
            .map(|l| std::cmp::min(l, MAX_LIMIT) as usize)
            .unwrap_or(DEFAULT_PAGE_SIZE);

        // Find starting index based on cursor
        let start_index = if let Some(cursor) = &cursor {
            // Cursor contains the last tool name from previous page
            let cursor_name = cursor.as_str();
            // Find the position after the cursor name (first tool > cursor)
            tools
                .iter()
                .position(|t| t.name.as_str() > cursor_name)
                .unwrap_or(tools.len())
        } else {
            0 // No cursor = start from beginning
        };

        // Calculate end index for this page
        let end_index = std::cmp::min(start_index + page_size, tools.len());

        // Extract page of tools
        let page_tools: Vec<Tool> = tools[start_index..end_index].to_vec();

        // Determine if there are more tools after this page
        let has_more = end_index < tools.len();

        // Generate next cursor if there are more tools
        let next_cursor = if has_more {
            // Cursor should be the name of the last item in current page
            page_tools.last().map(|t| Cursor::new(&t.name))
        } else {
            None
        };

        debug!(
            "Tool pagination: start={}, end={}, page_size={}, has_more={}, next_cursor={:?}",
            start_index,
            end_index,
            page_tools.len(),
            has_more,
            next_cursor
        );

        let mut base_response = ListToolsResult::new(page_tools);
        let total = Some(tools.len() as u64);

        // Set top-level nextCursor field on the result before wrapping
        if let Some(ref cursor) = next_cursor {
            base_response = base_response.with_next_cursor(cursor.clone());
        }

        let next_cursor_clone = next_cursor.clone();
        let mut paginated_response =
            PaginatedResponse::with_pagination(base_response, next_cursor, total, has_more);

        // Propagate optional _meta from request to response (MCP 2025-11-25 compliance)
        if let Some(request_meta) = list_params.meta {
            // Get existing meta from PaginatedResponse or use pagination defaults
            let mut response_meta = paginated_response.meta().cloned().unwrap_or_else(|| {
                turul_mcp_protocol::meta::Meta::with_pagination(next_cursor_clone, total, has_more)
            });

            // Merge request's _meta fields into extra without clobbering pagination
            for (key, value) in request_meta {
                response_meta.extra.insert(key, value);
            }

            paginated_response = paginated_response.with_meta(response_meta);
        }

        serde_json::to_value(paginated_response).map_err(McpError::SerializationError)
    }

    fn supported_methods(&self) -> Vec<String> {
        vec!["tools/list".to_string()]
    }
}

/// Session-aware handler for tool execution
pub struct SessionAwareToolHandler {
    tools: HashMap<String, Arc<dyn McpTool>>,
    session_manager: Arc<SessionManager>,
    strict_lifecycle: bool,
    /// Optional task runtime — when present AND request has `params.task`,
    /// the handler creates a task and executes asynchronously.
    task_runtime: Option<Arc<crate::task::runtime::TaskRuntime>>,
}

impl SessionAwareToolHandler {
    pub fn new(
        tools: HashMap<String, Arc<dyn McpTool>>,
        session_manager: Arc<SessionManager>,
        strict_lifecycle: bool,
    ) -> Self {
        Self {
            tools,
            session_manager,
            strict_lifecycle,
            task_runtime: None,
        }
    }

    pub fn with_task_runtime(mut self, runtime: Arc<crate::task::runtime::TaskRuntime>) -> Self {
        self.task_runtime = Some(runtime);
        self
    }
}

#[async_trait]
impl JsonRpcHandler for SessionAwareToolHandler {
    type Error = McpError;

    async fn handle(
        &self,
        method: &str,
        params: Option<turul_mcp_json_rpc_server::RequestParams>,
        session_context: Option<turul_mcp_json_rpc_server::r#async::SessionContext>,
    ) -> std::result::Result<serde_json::Value, McpError> {
        debug!("Handling {} request with session support", method);

        if method != "tools/call" {
            return Err(McpError::InvalidParameters(format!(
                "Method '{}' not supported by tools/call handler",
                method
            )));
        }

        // MCP Lifecycle Guard: Ensure session is initialized before allowing tool operations (if strict mode enabled)
        if self.strict_lifecycle {
            if let Some(ref session_ctx) = session_context {
                let session_initialized = self
                    .session_manager
                    .is_session_initialized(&session_ctx.session_id)
                    .await;
                if !session_initialized {
                    debug!(
                        "🚫 STRICT MODE: Rejecting {} request for session {} - session not yet initialized (waiting for notifications/initialized)",
                        method, session_ctx.session_id
                    );
                    return Err(McpError::SessionError(
                        "Session not initialized - client must send notifications/initialized first (strict lifecycle mode)".to_string(),
                    ));
                }
                debug!(
                    "✅ STRICT MODE: Session {} is initialized - allowing {} request",
                    session_ctx.session_id, method
                );
            }
        } else {
            debug!(
                "📝 LENIENT MODE: Allowing {} request without lifecycle check (strict_lifecycle=false)",
                method
            );
        }

        let params =
            params.ok_or_else(|| McpError::MissingParameter("CallToolRequest".to_string()))?;

        // Use the parameter extraction pattern from the other project
        use turul_mcp_protocol::param_extraction::extract_params;

        let call_params: turul_mcp_protocol::tools::CallToolParams = extract_params(params)?;

        // Find the tool
        let tool = self
            .tools
            .get(&call_params.name)
            .ok_or_else(|| McpError::ToolNotFound(call_params.name.clone()))?;

        // Convert JSON-RPC SessionContext to MCP SessionContext for tool execution
        let mcp_session_context = if let Some(json_rpc_ctx) = session_context {
            debug!(
                "Converting JSON-RPC session context for tool call: session_id={}",
                json_rpc_ctx.session_id
            );
            Some(SessionContext::from_json_rpc_with_broadcaster(
                json_rpc_ctx,
                self.session_manager.get_storage(),
            ))
        } else {
            debug!("No session context provided for tool call");
            None
        };

        // Build arguments Value
        let args = call_params
            .arguments
            .map(|hashmap| {
                serde_json::to_value(hashmap)
                    .unwrap_or(serde_json::Value::Object(serde_json::Map::new()))
            })
            .unwrap_or_else(|| serde_json::Value::Object(serde_json::Map::new()));

        // Task-augmented request detection (MCP 2025-11-25):
        // If params.task is present AND task_runtime is configured, create a task
        // and execute asynchronously. Otherwise execute synchronously.
        //
        // Per spec: respect tool-level execution.taskSupport:
        // - Forbidden + task present: reject (clients MUST NOT use task augmentation)
        // - Required + task absent: reject (clients MUST use task augmentation)
        // - Optional: either path is valid
        // - None (no declaration): reject task-augmented calls (experimental; no declaration = no support)
        {
            use turul_mcp_protocol::tools::TaskSupport;
            let tool_descriptor = tool.to_tool();
            if let Some(ref exec) = tool_descriptor.execution {
                if call_params.task.is_some() && exec.task_support == Some(TaskSupport::Forbidden) {
                    return Err(McpError::InvalidParameters(format!(
                        "Tool '{}' has taskSupport=forbidden; task-augmented requests are not allowed",
                        call_params.name
                    )));
                }
                if call_params.task.is_none() && exec.task_support == Some(TaskSupport::Required) {
                    return Err(McpError::InvalidParameters(format!(
                        "Tool '{}' has taskSupport=required; requests must include task augmentation",
                        call_params.name
                    )));
                }
            } else if call_params.task.is_some() {
                return Err(McpError::InvalidParameters(format!(
                    "Tool '{}' does not declare task support; task-augmented requests are not allowed",
                    call_params.name
                )));
            }
        }

        // Reject task-augmented calls when no task runtime is configured
        if call_params.task.is_some() && self.task_runtime.is_none() {
            return Err(McpError::InvalidParameters(
                "Task-augmented tool calls require the server to have task support configured"
                    .into(),
            ));
        }

        if let (Some(task_meta), Some(runtime)) = (call_params.task, self.task_runtime.as_ref()) {
            use turul_mcp_protocol::tasks::{CreateTaskResult, Task};
            use turul_mcp_task_storage::{TaskOutcome, TaskRecord};

            // Backend-agnostic task ID: UUID v7 for temporal ordering
            let task_id = uuid::Uuid::now_v7().as_simple().to_string();
            let now = chrono::Utc::now().to_rfc3339();
            let session_id = mcp_session_context
                .as_ref()
                .map(|ctx| ctx.session_id.to_string());

            let record = TaskRecord {
                task_id: task_id.clone(),
                session_id: session_id.clone(),
                status: turul_mcp_protocol::TaskStatus::Working,
                status_message: Some("Executing tool".to_string()),
                created_at: now.clone(),
                last_updated_at: now,
                ttl: task_meta.ttl.map(|t| t as i64),
                poll_interval: Some(1_000),
                original_method: "tools/call".to_string(),
                original_params: Some(serde_json::json!({
                    "name": call_params.name,
                    "arguments": &args,
                })),
                result: None,
                meta: None,
            };

            let created = runtime.register_task(record).await.map_err(|e| {
                McpError::ToolExecutionError(format!("Failed to create task: {}", e))
            })?;

            // Spawn async execution via the executor.
            // The work closure is responsible for executing the tool AND persisting
            // the result to storage, so that tasks/result can retrieve it immediately
            // when the executor signals terminal status.
            let tool = Arc::clone(tool);
            let runtime_for_work = Arc::clone(runtime);
            let task_id_for_work = task_id.clone();

            let work: crate::task::executor::BoxedTaskWork = Box::new(move || {
                Box::pin(async move {
                    let outcome = match tool.call(args, mcp_session_context).await {
                        Ok(result) => match serde_json::to_value(&result) {
                            Ok(value) => TaskOutcome::Success(value),
                            Err(e) => TaskOutcome::Error {
                                code: -32603,
                                message: format!("Serialization error: {}", e),
                                data: None,
                            },
                        },
                        Err(mcp_err) => TaskOutcome::Error {
                            code: -32603, // Internal error
                            message: mcp_err.to_string(),
                            data: None,
                        },
                    };

                    // Persist to storage BEFORE returning (so tasks/result can find it)
                    let terminal_status = match &outcome {
                        TaskOutcome::Success(_) => turul_mcp_protocol::TaskStatus::Completed,
                        TaskOutcome::Error { .. } => turul_mcp_protocol::TaskStatus::Failed,
                    };
                    if let Err(e) = runtime_for_work
                        .complete_task(&task_id_for_work, outcome.clone(), terminal_status, None)
                        .await
                    {
                        error!(task_id = %task_id_for_work, error = %e, "Failed to persist task result");
                    }

                    outcome
                })
            });

            // Start execution in the executor
            let _handle = runtime
                .executor()
                .start_task(&task_id, work)
                .await
                .map_err(|e| {
                    McpError::ToolExecutionError(format!("Failed to start task execution: {}", e))
                })?;

            // Return CreateTaskResult immediately
            let task = Task {
                task_id: created.task_id.clone(),
                status: created.status,
                created_at: created.created_at.clone(),
                last_updated_at: created.last_updated_at.clone(),
                status_message: created.status_message.clone(),
                ttl: created.ttl,
                poll_interval: created.poll_interval,
                meta: None,
            };
            let result = CreateTaskResult { task, meta: None };
            serde_json::to_value(result).map_err(McpError::SerializationError)
        } else {
            // Synchronous execution (no task augmentation or no runtime)
            match tool.call(args, mcp_session_context).await {
                Ok(response) => {
                    serde_json::to_value(response).map_err(McpError::SerializationError)
                }
                Err(error_msg) => {
                    error!("Tool execution error: {}", error_msg);
                    Err(error_msg)
                }
            }
        }
    }

    fn supported_methods(&self) -> Vec<String> {
        vec!["tools/call".to_string()]
    }
}

impl std::fmt::Debug for McpServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("McpServer")
            .field("implementation", &self.implementation)
            .field("capabilities", &self.capabilities)
            .field("tools", &format!("HashMap with {} tools", self.tools.len()))
            .field("instructions", &self.instructions)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::McpTool;
    use async_trait::async_trait;
    use serde_json::Value;
    use std::collections::HashMap;
    use turul_mcp_builders::prelude::*;
    use turul_mcp_protocol::ToolSchema;
    use turul_mcp_protocol::tools::{CallToolResult, ToolResult}; // HasBaseMetadata, HasDescription, etc.

    struct TestTool {
        input_schema: ToolSchema,
    }

    impl TestTool {
        fn new() -> Self {
            Self {
                input_schema: ToolSchema::object(),
            }
        }
    }

    impl HasBaseMetadata for TestTool {
        fn name(&self) -> &str {
            "test"
        }
        fn title(&self) -> Option<&str> {
            Some("Test Tool")
        }
    }

    impl HasDescription for TestTool {
        fn description(&self) -> Option<&str> {
            Some("Test tool for unit tests")
        }
    }

    impl HasInputSchema for TestTool {
        fn input_schema(&self) -> &ToolSchema {
            &self.input_schema
        }
    }

    impl HasOutputSchema for TestTool {
        fn output_schema(&self) -> Option<&ToolSchema> {
            None
        }
    }

    impl HasAnnotations for TestTool {
        fn annotations(&self) -> Option<&turul_mcp_protocol::tools::ToolAnnotations> {
            None
        }
    }

    impl HasToolMeta for TestTool {
        fn tool_meta(&self) -> Option<&HashMap<String, Value>> {
            None
        }
    }

    impl HasIcons for TestTool {}
    impl HasExecution for TestTool {}

    #[async_trait]
    impl McpTool for TestTool {
        async fn call(
            &self,
            _args: Value,
            _session: Option<crate::SessionContext>,
        ) -> crate::McpResult<CallToolResult> {
            Ok(CallToolResult::success(vec![ToolResult::text(
                "test result",
            )]))
        }
    }

    #[test]
    fn test_server_creation() {
        let server = McpServer::builder()
            .name("test-server")
            .version("1.0.0")
            .tool(TestTool::new())
            .build()
            .unwrap();

        assert_eq!(server.implementation.name, "test-server");
        assert_eq!(server.implementation.version, "1.0.0");
        assert_eq!(server.tools.len(), 1);
    }

    #[tokio::test]
    async fn test_list_tools_handler() {
        let mut tools: HashMap<String, Arc<dyn McpTool>> = HashMap::new();
        tools.insert("test".to_string(), Arc::new(TestTool::new()));

        let handler = ListToolsHandler::new(tools, false);
        let result = handler.handle("tools/list", None, None).await.unwrap();

        let response: ListToolsResult = serde_json::from_value(result).unwrap();
        assert_eq!(response.tools.len(), 1);
        assert_eq!(response.tools[0].name, "test");
    }

    #[tokio::test]
    async fn test_tool_handler() {
        let mut tools: HashMap<String, Arc<dyn McpTool>> = HashMap::new();
        tools.insert("test".to_string(), Arc::new(TestTool::new()));

        let session_manager = Arc::new(SessionManager::new(ServerCapabilities::default()));
        let handler = SessionAwareToolHandler::new(tools, session_manager, false);
        // Create params matching the CallToolParams structure
        let params = turul_mcp_json_rpc_server::RequestParams::Object(
            [
                ("name".to_string(), serde_json::json!("test")),
                ("arguments".to_string(), serde_json::json!({})),
            ]
            .into_iter()
            .collect(),
        );

        let result = handler
            .handle("tools/call", Some(params), None)
            .await
            .unwrap();
        let response: CallToolResult = serde_json::from_value(result).unwrap();

        assert_eq!(response.content.len(), 1);
        if let ToolResult::Text { text, .. } = &response.content[0] {
            assert_eq!(text, "test result");
        }
    }
}