tl-mcp 0.3.5

MCP (Model Context Protocol) integration for ThinkingLanguage
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
//! MCP server implementation for ThinkingLanguage.
//!
//! Provides [`TlServerHandler`] which implements the rmcp [`ServerHandler`] trait,
//! allowing TL to run as an MCP server over stdio. External MCP clients can connect,
//! discover registered tools via `tools/list`, and invoke them via `tools/call`.
//! The server also supports resources (`resources/list`, `resources/read`) and
//! prompts (`prompts/list`, `prompts/get`).
//!
//! # Example
//!
//! ```rust,no_run
//! use tl_mcp::server::{TlServerHandler, ToolDef, ToolHandler};
//! use std::sync::Arc;
//! use serde_json::json;
//!
//! let handler = TlServerHandler::builder()
//!     .name("my-tl-server")
//!     .version("1.0.0")
//!     .tool(ToolDef {
//!         name: "echo".to_string(),
//!         description: "Echoes back the input".to_string(),
//!         input_schema: json!({"type": "object", "properties": {"message": {"type": "string"}}}),
//!         handler: Arc::new(|args| Ok(args)),
//!     })
//!     .build();
//!
//! // tl_mcp::server::serve_stdio(handler).unwrap();
//! ```

use std::sync::Arc;

use rmcp::{
    handler::server::ServerHandler,
    model::{
        AnnotateAble, CallToolRequestParams, CallToolResult, Content, GetPromptRequestParams,
        GetPromptResult, Implementation, ListPromptsResult, ListResourcesResult, ListToolsResult,
        PaginatedRequestParams, Prompt, PromptArgument, PromptMessage, PromptMessageRole,
        RawResource, ReadResourceRequestParams, ReadResourceResult, ResourceContents,
        ServerCapabilities, ServerInfo, Tool,
    },
    service::ServiceExt,
};

use crate::error::McpError;

// ---------------------------------------------------------------------------
// Channel-based tool dispatch
// ---------------------------------------------------------------------------

/// A request to call a TL function from the MCP server thread.
///
/// When using channel-based dispatch, each tool invocation produces a
/// `ToolCallRequest` sent over a channel to the main TL execution thread.
/// The receiver processes the call and sends the result back via `response_tx`.
pub struct ToolCallRequest {
    /// Name of the tool being called.
    pub tool_name: String,
    /// JSON arguments passed by the MCP client.
    pub arguments: serde_json::Value,
    /// One-shot channel to send the result back to the MCP server thread.
    pub response_tx: std::sync::mpsc::SyncSender<Result<serde_json::Value, String>>,
}

/// Tool definition for channel-based dispatch (no closure handler).
///
/// Unlike [`ToolDef`], this does not carry a handler callback. Instead,
/// tools registered via [`TlServerBuilder::channel_tools`] send each
/// invocation through a channel for external processing.
pub struct ChannelToolDef {
    /// The tool name (must be unique within a server).
    pub name: String,
    /// Human-readable description of what the tool does.
    pub description: String,
    /// JSON Schema describing the expected input parameters.
    pub input_schema: serde_json::Value,
}

// ---------------------------------------------------------------------------
// ToolHandler type & ToolDef struct
// ---------------------------------------------------------------------------

/// Callback type for tool invocation.
///
/// Receives the tool arguments as a JSON value and returns either a JSON result
/// or a string error message.
pub type ToolHandler =
    Arc<dyn Fn(serde_json::Value) -> Result<serde_json::Value, String> + Send + Sync>;

/// A tool definition with its handler callback.
///
/// `Clone` is supported because the handler is wrapped in `Arc`.
#[derive(Clone)]
pub struct ToolDef {
    /// The tool name (must be unique within a server).
    pub name: String,
    /// Human-readable description of what the tool does.
    pub description: String,
    /// JSON Schema describing the expected input parameters.
    pub input_schema: serde_json::Value,
    /// The callback that executes this tool.
    pub handler: ToolHandler,
}

// ---------------------------------------------------------------------------
// ResourceDef & PromptDef
// ---------------------------------------------------------------------------

/// A static resource definition for the MCP server.
///
/// Resources are read-only data objects that clients can list and read.
/// Each resource has a unique URI and text content.
#[derive(Clone)]
pub struct ResourceDef {
    /// The display name of the resource.
    pub name: String,
    /// The URI that identifies this resource (e.g. `"tl://readme"`).
    pub uri: String,
    /// Optional human-readable description.
    pub description: Option<String>,
    /// Optional MIME type (e.g. `"text/plain"`, `"application/json"`).
    pub mime_type: Option<String>,
    /// The text content of the resource.
    pub content: String,
}

/// A prompt argument definition.
#[derive(Clone)]
pub struct PromptArgDef {
    /// The argument name.
    pub name: String,
    /// Optional human-readable description.
    pub description: Option<String>,
    /// Whether this argument is required.
    pub required: bool,
}

/// Callback type for prompt invocation.
///
/// Receives the prompt arguments as a JSON value and returns either a list of
/// prompt messages or a string error message.
pub type PromptHandler =
    Arc<dyn Fn(serde_json::Value) -> Result<Vec<PromptMessageDef>, String> + Send + Sync>;

