turbomcp-core 3.5.0

Core MCP types and primitives - no_std compatible for WASM targets
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
//! Shared MCP request router for all platforms.
//!
//! This module provides the core routing logic that maps JSON-RPC requests to
//! `McpHandler` methods. It is designed to work on both native and WASM targets.
//!
//! # Design Philosophy
//!
//! - **Unified**: Single router implementation for native and WASM
//! - **no_std Compatible**: Works in `no_std` environments with `alloc`
//! - **Extensible**: Native can layer additional validation (protocol, capabilities)
//!
//! # Example
//!
//! ```rust,ignore
//! use turbomcp_core::router::{route_request, RouteConfig};
//! use turbomcp_core::jsonrpc::{JsonRpcIncoming, JsonRpcOutgoing};
//! use turbomcp_core::context::RequestContext;
//!
//! // Basic routing (WASM-friendly)
//! let response = route_request(&handler, request, &ctx, &RouteConfig::default()).await;
//!
//! // With protocol version override
//! let config = RouteConfig {
//!     protocol_version: Some("2025-11-25"),
//! };
//! let response = route_request(&handler, request, &ctx, &config).await;
//! ```

use alloc::string::ToString;
use serde_json::Value;

use crate::PROTOCOL_VERSION;
use crate::context::RequestContext;
use crate::error::McpError;
use crate::handler::McpHandler;
use crate::jsonrpc::{JsonRpcIncoming, JsonRpcOutgoing};
use turbomcp_types::ServerInfo;

/// Deliver a client notification to its handler hook, if it has one.
///
/// Notifications get no response, so nothing is returned and a failing hook is
/// swallowed; unrecognised notifications are ignored, per the spec's
/// instruction to tolerate them.
///
/// This is public because `turbomcp-server` wraps this module with its own
/// router that short-circuits notifications before delegating here. Both call
/// this, so wiring a new hook is a one-line change in one place instead of a
/// change that silently applies to only some transports.
pub async fn dispatch_notification<H: McpHandler>(
    handler: &H,
    request: &JsonRpcIncoming,
    ctx: &RequestContext,
) {
    if request.method == "notifications/roots/list_changed" {
        let _ = handler.on_roots_list_changed(ctx).await;
    }
}

/// Lift `params._meta.progressToken` off an incoming request.
///
/// Per the MCP progress utility the token is `string | number`; anything else
/// is ignored rather than rejected, since a malformed `_meta` entry must not
/// fail an otherwise valid request.
fn progress_token(request: &JsonRpcIncoming) -> Option<Value> {
    let token = request
        .params
        .as_ref()?
        .get("_meta")?
        .get("progressToken")?;
    match token {
        Value::String(_) | Value::Number(_) => Some(token.clone()),
        _ => None,
    }
}

/// Apply a page of a list result and mint the cursor for the next one.
///
/// Cursors are opaque to clients — the spec says so explicitly, and forbids
/// them from parsing one — so the encoding is ours to choose. It carries the
/// list kind alongside the offset (`"tools:100"`) purely so a cursor handed
/// back to the wrong method is caught rather than silently reinterpreted as an
/// offset into a different list.
///
/// Returns `Err` for a cursor that is malformed, belongs to another method, or
/// points past the end. The spec's own guidance is `-32602` for an invalid
/// cursor, and failing loudly beats serving page one again, which a client
/// walking pages would read as an infinite list.
/// Ends a request's progress stream when the request has been answered.
struct ProgressScope<'a>(&'a RequestContext);

impl Drop for ProgressScope<'_> {
    fn drop(&mut self) {
        self.0.end_progress();
    }
}

/// Enforce a tool's `execution.taskSupport`.
///
/// It binds only on a server that declares `tasks.requests.tools.call`; a
/// server without it ignores `task` and runs the call normally, as the tasks
/// utility requires. On one that declares it, a `required` tool called without
/// `task` MUST be answered -32601, and a `forbidden` (or unmarked) tool called
/// with one SHOULD be.
///
/// This SDK does not run task-augmented calls itself: a handler that declares
/// the capability implements them, and this keeps plain and task invocations
/// on the side of the line the tool declared.
fn check_task_support<H: McpHandler>(
    handler: &H,
    name: &str,
    is_task: bool,
    ctx: &RequestContext,
) -> Result<(), McpError> {
    let declares_task_calls = handler
        .server_capabilities()
        .tasks
        .and_then(|tasks| tasks.requests)
        .and_then(|requests| requests.tools)
        .and_then(|tools| tools.call)
        .is_some();
    if !declares_task_calls {
        return Ok(());
    }

    let support = handler
        .list_tools_for(ctx)
        .into_iter()
        .find(|tool| tool.name == name)
        .and_then(|tool| tool.execution)
        .and_then(|execution| execution.task_support);
    match (support, is_task) {
        (Some(turbomcp_types::TaskSupportLevel::Required), false) => Err(McpError::new(
            crate::error::ErrorKind::MethodNotFound,
            alloc::format!("tool '{name}' must be invoked as a task"),
        )),
        (None | Some(turbomcp_types::TaskSupportLevel::Forbidden), true) => Err(McpError::new(
            crate::error::ErrorKind::MethodNotFound,
            alloc::format!("tool '{name}' cannot be invoked as a task"),
        )),
        _ => Ok(()),
    }
}