/// A prompt definition for the MCP server.
///
/// Prompts are parameterised message templates that clients can list and invoke.
/// The handler receives arguments and returns a sequence of messages.
#[derive(Clone)]
pub struct PromptDef {
    /// The prompt name (must be unique within a server).
    pub name: String,
    /// Optional human-readable description.
    pub description: Option<String>,
    /// The arguments this prompt accepts.
    pub arguments: Vec<PromptArgDef>,
    /// The callback that generates prompt messages from arguments.
    pub handler: PromptHandler,
}

/// A single message returned by a prompt handler.
#[derive(Clone, Debug, PartialEq)]
pub struct PromptMessageDef {
    /// The role: `"user"` or `"assistant"`.
    pub role: String,
    /// The text content of the message.
    pub content: String,
}

// ---------------------------------------------------------------------------
// TlServerHandler
// ---------------------------------------------------------------------------

/// MCP server handler that dispatches tool calls to registered TL tool handlers.
///
/// Implements the rmcp [`ServerHandler`] trait. Use [`TlServerHandler::builder()`]
/// to construct an instance with registered tools.
pub struct TlServerHandler {
    pub(crate) tools: Vec<ToolDef>,
    pub(crate) resources: Vec<ResourceDef>,
    pub(crate) prompts: Vec<PromptDef>,
    pub(crate) server_info: ServerInfo,
}

impl TlServerHandler {
    /// Create a new builder for constructing a `TlServerHandler`.
    pub fn builder() -> TlServerBuilder {
        TlServerBuilder {
            tools: Vec::new(),
            resources: Vec::new(),
            prompts: Vec::new(),
            name: "tl-mcp-server".to_string(),
            version: "0.1.0".to_string(),
        }
    }

    /// Returns the number of registered tools.
    pub fn tool_count(&self) -> usize {
        self.tools.len()
    }

    /// Returns the number of registered resources.
    pub fn resource_count(&self) -> usize {
        self.resources.len()
    }

    /// Returns the number of registered prompts.
    pub fn prompt_count(&self) -> usize {
        self.prompts.len()
    }

    /// Convert a `ToolDef` into an rmcp `Tool` for protocol responses.
    fn tool_def_to_rmcp(def: &ToolDef) -> Tool {
        // Extract the JSON object from the schema value.
        // If it's not an object, wrap it in one with "type": "object".
        let schema_obj = match &def.input_schema {
            serde_json::Value::Object(map) => map.clone(),
            _ => {
                let mut map = serde_json::Map::new();
                map.insert(
                    "type".to_string(),
                    serde_json::Value::String("object".to_string()),
                );
                map
            }
        };
        Tool::new(def.name.clone(), def.description.clone(), schema_obj)
    }
}

impl ServerHandler for TlServerHandler {
    fn get_info(&self) -> ServerInfo {
        self.server_info.clone()
    }

    fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<ListToolsResult, rmcp::ErrorData>> + Send + '_ {
        let tools: Vec<Tool> = self.tools.iter().map(Self::tool_def_to_rmcp).collect();
        std::future::ready(Ok(ListToolsResult {
            meta: None,
            next_cursor: None,
            tools,
        }))
    }

    fn call_tool(
        &self,
        request: CallToolRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<CallToolResult, rmcp::ErrorData>> + Send + '_ {
        let result = self.dispatch_tool_call(&request);
        std::future::ready(result)
    }

    fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<ListResourcesResult, rmcp::ErrorData>> + Send + '_ {
        let resources = self
            .resources
            .iter()
            .map(|r| {
                let mut raw = RawResource::new(&r.uri, &r.name);
                if let Some(desc) = &r.description {
                    raw = raw.with_description(desc.as_str());
                }
                if let Some(mime) = &r.mime_type {
                    raw = raw.with_mime_type(mime.as_str());
                }
                raw.no_annotation()
            })
            .collect();
        std::future::ready(Ok(ListResourcesResult {
            meta: None,
            next_cursor: None,
            resources,
        }))
    }

    fn read_resource(
        &self,
        request: ReadResourceRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<ReadResourceResult, rmcp::ErrorData>> + Send + '_ {
        let uri = &request.uri;
        let result = self.resources.iter().find(|r| r.uri == *uri);
        match result {
            Some(r) => {
                let mut content = ResourceContents::text(&r.content, &r.uri);
                if let Some(mime) = &r.mime_type {
                    content = content.with_mime_type(mime.as_str());
                }
                std::future::ready(Ok(ReadResourceResult::new(vec![content])))
            }
            None => std::future::ready(Err(rmcp::ErrorData::resource_not_found(
                format!("Resource not found: {uri}"),
                None,
            ))),
        }
    }

    fn list_prompts(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<ListPromptsResult, rmcp::ErrorData>> + Send + '_ {
        let prompts = self
            .prompts
            .iter()
            .map(|p| {
                let args: Option<Vec<PromptArgument>> = if p.arguments.is_empty() {
                    None
                } else {
                    Some(
                        p.arguments
                            .iter()
                            .map(|a| {
                                let mut arg = PromptArgument::new(&a.name);
                                if let Some(desc) = &a.description {
                                    arg = arg.with_description(desc.as_str());
                                }
                                arg = arg.with_required(a.required);
                                arg
                            })
                            .collect(),
                    )
                };
                Prompt::new(&p.name, p.description.as_deref(), args)
            })
            .collect();
        std::future::ready(Ok(ListPromptsResult {
            meta: None,
            next_cursor: None,
            prompts,
        }))
    }

    fn get_prompt(
        &self,
        request: GetPromptRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> impl Future<Output = Result<GetPromptResult, rmcp::ErrorData>> + Send + '_ {
        let name = &request.name;
        let result = self.prompts.iter().find(|p| p.name == *name);
        match result {
            Some(p) => {
                let args_json = match &request.arguments {
                    Some(args) => serde_json::Value::Object(args.clone()),
                    None => serde_json::Value::Object(serde_json::Map::new()),
                };
                match (p.handler)(args_json) {
                    Ok(messages) => {
                        let prompt_messages: Vec<PromptMessage> = messages
                            .iter()
                            .map(|m| {
                                let role = if m.role == "assistant" {
                                    PromptMessageRole::Assistant
                                } else {
                                    PromptMessageRole::User
                                };
                                PromptMessage::new_text(role, &m.content)
                            })
                            .collect();
                        let mut result = GetPromptResult::new(prompt_messages);
                        if let Some(desc) = &p.description {
                            result = result.with_description(desc.as_str());
                        }
                        std::future::ready(Ok(result))
                    }
                    Err(e) => std::future::ready(Err(rmcp::ErrorData::internal_error(e, None))),
                }
            }
            None => std::future::ready(Err(rmcp::ErrorData::invalid_params(
                format!("Prompt not found: {name}"),
                None,
            ))),
        }
    }
}

impl TlServerHandler {
    /// Dispatch a tool call to the matching registered handler.
    pub(crate) fn dispatch_tool_call(
        &self,
        request: &CallToolRequestParams,
    ) -> Result<CallToolResult, rmcp::ErrorData> {
        let tool_name = request.name.as_ref();

        // Find the matching tool
        let tool_def = self.tools.iter().find(|t| t.name == tool_name);
        let tool_def = match tool_def {
            Some(t) => t,
            None => {
                return Ok(CallToolResult::error(vec![Content::text(format!(
                    "Unknown tool: {tool_name}"
                ))]));
            }
        };

        // Convert the arguments map to a serde_json::Value::Object
        let args = match &request.arguments {
            Some(map) => serde_json::Value::Object(map.clone()),
            None => serde_json::Value::Object(serde_json::Map::new()),
        };

        // Call the handler
        match (tool_def.handler)(args) {
            Ok(result) => {
                let text = match result {
                    serde_json::Value::String(s) => s,
                    other => other.to_string(),
                };
                Ok(CallToolResult::success(vec![Content::text(text)]))
            }
            Err(err) => Ok(CallToolResult::error(vec![Content::text(err)])),
        }
    }
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Builder for constructing a [`TlServerHandler`] with registered tools,
/// resources, and prompts.
pub struct TlServerBuilder {
    tools: Vec<ToolDef>,
    resources: Vec<ResourceDef>,
    prompts: Vec<PromptDef>,
    name: String,
    version: String,
}

impl TlServerBuilder {
    /// Set the server name reported during MCP initialization.
    pub fn name(mut self, name: &str) -> Self {
        self.name = name.to_string();
        self
    }

    /// Set the server version reported during MCP initialization.
    pub fn version(mut self, version: &str) -> Self {
        self.version = version.to_string();
        self
    }

    /// Register a tool with the server.
    pub fn tool(mut self, def: ToolDef) -> Self {
        self.tools.push(def);
        self
    }

    /// Register a resource with the server.
    pub fn resource(mut self, def: ResourceDef) -> Self {
        self.resources.push(def);
        self
    }

    /// Register a prompt with the server.
    pub fn prompt(mut self, def: PromptDef) -> Self {
        self.prompts.push(def);
        self
    }

    /// Register tools that dispatch via channel instead of closures.
    ///
    /// Returns `(self, receiver)` where `receiver` yields [`ToolCallRequest`]s
    /// for each tool invocation. The caller is responsible for reading from the
    /// receiver and sending results back via each request's `response_tx`.
    ///
    /// The channel has a bounded capacity of 32 pending requests.
    pub fn channel_tools(
        mut self,
        tools: Vec<ChannelToolDef>,
    ) -> (Self, std::sync::mpsc::Receiver<ToolCallRequest>) {
        let (tx, rx) = std::sync::mpsc::sync_channel(32);
        for tool in tools {
            let tx = tx.clone();
            let tool_name = tool.name.clone();
            self.tools.push(ToolDef {
                name: tool.name,
                description: tool.description,
                input_schema: tool.input_schema,
                handler: Arc::new(move |args| {
                    let (resp_tx, resp_rx) = std::sync::mpsc::sync_channel(1);
                    tx.send(ToolCallRequest {
                        tool_name: tool_name.clone(),
                        arguments: args,
                        response_tx: resp_tx,
                    })
                    .map_err(|_| "Server dispatch channel closed".to_string())?;
                    resp_rx
                        .recv()
                        .map_err(|_| "Tool response channel closed".to_string())?
                }),
            });
        }
        (self, rx)
    }