/// The `cursor` param of a list request.
///
/// Absent or `null` means the first page. The schema types `Cursor` as a
/// string, and pagination says invalid cursors SHOULD be answered with
/// -32602; a number or object used to be silently read as "first page",
/// which restarts a client's walk without telling it.
fn cursor_param(params: Option<&serde_json::Value>) -> Result<Option<&str>, McpError> {
    match params.and_then(|params| params.get("cursor")) {
        None | Some(serde_json::Value::Null) => Ok(None),
        Some(serde_json::Value::String(cursor)) => Ok(Some(cursor)),
        Some(_) => Err(McpError::invalid_params("cursor must be a string")),
    }
}

fn paginate<T>(
    items: alloc::vec::Vec<T>,
    kind: &str,
    cursor: Option<&str>,
    page_size: Option<usize>,
) -> Result<(alloc::vec::Vec<T>, Option<alloc::string::String>), McpError> {
    let offset = match cursor {
        None => 0,
        Some(raw) => {
            let parsed = raw
                .split_once(':')
                .filter(|(cursor_kind, _)| *cursor_kind == kind)
                .and_then(|(_, offset)| offset.parse::<usize>().ok());
            match parsed {
                Some(offset) if offset <= items.len() => offset,
                _ => {
                    return Err(McpError::invalid_params(alloc::format!(
                        "invalid cursor for {kind}/list"
                    )));
                }
            }
        }
    };

    // No page size configured: the server does not paginate, so hand back
    // everything from the offset and mint no cursor.
    let Some(page_size) = page_size.filter(|size| *size > 0) else {
        return Ok((items.into_iter().skip(offset).collect(), None));
    };

    let mut remaining = items.into_iter().skip(offset);
    let page: alloc::vec::Vec<T> = remaining.by_ref().take(page_size).collect();
    let next = if remaining.next().is_some() {
        // `next()` consumed one, so the following page starts after it.
        Some(alloc::format!("{kind}:{}", offset + page.len()))
    } else {
        None
    };
    Ok((page, next))
}

/// Configuration for request routing.
///
/// This provides minimal configuration that works on all platforms.
/// Native platforms can provide additional validation through middleware.
#[derive(Debug, Clone, Default)]
pub struct RouteConfig<'a> {
    /// Override protocol version in initialize response.
    /// If None, uses `PROTOCOL_VERSION` constant.
    pub protocol_version: Option<&'a str>,
}