    /// Build the [`TlServerHandler`] with all registered tools, resources,
    /// and prompts.
    ///
    /// Capabilities are set based on what was registered:
    /// - Tools capability is always enabled.
    /// - Resources capability is enabled if at least one resource was registered.
    /// - Prompts capability is enabled if at least one prompt was registered.
    pub fn build(self) -> TlServerHandler {
        let has_resources = !self.resources.is_empty();
        let has_prompts = !self.prompts.is_empty();

        // The rmcp builder uses const-generic state tracking, so we need to
        // handle each combination to satisfy the type system.
        let capabilities = match (has_resources, has_prompts) {
            (true, true) => ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .enable_prompts()
                .build(),
            (true, false) => ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .build(),
            (false, true) => ServerCapabilities::builder()
                .enable_tools()
                .enable_prompts()
                .build(),
            (false, false) => ServerCapabilities::builder().enable_tools().build(),
        };

        let server_info = ServerInfo::new(capabilities)
            .with_server_info(Implementation::new(&self.name, &self.version));

        TlServerHandler {
            tools: self.tools,
            resources: self.resources,
            prompts: self.prompts,
            server_info,
        }
    }
}

// ---------------------------------------------------------------------------
// Stdio server entry points
// ---------------------------------------------------------------------------

/// Run the MCP server over stdio, blocking until the client disconnects.
///
/// This creates a new tokio runtime internally. For embedding in an existing
/// runtime, use [`serve_stdio_with_runtime`] instead.
pub fn serve_stdio(handler: TlServerHandler) -> Result<(), McpError> {
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|e| McpError::ConnectionFailed(format!("Runtime creation failed: {e}")))?;

    rt.block_on(async {
        let transport = rmcp::transport::io::stdio();
        let service = handler
            .serve(transport)
            .await
            .map_err(|e| McpError::ConnectionFailed(e.to_string()))?;

        // Wait until client disconnects or service is cancelled
        service
            .waiting()
            .await
            .map_err(|e| McpError::ProtocolError(e.to_string()))?;

        Ok(())
    })
}

/// Run the MCP server over stdio using an existing tokio runtime.
///
/// Blocks the calling thread until the client disconnects.
pub fn serve_stdio_with_runtime(
    handler: TlServerHandler,
    runtime: Arc<tokio::runtime::Runtime>,
) -> Result<(), McpError> {
    runtime.block_on(async {
        let transport = rmcp::transport::io::stdio();
        let service = handler
            .serve(transport)
            .await
            .map_err(|e| McpError::ConnectionFailed(e.to_string()))?;

        service
            .waiting()
            .await
            .map_err(|e| McpError::ProtocolError(e.to_string()))?;

        Ok(())
    })
}

/// Start the MCP server on a background thread via stdio.
///
/// Returns a join handle. The tool call receiver should have been obtained
/// from [`TlServerBuilder::channel_tools`] before building.
///
/// The background thread creates its own tokio runtime and blocks on
/// [`serve_stdio`] until the client disconnects.
pub fn serve_stdio_background(
    handler: TlServerHandler,
) -> std::thread::JoinHandle<Result<(), McpError>> {
    std::thread::spawn(move || serve_stdio(handler))
}

// ---------------------------------------------------------------------------
// HTTP server entry points
// ---------------------------------------------------------------------------

/// Run the MCP server over HTTP on the given port, blocking until shutdown.
///
/// Creates a new tokio runtime internally. The server listens on `0.0.0.0:{port}`
/// with the MCP endpoint at `/mcp`.
///
/// # Arguments
/// * `handler` — The server handler with registered tools.
/// * `port` — The TCP port to listen on.
///
/// # Errors
/// * [`McpError::RuntimeError`] — Could not create tokio runtime.
/// * [`McpError::ConnectionFailed`] — Could not bind the port.
pub fn serve_http(handler: TlServerHandler, port: u16) -> Result<(), McpError> {
    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()
        .map_err(|e| McpError::RuntimeError(format!("Failed to create runtime: {e}")))?;
    rt.block_on(serve_http_async(handler, port))
}

/// Run the MCP server over HTTP using an existing tokio runtime.
///
/// Blocks the calling thread until the server shuts down.
pub fn serve_http_with_runtime(
    handler: TlServerHandler,
    port: u16,
    runtime: Arc<tokio::runtime::Runtime>,
) -> Result<(), McpError> {
    runtime.block_on(serve_http_async(handler, port))
}