/// Route a JSON-RPC request to the appropriate handler method.
///
/// This is the core routing function used by both native and WASM platforms.
/// It dispatches MCP methods to the corresponding `McpHandler` methods.
///
/// # Supported Methods
///
/// - `initialize` - Returns server info and capabilities
/// - `initialized` / `notifications/initialized` - Acknowledges initialization
/// - `tools/list` - Lists available tools
/// - `tools/call` - Calls a tool by name
/// - `resources/list` - Lists available resources
/// - `resources/read` - Reads a resource by URI
/// - `prompts/list` - Lists available prompts
/// - `prompts/get` - Gets a prompt by name
/// - `ping` - Health check
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp_core::router::{route_request, RouteConfig};
///
/// let config = RouteConfig::default();
/// let response = route_request(&handler, request, &ctx, &config).await;
///
/// if response.should_send() {
///     // Send response to client
/// }
/// ```
pub async fn route_request<H: McpHandler>(
    handler: &H,
    request: JsonRpcIncoming,
    ctx: &RequestContext,
    config: &RouteConfig<'_>,
) -> JsonRpcOutgoing {
    if request.is_notification() {
        dispatch_notification(handler, &request, ctx).await;
        return JsonRpcOutgoing::notification_ack();
    }

    // Any request may carry `_meta.progressToken` to opt into progress
    // notifications, so the token is lifted here — once, centrally — rather
    // than in each method arm or each transport. The context is only cloned
    // when a token is actually present, keeping the common path allocation-free.
    let with_token;
    let ctx = match progress_token(&request) {
        Some(token) => {
            with_token = ctx.clone().with_progress_token(token);
            &with_token
        }
        None => ctx,
    };
    // Releases the request's progress state however this function returns.
    let _progress = ProgressScope(ctx);

    let id = request.id.clone();

    match request.method.as_str() {
        // Initialize handshake
        "initialize" => {
            let params = request.params.clone().unwrap_or_default();

            // Validate clientInfo is present (MCP spec requirement)
            let Some(client_info) = params.get("clientInfo") else {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("Missing required field: clientInfo"),
                );
            };

            // Validate clientInfo has required fields
            let client_name = client_info.get("name").and_then(|v| v.as_str());
            let client_version = client_info.get("version").and_then(|v| v.as_str());
            if client_name.is_none() || client_version.is_none() {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("clientInfo must contain 'name' and 'version' fields"),
                );
            }

            // Echo the client's version when it is one we support, rather than
            // always answering with the newest. The lifecycle spec: "If the
            // server supports the requested protocol version, it MUST respond
            // with the same version. Otherwise, the server MUST respond with
            // another protocol version it supports."
            //
            // `turbomcp-server` negotiates ahead of this and passes the result
            // in `config.protocol_version`, so this only decides the answer for
            // callers that route through core directly — the WASM/Worker entry
            // points, which previously told every client "2025-11-25" no matter
            // what it asked for, and then sent it 11-25-only fields.
            let protocol_version = config.protocol_version.unwrap_or_else(|| {
                params
                    .get("protocolVersion")
                    .and_then(|v| v.as_str())
                    .and_then(|requested| {
                        crate::SUPPORTED_VERSIONS
                            .iter()
                            .copied()
                            .find(|supported| *supported == requested)
                    })
                    // Unknown version: answer with one we do support, which is
                    // the spec's second branch. The client decides whether to
                    // proceed or disconnect.
                    .unwrap_or(PROTOCOL_VERSION)
            });
            let info = handler.server_info();
            let result = build_initialize_result(&info, handler, protocol_version);
            JsonRpcOutgoing::success(id, result)
        }

        // Handle both "initialized" and "notifications/initialized"
        "initialized" | "notifications/initialized" => {
            JsonRpcOutgoing::success(id, serde_json::json!({}))
        }

        // Tool methods
        "tools/list" => {
            let cursor = match cursor_param(request.params.as_ref()) {
                Ok(cursor) => cursor,
                Err(err) => return JsonRpcOutgoing::error(id, err),
            };
            match paginate(
                handler.list_tools_for(ctx),
                "tools",
                cursor,
                handler.page_size(),
            ) {
                Ok((tools, next_cursor)) => {
                    let mut result = serde_json::json!({ "tools": tools });
                    if let Some(next) = next_cursor {
                        result["nextCursor"] = serde_json::Value::String(next);
                    }
                    JsonRpcOutgoing::success(id, result)
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "tools/call" => {
            let params = request.params.unwrap_or_default();
            // `name` is schema-required. Defaulting it to "" turned a malformed
            // request into a lookup for the empty name, which then reported
            // "not found" — a different error, about a different thing.
            let Some(name) = params.get("name").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("tools/call requires a string 'name' parameter"),
                );
            };
            let args = params.get("arguments").cloned().unwrap_or_default();

            if let Err(err) = check_task_support(handler, name, params.get("task").is_some(), ctx) {
                return JsonRpcOutgoing::error(id, err);
            }

            match handler.call_tool(name, args, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(result_value) => JsonRpcOutgoing::success(id, result_value),
                    Err(e) => JsonRpcOutgoing::error(
                        id,
                        McpError::internal(alloc::format!(
                            "Failed to serialize tool result: {}",
                            e
                        )),
                    ),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Resource methods
        "resources/list" => {
            let cursor = match cursor_param(request.params.as_ref()) {
                Ok(cursor) => cursor,
                Err(err) => return JsonRpcOutgoing::error(id, err),
            };
            match paginate(
                handler.list_resources_for(ctx),
                "resources",
                cursor,
                handler.page_size(),
            ) {
                Ok((resources, next_cursor)) => {
                    let mut result = serde_json::json!({ "resources": resources });
                    if let Some(next) = next_cursor {
                        result["nextCursor"] = serde_json::Value::String(next);
                    }
                    JsonRpcOutgoing::success(id, result)
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "resources/templates/list" => {
            let cursor = match cursor_param(request.params.as_ref()) {
                Ok(cursor) => cursor,
                Err(err) => return JsonRpcOutgoing::error(id, err),
            };
            match paginate(
                handler.list_resource_templates_for(ctx),
                "resourceTemplates",
                cursor,
                handler.page_size(),
            ) {
                Ok((resource_templates, next_cursor)) => {
                    let mut result = serde_json::json!({ "resourceTemplates": resource_templates });
                    if let Some(next) = next_cursor {
                        result["nextCursor"] = serde_json::Value::String(next);
                    }
                    JsonRpcOutgoing::success(id, result)
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "resources/read" => {
            let params = request.params.unwrap_or_default();
            // Schema-required; see the note in the `tools/call` arm.
            let Some(uri) = params.get("uri").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("resources/read requires a string 'uri' parameter"),
                );
            };

            match handler.read_resource(uri, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(result_value) => JsonRpcOutgoing::success(id, result_value),
                    Err(e) => JsonRpcOutgoing::error(
                        id,
                        McpError::internal(alloc::format!(
                            "Failed to serialize resource result: {}",
                            e
                        )),
                    ),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Prompt methods
        "prompts/list" => {
            let cursor = match cursor_param(request.params.as_ref()) {
                Ok(cursor) => cursor,
                Err(err) => return JsonRpcOutgoing::error(id, err),
            };
            match paginate(
                handler.list_prompts_for(ctx),
                "prompts",
                cursor,
                handler.page_size(),
            ) {
                Ok((prompts, next_cursor)) => {
                    let mut result = serde_json::json!({ "prompts": prompts });
                    if let Some(next) = next_cursor {
                        result["nextCursor"] = serde_json::Value::String(next);
                    }
                    JsonRpcOutgoing::success(id, result)
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "prompts/get" => {
            let params = request.params.unwrap_or_default();
            // Schema-required; see the note in the `tools/call` arm.
            let Some(name) = params.get("name").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("prompts/get requires a string 'name' parameter"),
                );
            };
            let args = params.get("arguments").cloned();

            match handler.get_prompt(name, args, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(result_value) => JsonRpcOutgoing::success(id, result_value),
                    Err(e) => JsonRpcOutgoing::error(
                        id,
                        McpError::internal(alloc::format!(
                            "Failed to serialize prompt result: {}",
                            e
                        )),
                    ),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Task methods (SEP-1686)
        "tasks/list" => {
            let params = request.params.unwrap_or_default();
            let cursor = match cursor_param(Some(&params)) {
                Ok(cursor) => cursor,
                Err(err) => return JsonRpcOutgoing::error(id, err),
            };
            let limit = params
                .get("limit")
                .and_then(|v| v.as_u64())
                .map(|v| v as usize);

            match handler.list_tasks(cursor, limit, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(v) => JsonRpcOutgoing::success(id, v),
                    Err(e) => JsonRpcOutgoing::error(id, McpError::internal(e.to_string())),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "tasks/get" => {
            let params = request.params.unwrap_or_default();
            let Some(task_id) = params.get("taskId").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing taskId"));
            };

            match handler.get_task(task_id, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(v) => JsonRpcOutgoing::success(id, v),
                    Err(e) => JsonRpcOutgoing::error(id, McpError::internal(e.to_string())),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "tasks/cancel" => {
            let params = request.params.unwrap_or_default();
            let Some(task_id) = params.get("taskId").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing taskId"));
            };

            match handler.cancel_task(task_id, ctx).await {
                Ok(result) => match serde_json::to_value(&result) {
                    Ok(v) => JsonRpcOutgoing::success(id, v),
                    Err(e) => JsonRpcOutgoing::error(id, McpError::internal(e.to_string())),
                },
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "tasks/result" => {
            let params = request.params.unwrap_or_default();
            let Some(task_id) = params.get("taskId").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing taskId"));
            };

            match handler.get_task_result(task_id, ctx).await {
                Ok(result) => JsonRpcOutgoing::success(id, result),
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Resource subscriptions
        "resources/subscribe" => {
            let params = request.params.unwrap_or_default();
            let Some(uri) = params.get("uri").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing uri"));
            };
            match handler.subscribe(uri, ctx).await {
                Ok(()) => JsonRpcOutgoing::success(id, serde_json::json!({})),
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        "resources/unsubscribe" => {
            let params = request.params.unwrap_or_default();
            let Some(uri) = params.get("uri").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing uri"));
            };
            match handler.unsubscribe(uri, ctx).await {
                Ok(()) => JsonRpcOutgoing::success(id, serde_json::json!({})),
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Logging
        "logging/setLevel" => {
            // A server that did not declare `logging` does not implement this
            // method, whatever the params say.
            if handler.server_capabilities().logging.is_none() {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::capability_not_supported("logging/setLevel"),
                );
            }
            let params = request.params.unwrap_or_default();
            let Some(level) = params.get("level").and_then(|v| v.as_str()) else {
                return JsonRpcOutgoing::error(id, McpError::invalid_params("Missing level"));
            };
            // The eight RFC 5424 severities are a closed set in the schema, so
            // anything else is invalid params — not something to hand to a
            // user's handler, which would otherwise have to re-validate it or
            // silently store a level that means nothing.
            if !crate::LOG_LEVELS.contains(&level) {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params(alloc::format!(
                        "Invalid log level '{level}'; expected one of {}",
                        crate::LOG_LEVELS.join(", ")
                    )),
                );
            }
            match handler.set_log_level(level, ctx).await {
                Ok(()) => {
                    // Record it so `notifications/message` below this severity
                    // is suppressed for the rest of the session. Without this
                    // the level was accepted and then ignored, which is worse
                    // than refusing it: the client believes it is filtered.
                    #[cfg(feature = "std")]
                    ctx.set_min_log_level(level);
                    JsonRpcOutgoing::success(id, serde_json::json!({}))
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Completions
        "completion/complete" => {
            let params = request.params.unwrap_or_default();

            // Capability first, params second. A server that does not do
            // completions should answer "method not found" whatever the params
            // look like — validating them first would imply the method exists
            // and merely got bad input.
            if handler.server_capabilities().completions.is_none() {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::capability_not_supported("completion/complete"),
                );
            }

            // `ref` and `argument` are both schema-required, and `argument`
            // requires `name` and `value`. Validating here means every
            // `#[completion]` handler can index the shape it was promised
            // instead of re-checking it, and a malformed request is answered
            // as invalid params rather than reaching user code.
            let Some(reference) = params.get("ref") else {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params("completion/complete requires a 'ref' parameter"),
                );
            };
            match reference.get("type").and_then(|v| v.as_str()) {
                Some("ref/prompt") => {
                    if reference.get("name").and_then(|v| v.as_str()).is_none() {
                        return JsonRpcOutgoing::error(
                            id,
                            McpError::invalid_params("ref/prompt requires a string 'name'"),
                        );
                    }
                }
                Some("ref/resource") => {
                    if reference.get("uri").and_then(|v| v.as_str()).is_none() {
                        return JsonRpcOutgoing::error(
                            id,
                            McpError::invalid_params("ref/resource requires a string 'uri'"),
                        );
                    }
                }
                other => {
                    return JsonRpcOutgoing::error(
                        id,
                        McpError::invalid_params(alloc::format!(
                            "unsupported completion ref type {:?}; expected \
                             'ref/prompt' or 'ref/resource'",
                            other.unwrap_or("<missing>")
                        )),
                    );
                }
            }
            let argument_ok = params.get("argument").is_some_and(|argument| {
                argument.get("name").and_then(|v| v.as_str()).is_some()
                    && argument.get("value").and_then(|v| v.as_str()).is_some()
            });
            if !argument_ok {
                return JsonRpcOutgoing::error(
                    id,
                    McpError::invalid_params(
                        "completion/complete requires 'argument' with string 'name' and 'value'",
                    ),
                );
            }

            match handler.complete(params, ctx).await {
                Ok(mut value) => {
                    cap_completion_values(&mut value);
                    JsonRpcOutgoing::success(id, value)
                }
                Err(err) => JsonRpcOutgoing::error(id, err),
            }
        }

        // Ping
        "ping" => JsonRpcOutgoing::success(id, serde_json::json!({})),

        // Unknown method
        _ => JsonRpcOutgoing::error(id, McpError::method_not_found(&request.method)),
    }
}

/// Hold a completion result to the spec's 100-value ceiling.
///
/// "Maximum 100 items per response" is a property of the wire, not of any one
/// handler, so it is enforced here rather than left to every `#[completion]`
/// body to remember. Truncating sets `hasMore`, which is exactly what that flag
/// is for; `total` is left alone, since a handler that reported one was telling
/// the truth about how many matches exist.
fn cap_completion_values(value: &mut Value) {
    const MAX_COMPLETION_VALUES: usize = 100;

    let Some(completion) = value.get_mut("completion") else {
        return;
    };
    let Some(values) = completion.get_mut("values").and_then(Value::as_array_mut) else {
        return;
    };
    if values.len() <= MAX_COMPLETION_VALUES {
        return;
    }

    values.truncate(MAX_COMPLETION_VALUES);
    if let Some(object) = completion.as_object_mut() {
        object.insert("hasMore".into(), Value::Bool(true));
    }
}

/// Build the initialize result with server info and capabilities.
///
/// # MCP Spec Compliance
///
/// The capabilities object follows the MCP 2025-11-25 specification:
/// - Each capability is an object (not boolean)
/// - Capabilities are only included if the server supports them
/// - Sub-properties like `listChanged` indicate notification support
fn build_initialize_result<H: McpHandler>(
    info: &ServerInfo,
    handler: &H,
    protocol_version: &str,
) -> Value {
    let capabilities = match serde_json::to_value(handler.server_capabilities()) {
        Ok(Value::Object(map)) => map,
        Ok(_) | Err(_) => serde_json::Map::new(),
    };

    // Preserve the full ServerInfo payload so initialize responses stay aligned
    // with the shared MCP type definitions as metadata fields evolve.
    let server_info = match serde_json::to_value(info) {
        Ok(Value::Object(map)) => map,
        Ok(_) | Err(_) => {
            let mut fallback = serde_json::Map::new();
            fallback.insert("name".to_string(), serde_json::json!(info.name));
            fallback.insert("version".to_string(), serde_json::json!(info.version));
            fallback
        }
    };

    // Build final result
    let mut result = serde_json::Map::new();
    result.insert(
        "protocolVersion".to_string(),
        serde_json::json!(protocol_version),
    );
    result.insert("capabilities".to_string(), Value::Object(capabilities));
    result.insert("serverInfo".to_string(), Value::Object(server_info));

    // Optional per the schema: emit it only when the server supplies one, so
    // clients can distinguish "no guidance" from "empty guidance".
    if let Some(instructions) = handler.instructions() {
        result.insert("instructions".to_string(), Value::String(instructions));
    }

    Value::Object(result)
}

/// Parse a JSON string into a JSON-RPC incoming request.
///
/// This is a convenience function for parsing incoming messages.
pub fn parse_request(input: &str) -> Result<JsonRpcIncoming, McpError> {
    let value: serde_json::Value =
        serde_json::from_str(input).map_err(|e| McpError::parse_error(e.to_string()))?;
    parse_request_from_value(value)
}

/// Parse a pre-parsed `serde_json::Value` into a JSON-RPC incoming request.
/// Avoids the second JSON parse on the line transports' hot path: callers can
/// parse once into `Value` (to detect server-to-client responses), then use this
/// to convert into the typed request without re-parsing the source string.
pub fn parse_request_from_value(value: serde_json::Value) -> Result<JsonRpcIncoming, McpError> {
    let request: JsonRpcIncoming =
        serde_json::from_value(value).map_err(|e| McpError::invalid_request(e.to_string()))?;
    if !request.is_valid_version() {
        return Err(McpError::invalid_request(
            "jsonrpc field must be exactly \"2.0\"",
        ));
    }
    Ok(request)
}

/// Serialize a JSON-RPC outgoing response to a string.
///
/// This is a convenience function for serializing outgoing messages.
pub fn serialize_response(response: &JsonRpcOutgoing) -> Result<alloc::string::String, McpError> {
    response
        .to_json()
        .map_err(|e| McpError::internal(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::{ErrorKind, McpResult};
    use crate::marker::MaybeSend;
    use core::future::Future;
    use std::collections::HashMap;
    use turbomcp_types::{
        Prompt, PromptResult, Resource, ResourceResult, ResourceTemplate, ServerCapabilities,
        ServerTasksCapabilities, ServerTasksRequestsCapabilities, TasksCancelCapabilities,
        TasksListCapabilities, TasksToolsCallCapabilities, TasksToolsCapabilities, Tool,
        ToolResult,
    };

    #[derive(Clone)]
    struct TestHandler;

    impl McpHandler for TestHandler {
        fn server_info(&self) -> ServerInfo {
            ServerInfo::new("test-router", "1.0.0")
        }

        fn list_tools(&self) -> Vec<Tool> {
            vec![Tool::new("greet", "Say hello")]
        }

        fn list_resources(&self) -> Vec<Resource> {
            vec![]
        }

        fn list_prompts(&self) -> Vec<Prompt> {
            vec![]
        }

        fn call_tool<'a>(
            &'a self,
            name: &'a str,
            args: Value,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a {
            let name = name.to_string();
            async move {
                match name.as_str() {
                    "greet" => {
                        let who = args.get("name").and_then(|v| v.as_str()).unwrap_or("World");
                        Ok(ToolResult::text(alloc::format!("Hello, {}!", who)))
                    }
                    _ => Err(McpError::tool_not_found(&name)),
                }
            }
        }

        fn read_resource<'a>(
            &'a self,
            uri: &'a str,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a {
            let uri = uri.to_string();
            async move { Err(McpError::resource_not_found(&uri)) }
        }

        fn get_prompt<'a>(
            &'a self,
            name: &'a str,
            _args: Option<Value>,
            _ctx: &'a RequestContext,
        ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a {
            let name = name.to_string();
            async move { Err(McpError::prompt_not_found(&name)) }
        }
    }

    #[test]
    fn test_parse_request() {
        let input = r#"{"jsonrpc": "2.0", "id": 1, "method": "ping"}"#;
        let request = parse_request(input).unwrap();
        assert_eq!(request.method, "ping");
        assert_eq!(request.id, Some(serde_json::json!(1)));
    }

    #[test]
    fn test_parse_request_rejects_invalid_jsonrpc_version() {
        let input = r#"{"jsonrpc": "1.0", "id": 1, "method": "ping"}"#;
        let error = parse_request(input).unwrap_err();
        assert_eq!(error.kind, ErrorKind::InvalidRequest);
    }

    #[test]
    fn test_parse_request_rejects_invalid_id_as_invalid_request() {
        let input = r#"{"jsonrpc": "2.0", "id": null, "method": "ping"}"#;
        let error = parse_request(input).unwrap_err();
        assert_eq!(error.kind, ErrorKind::InvalidRequest);
    }

    #[test]
    fn test_serialize_response() {
        let response = JsonRpcOutgoing::success(Some(serde_json::json!(1)), serde_json::json!({}));
        let serialized = serialize_response(&response).unwrap();
        assert!(serialized.contains("\"jsonrpc\":\"2.0\""));
        assert!(serialized.contains("\"id\":1"));
    }

    #[tokio::test]
    async fn test_route_initialize() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25",
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                },
                "capabilities": {}
            })),
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.result.is_some());
        assert!(response.error.is_none());

        let result = response.result.unwrap();
        assert_eq!(result["serverInfo"]["name"], "test-router");
        assert!(result["capabilities"]["tools"].is_object());
        assert_eq!(result["capabilities"]["tools"]["listChanged"], true);
    }

    #[tokio::test]
    async fn test_route_initialize_preserves_server_info_metadata() {
        #[derive(Clone)]
        struct MetadataHandler;

        #[allow(clippy::manual_async_fn)]
        impl McpHandler for MetadataHandler {
            fn server_info(&self) -> ServerInfo {
                ServerInfo::new("test-router", "1.0.0")
                    .with_title("Test Router")
                    .with_description("Initialize metadata should survive serialization")
                    .with_website_url("https://example.com")
                    .with_icon(
                        turbomcp_types::Icon::new("https://example.com/icon.png")
                            .with_mime_type("image/png"),
                    )
            }

            fn list_tools(&self) -> Vec<Tool> {
                vec![]
            }

            fn list_resources(&self) -> Vec<Resource> {
                vec![]
            }

            fn list_prompts(&self) -> Vec<Prompt> {
                vec![]
            }

            fn call_tool<'a>(
                &'a self,
                _name: &'a str,
                _args: Value,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a {
                async move { unreachable!("tool calls are not used in this test") }
            }

            fn read_resource<'a>(
                &'a self,
                _uri: &'a str,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a {
                async move { unreachable!("resource reads are not used in this test") }
            }

            fn get_prompt<'a>(
                &'a self,
                _name: &'a str,
                _args: Option<Value>,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a {
                async move { unreachable!("prompt reads are not used in this test") }
            }
        }

        let handler = MetadataHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25",
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                },
                "capabilities": {}
            })),
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        let result = response.result.expect("initialize should succeed");
        assert_eq!(result["serverInfo"]["title"], "Test Router");
        assert_eq!(
            result["serverInfo"]["description"],
            "Initialize metadata should survive serialization"
        );
        assert_eq!(result["serverInfo"]["websiteUrl"], "https://example.com");
        assert_eq!(
            result["serverInfo"]["icons"][0]["src"],
            "https://example.com/icon.png"
        );
    }

    /// On a server declaring task-augmented `tools/call`, `taskSupport` is
    /// binding: `required` without `task` MUST be -32601, and `task` on a
    /// `forbidden` or unmarked tool SHOULD be. Without the capability, `task`
    /// is ignored and the call runs normally.
    #[tokio::test]
    async fn test_task_support_is_enforced_only_where_declared() {
        #[derive(Clone)]
        struct TaskServer {
            declares: bool,
        }

        #[allow(clippy::manual_async_fn)]
        impl McpHandler for TaskServer {
            fn server_info(&self) -> ServerInfo {
                ServerInfo::new("tasks", "1.0.0")
            }

            fn server_capabilities(&self) -> ServerCapabilities {
                ServerCapabilities {
                    tasks: self.declares.then(|| ServerTasksCapabilities {
                        requests: Some(ServerTasksRequestsCapabilities {
                            tools: Some(TasksToolsCapabilities {
                                call: Some(TasksToolsCallCapabilities {}),
                            }),
                        }),
                        ..Default::default()
                    }),
                    ..Default::default()
                }
            }

            fn list_tools(&self) -> Vec<Tool> {
                let with = |name: &str, support| {
                    let mut tool = Tool::new(name, name);
                    tool.execution = Some(turbomcp_types::ToolExecution {
                        task_support: Some(support),
                    });
                    tool
                };
                vec![
                    with("slow", turbomcp_types::TaskSupportLevel::Required),
                    with("quick", turbomcp_types::TaskSupportLevel::Forbidden),
                ]
            }

            fn list_resources(&self) -> Vec<Resource> {
                vec![]
            }

            fn list_prompts(&self) -> Vec<Prompt> {
                vec![]
            }

            fn call_tool<'a>(
                &'a self,
                _name: &'a str,
                _args: Value,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a {
                async move { Ok(ToolResult::text("ran")) }
            }

            fn read_resource<'a>(
                &'a self,
                uri: &'a str,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a {
                async move { Err(McpError::resource_not_found(uri)) }
            }

            fn get_prompt<'a>(
                &'a self,
                name: &'a str,
                _args: Option<Value>,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a {
                async move { Err(McpError::prompt_not_found(name)) }
            }
        }

        let call = |handler: TaskServer, tool: &'static str, task: bool| async move {
            let mut params = serde_json::json!({ "name": tool, "arguments": {} });
            if task {
                params["task"] = serde_json::json!({ "ttl": 1000 });
            }
            let request = JsonRpcIncoming {
                jsonrpc: "2.0".to_string(),
                id: Some(serde_json::json!(1)),
                method: "tools/call".to_string(),
                params: Some(params),
            };
            route_request(
                &handler,
                request,
                &RequestContext::stdio(),
                &RouteConfig::default(),
            )
            .await
        };
        let code = |response: JsonRpcOutgoing| response.error.map(|e| e.code);

        let declaring = TaskServer { declares: true };
        assert_eq!(
            code(call(declaring.clone(), "slow", false).await),
            Some(-32601)
        );
        assert_eq!(
            code(call(declaring.clone(), "quick", true).await),
            Some(-32601)
        );
        assert_eq!(code(call(declaring, "quick", false).await), None);

        let plain = TaskServer { declares: false };
        assert_eq!(code(call(plain.clone(), "slow", false).await), None);
        assert_eq!(code(call(plain, "quick", true).await), None);
    }

    #[tokio::test]
    async fn test_route_initialize_uses_handler_capabilities() {
        #[derive(Clone)]
        struct CapabilityHandler;

        #[allow(clippy::manual_async_fn)]
        impl McpHandler for CapabilityHandler {
            fn server_info(&self) -> ServerInfo {
                ServerInfo::new("capability-router", "1.0.0")
            }

            fn server_capabilities(&self) -> ServerCapabilities {
                ServerCapabilities {
                    tasks: Some(ServerTasksCapabilities {
                        list: Some(TasksListCapabilities {}),
                        cancel: Some(TasksCancelCapabilities {}),
                        requests: Some(ServerTasksRequestsCapabilities {
                            tools: Some(TasksToolsCapabilities {
                                call: Some(TasksToolsCallCapabilities {}),
                            }),
                        }),
                    }),
                    extensions: Some(HashMap::from([(
                        "trace".to_string(),
                        serde_json::json!({"version": "1"}),
                    )])),
                    ..Default::default()
                }
            }

            fn list_tools(&self) -> Vec<Tool> {
                vec![]
            }

            fn list_resources(&self) -> Vec<Resource> {
                vec![]
            }

            fn list_prompts(&self) -> Vec<Prompt> {
                vec![]
            }

            fn call_tool<'a>(
                &'a self,
                _name: &'a str,
                _args: Value,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ToolResult>> + MaybeSend + 'a {
                async move { unreachable!("tool calls are not used in this test") }
            }

            fn read_resource<'a>(
                &'a self,
                _uri: &'a str,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<ResourceResult>> + MaybeSend + 'a {
                async move { unreachable!("resource reads are not used in this test") }
            }

            fn get_prompt<'a>(
                &'a self,
                _name: &'a str,
                _args: Option<Value>,
                _ctx: &'a RequestContext,
            ) -> impl Future<Output = McpResult<PromptResult>> + MaybeSend + 'a {
                async move { unreachable!("prompt reads are not used in this test") }
            }
        }

        let handler = CapabilityHandler;
        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "DRAFT-2026-v1",
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                },
                "capabilities": {}
            })),
        };

        let response = route_request(&handler, request, &ctx, &RouteConfig::default()).await;
        let result = response.result.expect("initialize should succeed");
        assert!(result["capabilities"]["tasks"]["requests"]["tools"]["call"].is_object());
        assert_eq!(
            result["capabilities"]["extensions"]["trace"]["version"],
            "1"
        );
    }

    #[tokio::test]
    async fn test_route_initialize_missing_client_info() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25"
            })),
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.error.is_some());
        let error = response.error.unwrap();
        assert_eq!(error.code, -32602); // INVALID_PARAMS
    }

    #[tokio::test]
    async fn test_route_tools_list() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "tools/list".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.result.is_some());

        let result = response.result.unwrap();
        let tools = result["tools"].as_array().unwrap();
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["name"], "greet");
    }

    #[tokio::test]
    async fn test_route_resource_templates_list() {
        #[derive(Clone)]
        struct TemplateHandler;

        impl McpHandler for TemplateHandler {
            fn server_info(&self) -> ServerInfo {
                ServerInfo::new("template-router", "1.0.0")
            }

            fn list_tools(&self) -> Vec<Tool> {
                vec![]
            }

            fn list_resources(&self) -> Vec<Resource> {
                vec![]
            }

            fn list_resource_templates(&self) -> Vec<ResourceTemplate> {
                vec![ResourceTemplate::new("file://{path}", "file")]
            }

            fn list_prompts(&self) -> Vec<Prompt> {
                vec![]
            }

            async fn call_tool<'a>(
                &'a self,
                _name: &'a str,
                _args: Value,
                _ctx: &'a RequestContext,
            ) -> McpResult<ToolResult> {
                unreachable!("tool calls are not used in this test")
            }

            async fn read_resource<'a>(
                &'a self,
                _uri: &'a str,
                _ctx: &'a RequestContext,
            ) -> McpResult<ResourceResult> {
                unreachable!("resource reads are not used in this test")
            }

            async fn get_prompt<'a>(
                &'a self,
                _name: &'a str,
                _args: Option<Value>,
                _ctx: &'a RequestContext,
            ) -> McpResult<PromptResult> {
                unreachable!("prompt reads are not used in this test")
            }
        }

        let ctx = RequestContext::stdio();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "resources/templates/list".to_string(),
            params: None,
        };

        let response =
            route_request(&TemplateHandler, request, &ctx, &RouteConfig::default()).await;
        assert!(response.error.is_none());
        let result = response.result.expect("resource templates result");
        let templates = result["resourceTemplates"].as_array().unwrap();
        assert_eq!(templates.len(), 1);
        assert_eq!(templates[0]["uriTemplate"], "file://{path}");
        assert_eq!(templates[0]["name"], "file");
    }

    #[tokio::test]
    async fn test_route_tools_call() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "tools/call".to_string(),
            params: Some(serde_json::json!({
                "name": "greet",
                "arguments": {"name": "Alice"}
            })),
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.result.is_some());
        assert!(response.error.is_none());
    }

    #[tokio::test]
    async fn test_route_ping() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "ping".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.result.is_some());
        assert!(response.error.is_none());
    }

    #[tokio::test]
    async fn test_route_notification() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: None,
            method: "notifications/initialized".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(!response.should_send());
    }

    #[tokio::test]
    async fn test_route_request_method_without_id_is_not_sent() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: None,
            method: "tools/list".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(!response.should_send());
    }

    #[tokio::test]
    async fn test_route_unknown_method() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig::default();
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "unknown/method".to_string(),
            params: None,
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        assert!(response.error.is_some());
        let error = response.error.unwrap();
        assert_eq!(error.code, -32601); // METHOD_NOT_FOUND
    }

    #[tokio::test]
    async fn test_route_with_custom_protocol_version() {
        let handler = TestHandler;
        let ctx = RequestContext::stdio();
        let config = RouteConfig {
            protocol_version: Some("2025-11-25"),
        };
        let request = JsonRpcIncoming {
            jsonrpc: "2.0".to_string(),
            id: Some(serde_json::json!(1)),
            method: "initialize".to_string(),
            params: Some(serde_json::json!({
                "protocolVersion": "2025-11-25",
                "clientInfo": {
                    "name": "test-client",
                    "version": "1.0.0"
                }
            })),
        };

        let response = route_request(&handler, request, &ctx, &config).await;
        let result = response.result.unwrap();
        assert_eq!(result["protocolVersion"], "2025-11-25");
    }
}