/// Internal async HTTP server implementation.
async fn serve_http_async(handler: TlServerHandler, port: u16) -> Result<(), McpError> {
    use rmcp::transport::streamable_http_server::{
        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
    };

    // Capture all fields so the factory can create new TlServerHandler instances
    // per session (each session gets its own handler).
    let tools = handler.tools;
    let resources = handler.resources;
    let prompts = handler.prompts;
    let server_info = handler.server_info;

    let service = StreamableHttpService::new(
        move || {
            Ok(TlServerHandler {
                tools: tools.clone(),
                resources: resources.clone(),
                prompts: prompts.clone(),
                server_info: server_info.clone(),
            })
        },
        std::sync::Arc::new(LocalSessionManager::default()),
        StreamableHttpServerConfig::default(),
    );

    let app = axum::Router::new().nest_service("/mcp", service);
    let addr = format!("0.0.0.0:{port}");
    let listener = tokio::net::TcpListener::bind(&addr)
        .await
        .map_err(|e| McpError::ConnectionFailed(format!("Failed to bind {addr}: {e}")))?;

    axum::serve(listener, app)
        .await
        .map_err(|e| McpError::RuntimeError(format!("HTTP server error: {e}")))?;

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn make_echo_tool() -> ToolDef {
        ToolDef {
            name: "echo".to_string(),
            description: "Echoes back the input".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "message": {"type": "string"}
                }
            }),
            handler: Arc::new(|args| {
                let msg = args
                    .get("message")
                    .and_then(|v| v.as_str())
                    .unwrap_or("no message");
                Ok(serde_json::Value::String(msg.to_string()))
            }),
        }
    }

    fn make_add_tool() -> ToolDef {
        ToolDef {
            name: "add".to_string(),
            description: "Adds two numbers".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "a": {"type": "number"},
                    "b": {"type": "number"}
                }
            }),
            handler: Arc::new(|args| {
                let a = args.get("a").and_then(|v| v.as_f64()).unwrap_or(0.0);
                let b = args.get("b").and_then(|v| v.as_f64()).unwrap_or(0.0);
                Ok(json!(a + b))
            }),
        }
    }

    #[test]
    fn test_server_builder() {
        let handler = TlServerHandler::builder()
            .name("test-server")
            .version("2.0.0")
            .tool(make_echo_tool())
            .tool(make_add_tool())
            .build();

        assert_eq!(handler.tool_count(), 2);
        assert_eq!(handler.server_info.server_info.name, "test-server");
        assert_eq!(handler.server_info.server_info.version, "2.0.0");
    }

    #[test]
    fn test_server_capabilities() {
        let handler = TlServerHandler::builder()
            .name("cap-test")
            .version("1.0.0")
            .build();

        let info = handler.server_info.clone();
        // Tools capability should be enabled
        assert!(
            info.capabilities.tools.is_some(),
            "Tools capability should be enabled"
        );
    }

    #[test]
    fn test_server_tool_dispatch_success() {
        let handler = TlServerHandler::builder()
            .name("dispatch-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .tool(make_add_tool())
            .build();

        // Test echo tool
        let mut args_map = serde_json::Map::new();
        args_map.insert(
            "message".to_string(),
            serde_json::Value::String("hello world".to_string()),
        );

        let request = CallToolRequestParams::new("echo").with_arguments(args_map);

        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(false));
        assert_eq!(result.content.len(), 1);
        let text = result.content[0].as_text().unwrap();
        assert_eq!(text.text, "hello world");
    }

    #[test]
    fn test_server_tool_dispatch_add() {
        let handler = TlServerHandler::builder()
            .name("dispatch-test")
            .version("1.0.0")
            .tool(make_add_tool())
            .build();

        let mut args_map = serde_json::Map::new();
        args_map.insert("a".to_string(), json!(3.0));
        args_map.insert("b".to_string(), json!(4.0));

        let request = CallToolRequestParams::new("add").with_arguments(args_map);

        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(false));
        let text = result.content[0].as_text().unwrap();
        // json!(a + b) for floats produces "7.0"
        assert!(
            text.text == "7" || text.text == "7.0",
            "Expected 7 or 7.0, got: {}",
            text.text
        );
    }

    #[test]
    fn test_server_tool_dispatch_unknown_tool() {
        let handler = TlServerHandler::builder()
            .name("dispatch-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .build();

        let request = CallToolRequestParams::new("nonexistent");

        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(true));
        let text = result.content[0].as_text().unwrap();
        assert!(text.text.contains("Unknown tool"));
    }

    #[test]
    fn test_server_tool_dispatch_handler_error() {
        let handler = TlServerHandler::builder()
            .name("error-test")
            .version("1.0.0")
            .tool(ToolDef {
                name: "fail".to_string(),
                description: "Always fails".to_string(),
                input_schema: json!({"type": "object"}),
                handler: Arc::new(|_| Err("Something went wrong".to_string())),
            })
            .build();

        let request = CallToolRequestParams::new("fail");

        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(true));
        let text = result.content[0].as_text().unwrap();
        assert!(text.text.contains("Something went wrong"));
    }

    #[test]
    fn test_server_tool_dispatch_no_arguments() {
        let handler = TlServerHandler::builder()
            .name("no-args-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .build();

        // Call with no arguments — handler should still work
        let request = CallToolRequestParams::new("echo");

        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(false));
        let text = result.content[0].as_text().unwrap();
        assert_eq!(text.text, "no message");
    }

    #[tokio::test]
    async fn test_server_list_tools_via_trait() {
        let handler = TlServerHandler::builder()
            .name("list-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .tool(make_add_tool())
            .build();

        // Create a mock context — we need Peer and RequestContext
        // Since list_tools doesn't actually use the context, we test via
        // the direct method instead of through the full trait dispatch.
        let tools: Vec<Tool> = handler
            .tools
            .iter()
            .map(TlServerHandler::tool_def_to_rmcp)
            .collect();
        assert_eq!(tools.len(), 2);
        assert_eq!(tools[0].name.as_ref(), "echo");
        assert_eq!(tools[1].name.as_ref(), "add");
        assert!(tools[0].description.as_deref() == Some("Echoes back the input"));
        assert!(tools[1].description.as_deref() == Some("Adds two numbers"));
    }

    #[test]
    fn test_tool_schema_conversion() {
        let def = ToolDef {
            name: "test".to_string(),
            description: "Test tool".to_string(),
            input_schema: json!({
                "type": "object",
                "properties": {
                    "x": {"type": "integer"}
                },
                "required": ["x"]
            }),
            handler: Arc::new(|_| Ok(json!(null))),
        };

        let tool = TlServerHandler::tool_def_to_rmcp(&def);
        assert_eq!(tool.name.as_ref(), "test");
        let schema = tool.schema_as_json_value();
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["x"]["type"] == "integer");
    }

    #[test]
    fn test_empty_server() {
        let handler = TlServerHandler::builder()
            .name("empty")
            .version("0.0.1")
            .build();

        assert_eq!(handler.tool_count(), 0);
        assert!(handler.server_info.capabilities.tools.is_some());
    }

    // -----------------------------------------------------------------------
    // Channel-based dispatch tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_channel_tool_dispatch() {
        let (builder, rx) = TlServerHandler::builder()
            .name("channel-test")
            .version("1.0.0")
            .channel_tools(vec![ChannelToolDef {
                name: "greet".to_string(),
                description: "Greet someone".to_string(),
                input_schema: json!({
                    "type": "object",
                    "properties": {
                        "name": { "type": "string" }
                    }
                }),
            }]);
        let handler = builder.build();

        // Simulate a tool call in a background thread
        let handle = std::thread::spawn(move || {
            let request = CallToolRequestParams::new("greet").with_arguments(
                serde_json::Map::from_iter([("name".to_string(), json!("TL"))]),
            );
            handler.dispatch_tool_call(&request)
        });

        // Process the request on the "main" thread
        let req = rx.recv().unwrap();
        assert_eq!(req.tool_name, "greet");
        let name = req.arguments.get("name").unwrap().as_str().unwrap();
        assert_eq!(name, "TL");
        req.response_tx
            .send(Ok(json!(format!("Hello, {name}!"))))
            .unwrap();

        // Check the result
        let result = handle.join().unwrap().unwrap();
        assert_eq!(result.is_error, Some(false));
        let text = result.content[0].as_text().unwrap();
        assert_eq!(text.text, "Hello, TL!");
    }

    #[test]
    fn test_channel_tool_dispatch_error() {
        let (builder, rx) = TlServerHandler::builder()
            .name("channel-err-test")
            .version("1.0.0")
            .channel_tools(vec![ChannelToolDef {
                name: "fail_tool".to_string(),
                description: "A tool that will fail".to_string(),
                input_schema: json!({"type": "object"}),
            }]);
        let handler = builder.build();

        let handle = std::thread::spawn(move || {
            let request = CallToolRequestParams::new("fail_tool");
            handler.dispatch_tool_call(&request)
        });

        // Respond with error
        let req = rx.recv().unwrap();
        assert_eq!(req.tool_name, "fail_tool");
        req.response_tx
            .send(Err("Tool failed intentionally".to_string()))
            .unwrap();

        let result = handle.join().unwrap().unwrap();
        assert_eq!(result.is_error, Some(true));
        let text = result.content[0].as_text().unwrap();
        assert!(text.text.contains("Tool failed intentionally"));
    }

    #[test]
    fn test_channel_tools_mixed_with_closure_tools() {
        let (builder, rx) = TlServerHandler::builder()
            .name("mixed-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .channel_tools(vec![ChannelToolDef {
                name: "channel_add".to_string(),
                description: "Add via channel".to_string(),
                input_schema: json!({"type": "object"}),
            }]);
        let handler = builder.build();

        // Handler should have 2 tools total (1 closure + 1 channel)
        assert_eq!(handler.tool_count(), 2);

        // The closure-based echo tool should still work directly
        let echo_req = CallToolRequestParams::new("echo").with_arguments(
            serde_json::Map::from_iter([("message".to_string(), json!("direct"))]),
        );
        let echo_result = handler.dispatch_tool_call(&echo_req).unwrap();
        assert_eq!(echo_result.is_error, Some(false));
        let text = echo_result.content[0].as_text().unwrap();
        assert_eq!(text.text, "direct");

        // The channel-based tool should dispatch via the channel
        let handle = {
            let handler_ref = &handler;
            // We need to move handler into the thread, but we also need rx.
            // Instead, call dispatch from main and process in background.
            let (result_tx, result_rx) =
                std::sync::mpsc::sync_channel::<Result<CallToolResult, rmcp::ErrorData>>(1);
            let handler = TlServerHandler {
                tools: handler_ref.tools.clone(),
                resources: handler_ref.resources.clone(),
                prompts: handler_ref.prompts.clone(),
                server_info: handler_ref.server_info.clone(),
            };
            let jh = std::thread::spawn(move || {
                let req = CallToolRequestParams::new("channel_add").with_arguments(
                    serde_json::Map::from_iter([
                        ("a".to_string(), json!(10)),
                        ("b".to_string(), json!(20)),
                    ]),
                );
                let r = handler.dispatch_tool_call(&req);
                result_tx.send(r).ok();
            });
            // Process channel request
            let tool_req = rx.recv().unwrap();
            assert_eq!(tool_req.tool_name, "channel_add");
            let a = tool_req
                .arguments
                .get("a")
                .and_then(|v| v.as_i64())
                .unwrap_or(0);
            let b = tool_req
                .arguments
                .get("b")
                .and_then(|v| v.as_i64())
                .unwrap_or(0);
            tool_req.response_tx.send(Ok(json!(a + b))).unwrap();
            let result = result_rx.recv().unwrap().unwrap();
            assert_eq!(result.is_error, Some(false));
            let text = result.content[0].as_text().unwrap();
            assert_eq!(text.text, "30");
            jh
        };
        handle.join().unwrap();
    }

    #[test]
    fn test_channel_tool_unknown_tool() {
        let (builder, _rx) = TlServerHandler::builder()
            .name("channel-unknown-test")
            .version("1.0.0")
            .channel_tools(vec![ChannelToolDef {
                name: "only_tool".to_string(),
                description: "The only tool".to_string(),
                input_schema: json!({"type": "object"}),
            }]);
        let handler = builder.build();

        // Calling a non-existent tool should not touch the channel
        let request = CallToolRequestParams::new("nonexistent");
        let result = handler.dispatch_tool_call(&request).unwrap();
        assert_eq!(result.is_error, Some(true));
        let text = result.content[0].as_text().unwrap();
        assert!(text.text.contains("Unknown tool"));
    }

    #[test]
    fn test_serve_stdio_background_type() {
        // Just verify the function signature compiles and returns a JoinHandle.
        // We cannot actually run stdio in tests, but we can verify the type.
        let _: fn(TlServerHandler) -> std::thread::JoinHandle<Result<(), McpError>> =
            serve_stdio_background;
    }

    // -----------------------------------------------------------------------
    // Resource tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_server_with_resources() {
        let handler = TlServerHandler::builder()
            .name("res-test")
            .version("1.0.0")
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: Some("A readme".to_string()),
                mime_type: Some("text/plain".to_string()),
                content: "Hello from TL!".to_string(),
            })
            .build();

        assert_eq!(handler.resource_count(), 1);
        assert!(handler.server_info.capabilities.resources.is_some());
        assert!(handler.server_info.capabilities.tools.is_some());
    }

    #[test]
    fn test_server_no_resources_capability_disabled() {
        let handler = TlServerHandler::builder()
            .name("no-res-test")
            .version("1.0.0")
            .build();

        assert_eq!(handler.resource_count(), 0);
        assert!(
            handler.server_info.capabilities.resources.is_none(),
            "Resources capability should be disabled when no resources registered"
        );
    }

    #[test]
    fn test_list_resources() {
        let handler = TlServerHandler::builder()
            .name("list-res-test")
            .version("1.0.0")
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: Some("A readme".to_string()),
                mime_type: Some("text/plain".to_string()),
                content: "Hello from TL!".to_string(),
            })
            .resource(ResourceDef {
                name: "config".to_string(),
                uri: "tl://config".to_string(),
                description: None,
                mime_type: Some("application/json".to_string()),
                content: "{}".to_string(),
            })
            .build();

        assert_eq!(handler.resource_count(), 2);
        assert_eq!(handler.resources[0].name, "readme");
        assert_eq!(handler.resources[1].name, "config");
    }

    #[test]
    fn test_read_resource_found() {
        let handler = TlServerHandler::builder()
            .name("read-res-test")
            .version("1.0.0")
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: Some("A readme".to_string()),
                mime_type: Some("text/plain".to_string()),
                content: "Hello from TL!".to_string(),
            })
            .build();

        let resource = handler.resources.iter().find(|r| r.uri == "tl://readme");
        assert!(resource.is_some());
        let r = resource.unwrap();
        assert_eq!(r.content, "Hello from TL!");
        assert_eq!(r.mime_type.as_deref(), Some("text/plain"));
    }

    #[test]
    fn test_read_resource_not_found() {
        let handler = TlServerHandler::builder()
            .name("read-res-test")
            .version("1.0.0")
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: None,
                mime_type: None,
                content: "content".to_string(),
            })
            .build();

        let resource = handler
            .resources
            .iter()
            .find(|r| r.uri == "tl://nonexistent");
        assert!(resource.is_none());
    }

    // -----------------------------------------------------------------------
    // Prompt tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_server_with_prompts() {
        let handler = TlServerHandler::builder()
            .name("prompt-test")
            .version("1.0.0")
            .prompt(PromptDef {
                name: "greeting".to_string(),
                description: Some("Greet someone".to_string()),
                arguments: vec![PromptArgDef {
                    name: "name".to_string(),
                    description: Some("Person to greet".to_string()),
                    required: true,
                }],
                handler: Arc::new(|args| {
                    let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("World");
                    Ok(vec![PromptMessageDef {
                        role: "user".to_string(),
                        content: format!("Please greet {name} warmly"),
                    }])
                }),
            })
            .build();

        assert_eq!(handler.prompt_count(), 1);
        assert!(handler.server_info.capabilities.prompts.is_some());
        assert!(handler.server_info.capabilities.tools.is_some());
    }

    #[test]
    fn test_server_no_prompts_capability_disabled() {
        let handler = TlServerHandler::builder()
            .name("no-prompt-test")
            .version("1.0.0")
            .build();

        assert_eq!(handler.prompt_count(), 0);
        assert!(
            handler.server_info.capabilities.prompts.is_none(),
            "Prompts capability should be disabled when no prompts registered"
        );
    }

    #[test]
    fn test_prompt_handler_invocation() {
        let handler = TlServerHandler::builder()
            .name("prompt-invoke-test")
            .version("1.0.0")
            .prompt(PromptDef {
                name: "greeting".to_string(),
                description: Some("Greet someone".to_string()),
                arguments: vec![PromptArgDef {
                    name: "name".to_string(),
                    description: Some("Person to greet".to_string()),
                    required: true,
                }],
                handler: Arc::new(|args| {
                    let name = args.get("name").and_then(|v| v.as_str()).unwrap_or("World");
                    Ok(vec![
                        PromptMessageDef {
                            role: "user".to_string(),
                            content: format!("Please greet {name} warmly"),
                        },
                        PromptMessageDef {
                            role: "assistant".to_string(),
                            content: format!("Hello, {name}! Welcome!"),
                        },
                    ])
                }),
            })
            .build();

        let prompt = &handler.prompts[0];
        let args = json!({"name": "Alice"});
        let messages = (prompt.handler)(args).unwrap();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0].role, "user");
        assert_eq!(messages[0].content, "Please greet Alice warmly");
        assert_eq!(messages[1].role, "assistant");
        assert_eq!(messages[1].content, "Hello, Alice! Welcome!");
    }

    #[test]
    fn test_prompt_handler_error() {
        let handler = TlServerHandler::builder()
            .name("prompt-err-test")
            .version("1.0.0")
            .prompt(PromptDef {
                name: "failing".to_string(),
                description: None,
                arguments: vec![],
                handler: Arc::new(|_| Err("Missing required argument".to_string())),
            })
            .build();

        let prompt = &handler.prompts[0];
        let result = (prompt.handler)(json!({}));
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Missing required argument");
    }

    #[test]
    fn test_prompt_not_found() {
        let handler = TlServerHandler::builder()
            .name("prompt-notfound-test")
            .version("1.0.0")
            .prompt(PromptDef {
                name: "existing".to_string(),
                description: None,
                arguments: vec![],
                handler: Arc::new(|_| Ok(vec![])),
            })
            .build();

        let found = handler.prompts.iter().find(|p| p.name == "nonexistent");
        assert!(found.is_none());
    }

    #[test]
    fn test_server_all_capabilities() {
        let handler = TlServerHandler::builder()
            .name("full-test")
            .version("1.0.0")
            .tool(make_echo_tool())
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: None,
                mime_type: None,
                content: "content".to_string(),
            })
            .prompt(PromptDef {
                name: "greet".to_string(),
                description: None,
                arguments: vec![],
                handler: Arc::new(|_| Ok(vec![])),
            })
            .build();

        assert_eq!(handler.tool_count(), 1);
        assert_eq!(handler.resource_count(), 1);
        assert_eq!(handler.prompt_count(), 1);
        assert!(handler.server_info.capabilities.tools.is_some());
        assert!(handler.server_info.capabilities.resources.is_some());
        assert!(handler.server_info.capabilities.prompts.is_some());
    }

    #[tokio::test]
    async fn test_list_resources_via_trait() {
        let handler = TlServerHandler::builder()
            .name("trait-res-test")
            .version("1.0.0")
            .resource(ResourceDef {
                name: "readme".to_string(),
                uri: "tl://readme".to_string(),
                description: Some("A readme".to_string()),
                mime_type: Some("text/plain".to_string()),
                content: "Hello from TL!".to_string(),
            })
            .build();

        // Convert using the same logic as list_resources
        let resources: Vec<rmcp::model::Resource> = handler
            .resources
            .iter()
            .map(|r| {
                let mut raw = RawResource::new(&r.uri, &r.name);
                if let Some(desc) = &r.description {
                    raw = raw.with_description(desc.as_str());
                }
                if let Some(mime) = &r.mime_type {
                    raw = raw.with_mime_type(mime.as_str());
                }
                raw.no_annotation()
            })
            .collect();

        assert_eq!(resources.len(), 1);
        assert_eq!(resources[0].name, "readme");
        assert_eq!(resources[0].uri, "tl://readme");
        assert_eq!(resources[0].description.as_deref(), Some("A readme"));
        assert_eq!(resources[0].mime_type.as_deref(), Some("text/plain"));
    }

    #[tokio::test]
    async fn test_list_prompts_via_trait() {
        let handler = TlServerHandler::builder()
            .name("trait-prompt-test")
            .version("1.0.0")
            .prompt(PromptDef {
                name: "greeting".to_string(),
                description: Some("Greet someone".to_string()),
                arguments: vec![
                    PromptArgDef {
                        name: "name".to_string(),
                        description: Some("Person to greet".to_string()),
                        required: true,
                    },
                    PromptArgDef {
                        name: "style".to_string(),
                        description: None,
                        required: false,
                    },
                ],
                handler: Arc::new(|_| Ok(vec![])),
            })
            .build();

        // Convert using the same logic as list_prompts
        let prompts: Vec<Prompt> = handler
            .prompts
            .iter()
            .map(|p| {
                let args: Option<Vec<PromptArgument>> = if p.arguments.is_empty() {
                    None
                } else {
                    Some(
                        p.arguments
                            .iter()
                            .map(|a| {
                                let mut arg = PromptArgument::new(&a.name);
                                if let Some(desc) = &a.description {
                                    arg = arg.with_description(desc.as_str());
                                }
                                arg = arg.with_required(a.required);
                                arg
                            })
                            .collect(),
                    )
                };
                Prompt::new(&p.name, p.description.as_deref(), args)
            })
            .collect();

        assert_eq!(prompts.len(), 1);
        assert_eq!(prompts[0].name, "greeting");
        assert_eq!(prompts[0].description.as_deref(), Some("Greet someone"));
        let args = prompts[0].arguments.as_ref().unwrap();
        assert_eq!(args.len(), 2);
        assert_eq!(args[0].name, "name");
        assert_eq!(args[0].description.as_deref(), Some("Person to greet"));
        assert_eq!(args[0].required, Some(true));
        assert_eq!(args[1].name, "style");
        assert_eq!(args[1].description, None);
        assert_eq!(args[1].required, Some(false));
    }
}