1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
//! Represents an MCP application
use self::{
context::{Context, ServerRuntime},
options::{McpOptions, RuntimeMcpOptions},
};
use crate::app::handler::{
CompletionHandler, FromHandlerParams, GenericHandler, HandlerParams, ListResourcesHandler,
RequestFunc, RequestHandler,
};
use crate::error::{Error, ErrorCode};
use crate::middleware::{MwContext, Next, make_fn::make_mw};
use crate::shared;
use crate::transport::{Receiver, Sender, Transport};
use crate::types::{
CallToolRequestParams, CallToolResponse, CompleteResult, GetPromptRequestParams,
GetPromptResult, IntoResponse, ListPromptsRequestParams, ListPromptsResult,
ListResourceTemplatesRequestParams, ListResourceTemplatesResult, ListResourcesRequestParams,
ListResourcesResult, ListToolsRequestParams, ListToolsResult, Message, MessageBatch,
MessageEnvelope, Prompt, PromptHandler, ReadResourceRequestParams, ReadResourceResult, Request,
Resource, ResourceTemplate, Response, Tool, ToolHandler, Uri,
notification::{CancelledNotificationParams, Notification},
resource::template::ResourceFunc,
};
// Subscribe/unsubscribe handlers exist only under the non-RC transport, which
// can push `notifications/resources/updated`; the RC stateless build masks the
// capability and skips the handlers, so these params are unused there.
#[cfg(not(feature = "proto-2026-07-28-rc"))]
use crate::types::{InitializeRequestParams, InitializeResult};
#[cfg(not(feature = "proto-2026-07-28-rc"))]
use crate::types::{SubscribeRequestParams, UnsubscribeRequestParams};
use tokio_util::sync::CancellationToken;
#[cfg(feature = "tasks")]
use crate::types::{
CancelTaskRequestParams, GetTaskPayloadRequestParams, GetTaskRequestParams,
ListTasksRequestParams, ListTasksResult, Task, TaskPayload, cursor::Pagination,
};
#[cfg(feature = "tasks")]
use context::ToolOrTaskResponse;
use std::{
collections::HashMap,
fmt::{Debug, Formatter},
sync::Arc,
};
#[cfg(all(feature = "tracing", not(feature = "proto-2026-07-28-rc")))]
use crate::types::notification::SetLevelRequestParams;
#[cfg(feature = "tracing")]
use tracing::Instrument;
#[cfg(feature = "di")]
use volga_di::{Container, ContainerBuilder};
mod collection;
pub mod context;
#[cfg(feature = "proto-2026-07-28-rc")]
pub mod extension;
mod greeter;
pub(crate) mod handler;
#[cfg(feature = "proto-2026-07-28-rc")]
pub mod mrtr_store;
pub mod options;
const DEFAULT_PAGE_SIZE: usize = 10;
type RequestHandlers = HashMap<String, RequestHandler<Response>>;
/// Represents an MCP server application
pub struct App {
/// Whether to print the startup greeting banner
greeting: bool,
/// MCP server options
pub(super) options: McpOptions,
/// DI container
#[cfg(feature = "di")]
pub(super) container: ContainerBuilder,
/// MCP server request handlers
handlers: RequestHandlers,
}
impl Debug for App {
#[inline]
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str("App { ... }")
}
}
impl Default for App {
/// Creates a default [`App`] with all built-in handlers registered.
fn default() -> Self {
Self::new()
}
}
impl App {
/// Initializes a new MCP app
pub fn new() -> Self {
let mut app = Self {
greeting: cfg!(debug_assertions),
options: McpOptions::default(),
handlers: HashMap::new(),
#[cfg(feature = "di")]
container: ContainerBuilder::new(),
};
#[cfg(not(feature = "proto-2026-07-28-rc"))]
app.map_handler(crate::commands::INIT, Self::init);
#[cfg(feature = "proto-2026-07-28-rc")]
app.map_handler(crate::commands::DISCOVER, Self::discover);
app.map_handler(
crate::types::completion::commands::COMPLETE,
Self::completion,
);
app.map_handler(crate::types::tool::commands::LIST, Self::tools);
app.map_handler(crate::types::tool::commands::CALL, Self::tool);
app.map_handler(crate::types::resource::commands::LIST, Self::resources);
app.map_handler(
crate::types::resource::commands::TEMPLATES_LIST,
Self::resource_templates,
);
app.map_handler(crate::types::resource::commands::READ, Self::resource);
// The stateless `proto-2026-07-28-rc` transport cannot push
// `notifications/resources/updated`, so the `resources.subscribe`
// capability is masked off (see `McpOptions::resources_capability`).
// Don't register subscribe/unsubscribe handlers under RC either, so the
// advertised surface and the accepted methods stay in sync — the server
// won't accept a subscription it never announces.
#[cfg(not(feature = "proto-2026-07-28-rc"))]
{
app.map_handler(
crate::types::resource::commands::SUBSCRIBE,
Self::resource_subscribe,
);
app.map_handler(
crate::types::resource::commands::UNSUBSCRIBE,
Self::resource_unsubscribe,
);
}
app.map_handler(crate::types::prompt::commands::LIST, Self::prompts);
app.map_handler(crate::types::prompt::commands::GET, Self::prompt);
#[cfg(feature = "tasks")]
{
app.map_handler(crate::types::task::commands::LIST, Self::tasks);
app.map_handler(crate::types::task::commands::GET, Self::task);
app.map_handler(crate::types::task::commands::CANCEL, Self::cancel_task);
app.map_handler(crate::types::task::commands::RESULT, Self::task_result);
}
app.map_handler(crate::commands::PING, Self::ping);
#[cfg(all(feature = "tracing", not(feature = "proto-2026-07-28-rc")))]
app.map_handler(
crate::types::notification::commands::SET_LOG_LEVEL,
Self::set_log_level,
);
app
}
/// Starts the [`App`] with its own Tokio runtime.
///
/// This method is intended for simple use cases where you don't already have a Tokio runtime setup.
/// Internally, it creates and runs a multi-threaded Tokio runtime to execute the application.
///
/// **Note:** This method **must not** be called from within an existing Tokio runtime
/// (e.g., inside an `#[tokio::main]` async function), or it will panic.
/// If you are already using Tokio in your application, use [`App::run`] instead.
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # fn main() {
/// let mut app = App::new();
///
/// // configure tools, resources, prompts
///
/// app.run_blocking()
/// # }
/// ```
pub fn run_blocking(self) {
if tokio::runtime::Handle::try_current().is_ok() {
panic!(
"`App::run_blocking()` cannot be called inside an existing Tokio runtime. Use `run().await` instead."
);
}
let runtime = match tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
{
Ok(rt) => rt,
Err(err) => {
#[cfg(feature = "tracing")]
tracing::error!("failed to start the runtime: {err:#}");
#[cfg(not(feature = "tracing"))]
eprintln!("failed to start the runtime: {err:#}");
return;
}
};
runtime.block_on(async { self.run().await });
}
/// Run the MCP server
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// // configure tools, resources, prompts
///
/// app.run().await;
/// # }
/// ```
pub async fn run(mut self) {
#[cfg(feature = "macros")]
self.register_methods();
// ORDERING CONSTRAINT: must execute after register_methods() so macro-registered
// tools/prompts are present; must execute before self.options.transport() consumes
// `proto` and before ServerRuntime::new() transitions collections to Runtime state
// (Collection::as_ref() panics if called in Runtime state).
if self.greeting {
let transport_label = self.options.transport_label();
let tools: Vec<String> = self.options.tools.as_ref().keys().cloned().collect();
let prompts: Vec<String> = self.options.prompts.as_ref().keys().cloned().collect();
let resource_templates: Vec<String> = self
.options
.resources_templates
.as_ref()
.keys()
.cloned()
.collect();
greeter::Greeter {
server_name: &self.options.implementation.name,
server_version: &self.options.implementation.version,
neva_version: env!("CARGO_PKG_VERSION"),
transport_label: &transport_label,
tools: &tools,
prompts: &prompts,
resource_templates: &resource_templates,
use_color: std::env::var_os("NO_COLOR").is_none(),
}
.print();
}
// Multi-instance footgun guard: under the stateless RC HTTP transport an
// MRTR retry can land on a different instance than the one that issued
// the `requestState`. With the default ephemeral per-process secret that
// retry fails `requestState` decryption/verification, which is a silent
// prod failure. Warn at startup unless a shared secret was set explicitly.
#[cfg(all(
feature = "proto-2026-07-28-rc",
feature = "http-server",
feature = "tracing"
))]
if self.options.is_http_transport() && !self.options.request_state_secret_is_explicit() {
tracing::warn!(
"MRTR requestState is encrypted with an ephemeral per-process key. \
Multi-instance HTTP deployments MUST call \
App::with_request_state_secret(...) with a shared secret, or a \
retry routed to another instance will fail requestState \
verification."
);
}
#[cfg(feature = "tracing")]
self.options
.add_middleware(make_mw(Self::tracing_middleware));
self.options
.add_middleware(make_mw(Self::message_middleware));
let mut transport = self.options.transport();
let cancellation_token = transport.start();
self.wait_for_shutdown_signal(cancellation_token.clone());
let (sender, mut receiver) = transport.split();
let runtime = ServerRuntime::new(
sender,
self.options,
self.handlers,
#[cfg(feature = "di")]
self.container.build(),
);
loop {
tokio::select! {
biased;
_ = cancellation_token.cancelled() => break,
msg = receiver.recv() => {
match msg {
Ok(msg) => match msg {
Message::Batch(batch) => {
tokio::spawn(Self::execute_batch(batch, runtime.clone()));
},
msg => {
tokio::spawn(Self::execute(msg, runtime.clone()));
}
},
Err(_err) => {
#[cfg(feature = "tracing")]
tracing::error!("Error handling message: {:?}", _err);
break;
}
}
}
}
}
}
/// Sets the shared secret used to encrypt and authenticate MRTR
/// `requestState` (`proto-2026-07-28-rc`).
///
/// The blob is sealed with ChaCha20-Poly1305 (AEAD) using a key derived from
/// this secret, so the payload — including any values a handler caches via
/// [`Context::memo`](crate::Context::memo) — is confidential as well as
/// tamper-evident.
///
/// **Multi-instance stateless deployments MUST set this to a shared
/// secret** — otherwise a retry that lands on a different instance fails to
/// decrypt the `requestState`. If unset, an ephemeral per-process key is
/// used (fine for single-instance / development).
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "proto-2026-07-28-rc")] {
/// use neva::App;
///
/// let app = App::new()
/// .with_request_state_secret(b"shared-secret");
/// # }
/// ```
#[cfg(feature = "proto-2026-07-28-rc")]
pub fn with_request_state_secret(mut self, secret: impl AsRef<[u8]>) -> Self {
self.options.set_request_state_secret(secret.as_ref());
self
}
/// Sets the maximum encoded `requestState` size (bytes). When a round-trip
/// would emit a larger blob, the server returns an error result instead
/// (`proto-2026-07-28-rc`).
///
/// Defaults to 8 KiB. Lower it to push handlers toward [`crate::Context::once`]
/// (key-only) over [`crate::Context::memo`] (serialized value); raise it for
/// memo-heavy flows.
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "proto-2026-07-28-rc")] {
/// use neva::App;
///
/// let app = App::new()
/// .with_max_state_bytes(16 * 1024);
/// # }
/// ```
#[cfg(feature = "proto-2026-07-28-rc")]
pub fn with_max_state_bytes(mut self, bytes: usize) -> Self {
self.options.set_max_state_bytes(bytes);
self
}
/// Sets the store backing MRTR final-round idempotency
/// (`proto-2026-07-28-rc`).
///
/// When the final round of an MRTR flow commits but its HTTP response is
/// lost, the client retries the same `requestState`; the store lets the
/// server return the already-computed response instead of re-running the
/// handler (and its [`Context::on_commit`](crate::Context::on_commit) /
/// [`Context::once`](crate::Context::once) side effects) a second time.
///
/// Defaults to a per-process
/// [`InMemoryStateStore`](crate::app::mrtr_store::InMemoryStateStore).
/// **Multi-instance stateless deployments should set a shared store** (e.g.
/// Redis) so a retry routed to another instance still sees the committed
/// result — the same constraint as
/// [`with_request_state_secret`](Self::with_request_state_secret).
///
/// # Example
/// ```no_run
/// # #[cfg(feature = "proto-2026-07-28-rc")] {
/// use neva::App;
/// use neva::app::mrtr_store::InMemoryStateStore;
///
/// let app = App::new()
/// .with_request_state_store(InMemoryStateStore::new());
/// # }
/// ```
#[cfg(feature = "proto-2026-07-28-rc")]
pub fn with_request_state_store(
mut self,
store: impl crate::app::mrtr_store::RequestStateStore + 'static,
) -> Self {
self.options
.set_request_state_store(std::sync::Arc::new(store));
self
}
/// Registers a protocol [`Extension`](crate::app::extension::Extension)
/// (MCP 2026-07-28 RC).
///
/// Records the extension's capability under its reverse-DNS id (surfaced by
/// `server/discover` under `capabilities.extensions`) and lets it register
/// its request handlers. This is the generic entry point for extensions;
/// the built-in Tasks extension is also reachable through `with_tasks`.
///
/// # Example
/// ```no_run
/// # #[cfg(all(feature = "proto-2026-07-28-rc", feature = "tasks"))] {
/// use neva::App;
/// use neva::app::extension::TasksExtension;
/// use neva::types::ServerTasksCapability;
/// let app = App::new()
/// .with_extension(TasksExtension::new(ServerTasksCapability::default()));
/// # }
/// ```
#[cfg(feature = "proto-2026-07-28-rc")]
pub fn with_extension<E: crate::app::extension::Extension>(mut self, ext: E) -> Self {
self.options.register_extension(ext.id(), ext.capability());
ext.register(&mut self);
self
}
/// Enable the greeting banner on startup (forced on, even in release builds).
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # fn main() {
/// let app = App::new().with_greeting();
/// # }
/// ```
pub fn with_greeting(mut self) -> Self {
self.greeting = true;
self
}
/// Suppress the greeting banner on startup.
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # fn main() {
/// let app = App::new().without_greeting();
/// # }
/// ```
pub fn without_greeting(mut self) -> Self {
self.greeting = false;
self
}
/// Configure MCP server options
pub fn with_options<F>(mut self, config: F) -> Self
where
F: FnOnce(McpOptions) -> McpOptions,
{
self.options = config(self.options);
self
}
/// Maps an MCP client request to a specific function
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_handler("ping", || async {
/// "pong"
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_handler<F, R, Args>(&mut self, name: impl Into<String>, handler: F) -> &mut Self
where
F: GenericHandler<Args, Output = R>,
R: IntoResponse + Send + 'static,
Args: FromHandlerParams + Send + Sync + 'static,
{
let handler = RequestFunc::new(handler);
self.handlers.insert(name.into(), handler);
self
}
/// Maps an MCP tool call request to a specific function and returns a mutable reference to the
/// [`Tool`] for further configuration
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_tool("hello", |name: String| async move {
/// format!("Hello, {name}")
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_tool<F, R, Args>(&mut self, name: impl Into<String>, handler: F) -> &mut Tool
where
F: ToolHandler<Args, Output = R>,
R: Into<CallToolResponse> + Send + 'static,
Args: TryFrom<CallToolRequestParams, Error = Error> + Send + Sync + 'static,
{
self.options.add_tool(Tool::new(name, handler))
}
/// Adds a known resource
pub fn add_resource<U: Into<Uri>, S: Into<String>>(
&mut self,
uri: U,
name: S,
) -> &mut Resource {
let resource = Resource::new(uri, name);
self.options.add_resource(resource)
}
/// Maps an MCP resource read request to a specific function
///
/// # Example
/// ```no_run
/// use neva::App;
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_resource("res://{name}", "read_resource", |name: String| async move {
/// (format!("res://{name}"), format!("Resource: {name} content"))
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_resource<F, R, Args>(
&mut self,
uri: impl Into<Uri>,
name: impl Into<String>,
handler: F,
) -> &mut ResourceTemplate
where
F: GenericHandler<Args, Output = R>,
R: TryInto<ReadResourceResult> + Send + 'static,
R::Error: Into<Error>,
Args: TryFrom<ReadResourceRequestParams, Error = Error> + Send + Sync + 'static,
{
let handler = ResourceFunc::new(handler);
let template = ResourceTemplate::new(uri, name);
self.options.add_resource_template(template, handler)
}
/// Maps an MCP get a prompt request to a specific function
///
/// # Example
/// ```no_run
/// use neva::{App, types::Role};
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_prompt("analyze-code", |lang: String| async move {
/// (format!("Language: {lang}"), Role::User)
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_prompt<F, R, Args>(&mut self, name: impl Into<String>, handler: F) -> &mut Prompt
where
F: PromptHandler<Args, Output = R>,
R: TryInto<GetPromptResult> + Send + 'static,
R::Error: Into<Error>,
Args: TryFrom<GetPromptRequestParams, Error = Error> + Send + Sync + 'static,
{
self.options.add_prompt(Prompt::new(name, handler))
}
/// Maps an MCP resource read request to a specific function
///
/// # Example
/// ```no_run
/// use neva::{App, types::{Resource, ListResourcesRequestParams}};
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_resources(|_params: ListResourcesRequestParams| async move {
/// [
/// Resource::new("res://res1", "res1"),
/// Resource::new("res://res2", "res2")
/// ]
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_resources<F, Args, R>(&mut self, handler: F) -> &mut Self
where
F: ListResourcesHandler<Args, Output = R> + Clone + Send + Sync + 'static,
Args: FromHandlerParams + Send + Sync + 'static,
R: Into<ListResourcesResult>,
{
let handler = move |params, args| {
let handler = handler.clone();
async move { handler.call(params, args).await.into() }
};
self.map_handler(crate::types::resource::commands::LIST, handler);
self
}
/// Maps a completion request
///
/// # Example
/// ```no_run
/// use neva::{App, types::{CompleteRequestParams, CompleteResult}};
///
/// # #[tokio::main]
/// # async fn main() {
/// let mut app = App::new();
///
/// app.map_completion(|_params: CompleteRequestParams| async move {
/// ["Item 1", "Item 2", "Item 3"]
/// });
///
/// # app.run().await;
/// # }
/// ```
pub fn map_completion<F, Args, R>(&mut self, handler: F) -> &mut Self
where
F: CompletionHandler<Args, Output = R> + Clone + Send + Sync + 'static,
Args: FromHandlerParams + Send + Sync + 'static,
R: Into<CompleteResult>,
{
let handler = move |params, args| {
let handler = handler.clone();
async move { handler.call(params, args).await.into() }
};
self.map_handler(crate::types::completion::commands::COMPLETE, handler);
self
}
/// Connection initialization handler (pre-RC handshake).
#[cfg(not(feature = "proto-2026-07-28-rc"))]
async fn init(
options: RuntimeMcpOptions,
_params: InitializeRequestParams,
) -> Result<InitializeResult, Error> {
Ok(InitializeResult::new(&options))
}
/// Stateless capability discovery handler (MCP 2026-07-28 RC).
#[cfg(feature = "proto-2026-07-28-rc")]
async fn discover(
options: RuntimeMcpOptions,
_params: crate::types::DiscoverRequestParams,
) -> Result<crate::types::DiscoverResult, Error> {
Ok(crate::types::DiscoverResult::new(&options))
}
/// Completion request handler
async fn completion() -> CompleteResult {
// return default as its non-optional capability so far
CompleteResult::default()
}
/// Tools request handler
#[cfg_attr(not(feature = "proto-2026-07-28-rc"), allow(clippy::needless_update))]
async fn tools(options: RuntimeMcpOptions, params: ListToolsRequestParams) -> ListToolsResult {
let (tools, next_cursor) = options
.list_tools_page(params.cursor, DEFAULT_PAGE_SIZE)
.await;
ListToolsResult {
tools,
next_cursor,
..Default::default()
}
}
/// Resources request handler
#[cfg_attr(not(feature = "proto-2026-07-28-rc"), allow(clippy::needless_update))]
async fn resources(
options: RuntimeMcpOptions,
params: ListResourcesRequestParams,
) -> ListResourcesResult {
let (resources, next_cursor) = options
.list_resources_page(params.cursor, DEFAULT_PAGE_SIZE)
.await;
ListResourcesResult {
resources,
next_cursor,
..Default::default()
}
}
/// Resource templates request handler
#[cfg_attr(not(feature = "proto-2026-07-28-rc"), allow(clippy::needless_update))]
async fn resource_templates(
options: RuntimeMcpOptions,
params: ListResourceTemplatesRequestParams,
) -> ListResourceTemplatesResult {
let (resource_templates, next_cursor) = options
.list_resource_templates_page(params.cursor, DEFAULT_PAGE_SIZE)
.await;
ListResourceTemplatesResult {
templates: resource_templates,
next_cursor,
..Default::default()
}
}
/// Prompts request handler
#[cfg_attr(not(feature = "proto-2026-07-28-rc"), allow(clippy::needless_update))]
async fn prompts(
options: RuntimeMcpOptions,
params: ListPromptsRequestParams,
) -> ListPromptsResult {
let (prompts, next_cursor) = options
.list_prompts_page(params.cursor, DEFAULT_PAGE_SIZE)
.await;
ListPromptsResult {
prompts,
next_cursor,
..Default::default()
}
}
/// A tool call request handler
#[cfg(not(feature = "tasks"))]
async fn tool(ctx: Context, params: CallToolRequestParams) -> Result<CallToolResponse, Error> {
ctx.call_tool(params).await
}
/// A tool call request handler
#[cfg(feature = "tasks")]
async fn tool(
ctx: Context,
params: CallToolRequestParams,
) -> Result<ToolOrTaskResponse, Error> {
ctx.call_tool_with_task(params).await
}
/// A read resource request handler
async fn resource(
ctx: Context,
params: ReadResourceRequestParams,
) -> Result<ReadResourceResult, Error> {
ctx.read_resource(params).await
}
/// A get prompt request handler
async fn prompt(
ctx: Context,
params: GetPromptRequestParams,
) -> Result<GetPromptResult, Error> {
ctx.get_prompt(params).await
}
/// Ping request handler
async fn ping() {}
/// A subscription to a resource change request handler
///
/// Not registered under `proto-2026-07-28-rc`: the stateless transport
/// cannot push `notifications/resources/updated`, so subscriptions are not
/// advertised and the method is not accepted.
#[cfg(not(feature = "proto-2026-07-28-rc"))]
async fn resource_subscribe(mut ctx: Context, params: SubscribeRequestParams) {
ctx.subscribe_to_resource(params.uri);
}
/// An unsubscription to from resource change request handler
///
/// Not registered under `proto-2026-07-28-rc`; see [`Self::resource_subscribe`].
#[cfg(not(feature = "proto-2026-07-28-rc"))]
async fn resource_unsubscribe(mut ctx: Context, params: UnsubscribeRequestParams) {
ctx.unsubscribe_from_resource(¶ms.uri);
}
/// Tasks request handler
#[cfg(feature = "tasks")]
async fn tasks(
options: RuntimeMcpOptions,
params: ListTasksRequestParams,
) -> Result<ListTasksResult, Error> {
if !options.is_tasks_list_supported() {
return Err(Error::new(
ErrorCode::InvalidRequest,
"Server does not support support tasks/list requests.",
));
}
Ok(options
.list_tasks()
.paginate(params.cursor, DEFAULT_PAGE_SIZE)
.into())
}
/// A cancel task request handler
#[cfg(feature = "tasks")]
async fn cancel_task(
options: RuntimeMcpOptions,
params: CancelTaskRequestParams,
) -> Result<Task, Error> {
if options.is_tasks_cancellation_supported() {
options.cancel_task(¶ms.id)
} else {
Err(Error::new(
ErrorCode::InvalidRequest,
"Server does not support support tasks/cancel requests.",
))
}
}
/// A task status retrieval request handler
#[cfg(feature = "tasks")]
async fn task(options: RuntimeMcpOptions, params: GetTaskRequestParams) -> Result<Task, Error> {
options.get_task_status(¶ms.id)
}
/// A task result retrieval request handler
#[cfg(feature = "tasks")]
async fn task_result(
options: RuntimeMcpOptions,
params: GetTaskPayloadRequestParams,
) -> Result<TaskPayload, Error> {
options.get_task_result(¶ms.id).await
}
/// Sets the logging level
#[allow(deprecated)]
#[cfg(all(feature = "tracing", not(feature = "proto-2026-07-28-rc")))]
async fn set_log_level(
options: RuntimeMcpOptions,
params: SetLevelRequestParams,
) -> Result<(), Error> {
let current_level = options.log_level();
tracing::debug!(
logger = "neva",
"Logging level has been changed from {:?} to {:?}",
current_level,
params.level
);
options.set_log_level(params.level)
}
#[cfg(feature = "tracing")]
async fn tracing_middleware(ctx: MwContext, next: Next) -> Response {
let span = create_tracing_span(ctx.session_id().cloned());
next(ctx).instrument(span).await
}
#[inline]
async fn execute(msg: Message, runtime: ServerRuntime) {
runtime.execute(msg).await;
}
async fn execute_batch(batch: MessageBatch, runtime: ServerRuntime) {
use crate::transport::TransportProtoSender;
use futures_util::future::join_all;
// Capture the incoming batch's correlation and HTTP-context fields.
// `id` + `session_id` are needed so the response batch can be routed
// back to the correct waiting HTTP handler. `headers` and `claims`
// are copied onto every inner Request so that middleware (auth checks,
// role/permission guards, SSE routing) sees the original HTTP context.
let batch_id = batch.id.clone();
let batch_session_id = batch.session_id;
#[cfg(feature = "http-server")]
let batch_headers = batch.headers.clone();
#[cfg(feature = "http-server")]
let batch_claims = batch.claims.clone();
let real_sender = runtime.sender();
// Collect responses produced by batch request handlers in-memory.
// Server-initiated messages (sampling, elicitation, notifications) go
// straight to the real transport inside BatchCollect::send, so handlers
// that call ctx.elicit()/ctx.sample() never deadlock.
//
// Crucially, background tasks that capture a BatchCollect sender clone
// do NOT block the batch response: we only wait for the join_all futures,
// then snapshot whatever responses have been collected so far.
let responses: Arc<std::sync::Mutex<Vec<MessageEnvelope>>> = Arc::default();
let batch_sender = TransportProtoSender::BatchCollect {
real_sender: Arc::new(tokio::sync::Mutex::new(real_sender.clone())),
responses: Arc::clone(&responses),
};
// Capture before consuming the batch so we know whether to send an ack
// when all Response envelopes were consumed by pending.complete (§ below).
let has_error_responses = batch
.iter()
.any(|e| matches!(e, MessageEnvelope::Response(Response::Err(_))));
let futures = batch.into_iter().map(|envelope| {
let runtime = runtime.clone();
let mut sender = batch_sender.clone();
// Clone per-iteration so each async move block owns its own copy.
#[cfg(feature = "http-server")]
let batch_headers = batch_headers.clone();
#[cfg(feature = "http-server")]
let batch_claims = batch_claims.clone();
async move {
match envelope {
MessageEnvelope::Request(mut req) => {
// Copy the batch's HTTP metadata onto the inner request
// so that session/auth context is preserved: without
// this, role/permission checks can fail with a valid
// token and server-initiated follow-up calls (sampling,
// elicitation) cannot be routed back over SSE.
req.session_id = batch_session_id;
#[cfg(feature = "http-server")]
{
req.headers = batch_headers;
req.claims = batch_claims;
}
// Route through the full middleware chain with the
// batch-collect sender so registered middlewares apply.
runtime
.with_sender(sender)
.execute(Message::Request(req))
.await;
}
MessageEnvelope::Notification(notification) => {
Self::handle_notification(notification, runtime.clone()).await;
}
MessageEnvelope::Response(mut resp) => {
// Apply the batch's session context so that
// `resp.full_id()` (= session_id + resp_id) matches
// the key used when the server registered the pending
// request via `send_request`. Without this the lookup
// in the pending queue misses and the pending handler leaks.
if let Some(session_id) = batch_session_id {
resp = resp.set_session_id(session_id);
}
#[cfg(feature = "http-server")]
{
resp = resp.set_headers(batch_headers);
}
// If a pending server-initiated request matches this id,
// complete it (the client is responding to a server request
// inside the batch). Otherwise, if the response carries an
// error, it is a synthetic InvalidRequest injected by the
// deserializer for a malformed batch item — route it through
// the collector so it appears in the batch reply.
// Unmatched Ok responses are unsolicited or stale and are
// dropped silently, consistent with the single-message
// handle_response path.
if let Some(handle) = runtime.pending_requests().pop(&resp.full_id()) {
handle.send(resp);
} else if matches!(resp, Response::Err(_)) {
let _ = sender.send(Message::Response(resp)).await;
}
}
}
}
});
join_all(futures).await;
// Snapshot collected responses. Any response that a background task
// produces after this point is silently discarded — it arrived too
// late to be included in the batch reply.
let envelopes = responses
.lock()
.map(|mut guard| std::mem::take(&mut *guard))
.unwrap_or_default();
if envelopes.is_empty() {
if has_error_responses {
// All Response::Err items were legitimate peer error responses
// consumed by pending.complete above. If the HTTP transport
// created a pending slot for this batch (because
// `has_error_responses()` was true), we must close it;
// otherwise the HTTP handler will block forever waiting for a
// reply that never comes.
let mut ack = Response::empty(batch_id);
if let Some(session_id) = batch_session_id {
ack = ack.set_session_id(session_id);
}
let mut sender = real_sender;
let _ = sender.send(Message::Response(ack)).await;
}
return;
}
let mut resp_batch = match MessageBatch::new(envelopes) {
Ok(b) => b,
Err(_err) => {
// Unreachable in practice: envelopes are non-empty above.
#[cfg(feature = "tracing")]
tracing::error!(
logger = "neva",
"Failed to construct batch response: {:?}",
_err
);
return;
}
};
// Restore the correlation id+session so the HTTP transport can match
// this response batch to the waiting HTTP handler.
resp_batch.id = batch_id;
resp_batch.session_id = batch_session_id;
let mut sender = real_sender;
if let Err(_err) = sender.send(Message::Batch(resp_batch)).await {
#[cfg(feature = "tracing")]
tracing::error!(logger = "neva", "Error sending batch response: {:?}", _err);
}
}
async fn message_middleware(ctx: MwContext, _: Next) -> Response {
let MwContext {
msg,
runtime,
#[cfg(feature = "di")]
scope,
} = ctx;
let id = msg.id();
let mut sender = runtime.sender();
if let Some(resp) = Self::handle_message(
msg,
runtime,
#[cfg(feature = "di")]
scope,
)
.await
&& let Err(_err) = sender.send(resp.into()).await
{
#[cfg(feature = "tracing")]
tracing::error!(
logger = "neva",
error = format!("Error sending response: {:?}", _err)
);
}
Response::empty(id)
}
#[inline]
async fn handle_message(
msg: Message,
runtime: ServerRuntime,
#[cfg(feature = "di")] scope: Container,
) -> Option<Response> {
match msg {
Message::Request(req) => Some(
Self::handle_request(
req,
runtime,
#[cfg(feature = "di")]
scope,
)
.await,
),
Message::Response(resp) => Some(Self::handle_response(resp, runtime).await),
Message::Notification(notification) => {
// JSON-RPC 2.0 §4: notifications must never receive a response.
Self::handle_notification(notification, runtime).await;
None
}
Message::Batch(_) => {
// Batches are dispatched via execute_batch before reaching handle_message
unreachable!(
"Message::Batch should be intercepted in App::run before handle_message"
)
}
}
}
async fn handle_request(
req: Request,
runtime: ServerRuntime,
#[cfg(feature = "di")] scope: Container,
) -> Response {
#[cfg(feature = "http-server")]
let mut req = req;
let req_id = req.id();
let session_id = req.session_id;
let full_id = req.full_id();
// MRTR pre-capture: method + salient params (params minus `_meta`),
// needed after `req`/`context` are moved into `handler.call`.
#[cfg(feature = "proto-2026-07-28-rc")]
let mrtr_method = shared::is_mrtr_method(&req.method);
#[cfg(feature = "proto-2026-07-28-rc")]
let req_method = req.method.clone();
#[cfg(feature = "proto-2026-07-28-rc")]
let salient_params = req
.params
.as_ref()
.map(strip_meta)
.unwrap_or(serde_json::Value::Null);
#[cfg(not(feature = "http-server"))]
let context = runtime.context(session_id);
#[cfg(feature = "http-server")]
let context = {
let headers = std::mem::take(&mut req.headers);
let claims = req.claims.take();
runtime.context(session_id, headers, claims)
};
#[cfg(feature = "di")]
let context = context.with_scope(scope);
let options = runtime.options();
let handlers = runtime.request_handlers();
let token = options.track_request(&full_id);
// MRTR seed: decode/verify any incoming `requestState`, merge this
// round's `inputResponses`, and attach the replay state to the context.
#[cfg(feature = "proto-2026-07-28-rc")]
let mut context = context;
#[cfg(feature = "proto-2026-07-28-rc")]
let (mrtr_arc, mrtr_principal) = if mrtr_method {
#[cfg(feature = "http-server")]
let principal = context
.claims
.as_ref()
.and_then(|c| c.subject().map(|s| s.to_owned()));
#[cfg(not(feature = "http-server"))]
let principal: Option<String> = None;
match seed_mrtr_ctx(
&req,
&req_method,
&salient_params,
&options,
principal.as_deref(),
) {
Ok(arc) => {
context.exec = crate::app::context::ExecMode::Mrtr(arc.clone());
(Some(arc), principal)
}
Err(e) => {
options.complete_request(&full_id);
let mut resp = Err::<Response, _>(e).into_response(req_id);
if let Some(session_id) = session_id {
resp = resp.set_session_id(session_id);
}
return resp;
}
}
} else {
(None, None)
};
// MRTR idempotency: the final-round response cache is keyed by the
// incoming state's sealed segment (the ciphertext+tag after the `.`,
// unique per minted state thanks to the random AEAD nonce) *plus* a
// digest of this round's `inputResponses`. The answers digest matters
// because the *same* minted state can be echoed with *different*
// answers — a client (or attacker) replaying one round-1 blob with two
// different `inputResponses` would otherwise hit the first answer's
// cached result for the second. Folding in the answers' digest keeps
// those apart, while a genuine lost-response retry — same state *and*
// same answers — still hits. Only committed *final* rounds are ever
// cached, so a hit here is by construction a replay of one.
#[cfg(feature = "proto-2026-07-28-rc")]
let state_tag: Option<String> = if mrtr_method {
req.meta().and_then(|m| {
let tag = m
.request_state
.as_deref()
.and_then(|blob| blob.rsplit_once('.').map(|(_, tag)| tag))?;
let answers = m
.input_responses
.as_ref()
.map(crate::types::mrtr::state::input_responses_digest)
.unwrap_or_default();
Some(format!("{tag}.{answers}"))
})
} else {
None
};
// Claim the per-state reservation *before* the cache lookup and hold it
// through the handler, commits and the final `put`. Two identical
// final-round retries (e.g. a client that timed out and re-sent while
// the first round is still committing) would otherwise both miss the
// cache below and re-run the handler + `on_commit` effects. The loser
// blocks here until the winner has cached, then hits it instead.
//
// NOTE: this guard MUST stay live until after the final `put` below.
// Dropping it early (e.g. rewriting to `let _ = ...reserve().await;`)
// releases the lock immediately and reopens the concurrent-retry race;
// the explicit, self-describing name guards against that refactor.
#[cfg(feature = "proto-2026-07-28-rc")]
let _reservation_guard_held_through_commit = match state_tag.as_deref() {
Some(tag) => Some(options.request_state_store().reserve(tag).await),
None => None,
};
#[cfg(feature = "proto-2026-07-28-rc")]
if let Some(tag) = state_tag.as_deref()
&& let Some(cached) = options.request_state_store().get(tag).await
{
options.complete_request(&full_id);
let mut resp = cached.set_id(req_id.clone());
if let Some(session_id) = session_id {
resp = resp.set_session_id(session_id);
}
return resp;
}
#[cfg(feature = "tracing")]
tracing::trace!(logger = "neva", "Received: {:?}", req);
let resp = if let Some(handler) = handlers.get(&req.method) {
tokio::select! {
resp = handler.call(HandlerParams::Request(context, req)) => {
options.complete_request(&full_id);
resp
}
_ = token.cancelled() => {
#[cfg(feature = "tracing")]
tracing::debug!(
logger = "neva",
"The request with ID: {} has been cancelled", full_id);
Err(Error::from(ErrorCode::RequestCancelled))
}
}
} else {
Err(Error::from(ErrorCode::MethodNotFound))
};
// MRTR interception: if the handler requested input (recorded in the
// shared `MrtrCtx`), convert to an `InputRequiredResult` regardless of
// what the handler returned. The pending flag — not the sentinel error
// — is the reliable signal, because tool/prompt/resource wrappers fold
// a handler `Err` into an in-band error result before we see it.
#[cfg(feature = "proto-2026-07-28-rc")]
let mut cache_final = false;
#[cfg(feature = "proto-2026-07-28-rc")]
let resp = match (mrtr_method, mrtr_arc) {
(true, Some(arc)) => {
let has_pending = arc.pending.lock().map(|p| p.is_some()).unwrap_or(false);
if has_pending {
build_input_required(
&arc,
&req_method,
&salient_params,
&options,
mrtr_principal,
)
.map(|ir| ir.into_response(req_id.clone()))
} else if mrtr_should_commit(&resp) {
// Final round: run deferred commits in registration order.
// The first Err becomes the response error.
let commits = arc
.commits
.lock()
.map(|mut c| std::mem::take(&mut *c))
.unwrap_or_default();
let mut commit_err = None;
for fut in commits {
if let Err(e) = fut.await {
commit_err = Some(e);
break;
}
}
match commit_err {
Some(e) => Err(e),
None => {
// Final round committed successfully: cache its
// response (below, once the id is final) so a
// lost-response retry is served idempotently.
cache_final = true;
resp
}
}
} else {
resp
}
}
_ => resp,
};
let mut resp = resp.into_response(req_id);
if let Some(session_id) = session_id {
resp = resp.set_session_id(session_id);
}
// Record the committed final response under the incoming state's tag
// plus this round's answers digest (see `state_tag` above). Retained
// until the state's own expiry window (`now + ttl`, an upper bound on
// its remaining life), after which a retry is rejected as expired before
// reaching the store.
#[cfg(feature = "proto-2026-07-28-rc")]
if cache_final && let Some(tag) = state_tag.as_deref() {
let exp = crate::types::mrtr::state::now_secs() + options.request_state_ttl_secs();
options
.request_state_store()
.put(tag, resp.clone(), exp)
.await;
}
resp
}
async fn handle_response(resp: Response, runtime: ServerRuntime) -> Response {
let resp_id = resp.id().clone();
let session_id = resp.session_id().cloned();
// RC task-elicit resume: an answer to a suspended task `ctx.elicit` is
// correlated by the server-generated task id (the bare response id),
// *not* the session — the stateless transport mints a fresh session per
// POST, so the session-keyed request queue could never match the
// suspend round. Try delivering to a parked task first; `provide_input`
// hands the response back when no task elicit is waiting, so non-task
// responses fall through to the request queue unchanged.
#[cfg(all(feature = "proto-2026-07-28-rc", feature = "tasks"))]
let resp = match runtime
.options()
.tasks
.provide_input(&resp_id.to_string(), resp)
{
Ok(()) => {
let mut resp = Response::empty(resp_id);
if let Some(session_id) = session_id {
resp = resp.set_session_id(session_id);
}
return resp;
}
Err(resp) => *resp,
};
runtime.pending_requests().complete(resp);
let mut resp = Response::empty(resp_id);
if let Some(session_id) = session_id {
resp = resp.set_session_id(session_id);
}
resp
}
#[inline]
async fn handle_notification(notification: Notification, runtime: ServerRuntime) {
match notification.method.as_str() {
crate::types::notification::commands::CANCELLED => {
if let Some(params) = notification.params
&& let Ok(params) =
serde_json::from_value::<CancelledNotificationParams>(params)
{
runtime.options().cancel_request(¶ms.request_id);
}
}
#[cfg(not(feature = "proto-2026-07-28-rc"))]
crate::types::notification::commands::MESSAGE => {
#[cfg(feature = "tracing")]
notification.write();
}
_ => {}
}
}
#[inline]
fn wait_for_shutdown_signal(&mut self, token: CancellationToken) {
shared::wait_for_shutdown_signal(token);
}
}
#[cfg(feature = "tracing")]
fn create_tracing_span(session_id: Option<uuid::Uuid>) -> tracing::Span {
if let Some(mcp_session_id) = session_id {
tracing::info_span!("request", mcp_session_id = mcp_session_id.to_string())
} else {
tracing::info_span!("request")
}
}
/// Returns a clone of `params` with the `_meta` key removed, so the MRTR
/// request-binding digest is stable across round-trips.
#[cfg(feature = "proto-2026-07-28-rc")]
fn strip_meta(params: &serde_json::Value) -> serde_json::Value {
match params {
serde_json::Value::Object(map) => {
let mut cloned = map.clone();
cloned.remove("_meta");
serde_json::Value::Object(cloned)
}
other => other.clone(),
}
}
/// Decodes/verifies any incoming `requestState` and merges this round's
/// `inputResponses` into the replay log, producing the per-dispatch MRTR state.
#[cfg(feature = "proto-2026-07-28-rc")]
fn seed_mrtr_ctx(
req: &Request,
method: &str,
salient: &serde_json::Value,
options: &crate::app::options::RuntimeMcpOptions,
principal: Option<&str>,
) -> Result<std::sync::Arc<crate::app::context::MrtrCtx>, Error> {
use crate::types::mrtr::state::{StateCodec, now_secs, request_binding};
let meta = req.meta();
let elicitation_allowed = meta
.as_ref()
.and_then(|m| m.client_capabilities)
.map(|c| c.elicitation)
.unwrap_or(false);
let mut answers = std::collections::HashMap::new();
let mut memos = std::collections::HashMap::new();
let mut effects = std::collections::HashSet::new();
// Keys the server requested in the prior round, decoded from the verified
// state. `None` means no valid state was supplied, so no input was solicited.
let mut requested: Option<Vec<String>> = None;
if let Some(state) = meta.as_ref().and_then(|m| m.request_state.clone()) {
// Reject an oversized inbound state before decoding it. Base64 decoding
// and AEAD decryption in `StateCodec::decode` both allocate/compute in
// proportion to the blob size, so without this guard `with_max_state_bytes`
// would only bound the states we *mint* and a bogus oversized
// `requestState` from an untrusted client could force that work before
// failing. The cap is the same encoded-length bound enforced on the
// outbound path in `build_input_required`.
if state.len() > options.max_state_bytes() {
return Err(Error::new(
ErrorCode::InvalidParams,
"requestState exceeds the configured maximum size",
));
}
let payload = StateCodec::new(options.request_state_secret()).decode(&state)?;
if payload.exp < now_secs() {
return Err(Error::new(ErrorCode::InvalidParams, "requestState expired"));
}
if payload.req != request_binding(method, salient) {
return Err(Error::new(
ErrorCode::InvalidParams,
"requestState does not match this request",
));
}
if payload.principal.as_deref() != principal {
return Err(Error::new(
ErrorCode::InvalidParams,
"requestState principal mismatch",
));
}
answers = payload.answers;
memos = payload.memos;
effects = payload.effects;
requested = Some(payload.requested);
}
if let Some(responses) = meta.and_then(|m| m.input_responses) {
// `inputResponses` are answers to inputs the server requested in a
// prior round; that request set lives in the encrypted `requestState`.
// Without a verified state there is nothing to bind them to, so accept
// only solicited, non-duplicate keys — otherwise a client could
// pre-seed answers for a later `ctx.elicit` key (skipping the intended
// `InputRequiredResult`) or overwrite an already-resolved answer.
let Some(requested) = requested.as_ref() else {
return Err(Error::new(
ErrorCode::InvalidParams,
"inputResponses supplied without a requestState",
));
};
for (key, value) in responses {
if answers.contains_key(&key) {
return Err(Error::new(
ErrorCode::InvalidParams,
"inputResponses re-answers an already-resolved input",
));
}
if !requested.contains(&key) {
return Err(Error::new(
ErrorCode::InvalidParams,
"inputResponses contains a key the server did not request",
));
}
answers.insert(key, value);
}
}
Ok(std::sync::Arc::new(crate::app::context::MrtrCtx {
answers,
pending: Default::default(),
elicitation_allowed,
memos: std::sync::Mutex::new(memos),
effects: std::sync::Mutex::new(effects),
commits: Default::default(),
}))
}
/// Builds the `InputRequiredResult` for the input the handler requested,
/// encoding a fresh encrypted `requestState`.
#[cfg(feature = "proto-2026-07-28-rc")]
fn build_input_required(
arc: &std::sync::Arc<crate::app::context::MrtrCtx>,
method: &str,
salient: &serde_json::Value,
options: &crate::app::options::RuntimeMcpOptions,
principal: Option<String>,
) -> Result<crate::types::mrtr::InputRequiredResult, Error> {
use crate::types::mrtr::InputRequiredResult;
use crate::types::mrtr::state::{StateCodec, StatePayload, now_secs, request_binding};
if !arc.elicitation_allowed {
return Err(Error::new(
ErrorCode::InvalidRequest,
"server requested elicitation but the client did not declare support",
));
}
let (key, params) = arc
.pending
.lock()
.ok()
.and_then(|mut p| p.take())
.ok_or_else(|| Error::new(ErrorCode::InternalError, "missing pending MRTR input"))?;
let memos = arc.memos.lock().map(|m| m.clone()).unwrap_or_default();
let effects = arc.effects.lock().map(|e| e.clone()).unwrap_or_default();
let payload = StatePayload {
answers: arc.answers.clone(),
// Bind the key we are requesting into the signed state so the next
// round can verify the client only answers what we actually asked for.
requested: vec![key.clone()],
memos,
effects,
exp: now_secs() + options.request_state_ttl_secs(),
req: request_binding(method, salient),
principal,
};
let state = StateCodec::new(options.request_state_secret()).encode(&payload)?;
if state.len() > options.max_state_bytes() {
return Err(Error::new(
ErrorCode::InternalError,
"requestState too large",
));
}
Ok(InputRequiredResult::elicitation(key, params, state))
}
/// Returns `true` only when `resp` is a genuine success that should trigger the
/// final round's deferred MRTR commits.
///
/// A protocol-level failure (`Err`, or an `Ok(Response::Err(..))`) is excluded
/// by construction. Crucially, so is an *in-band* tool error: tool/prompt
/// wrappers fold a handler `Err` into `Ok(CallToolResponse { isError: true })`,
/// so a plain `resp.is_ok()` check would still run commits on a failed call —
/// applying irreversible side effects (DB writes, charges) registered via
/// `ctx.on_commit(..)` even though the tool ultimately reported failure.
#[cfg(feature = "proto-2026-07-28-rc")]
fn mrtr_should_commit(resp: &Result<Response, Error>) -> bool {
match resp {
Ok(Response::Ok(ok)) => ok.result.get("isError") != Some(&serde_json::Value::Bool(true)),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::App;
use crate::types::{MessageBatch, MessageEnvelope};
#[test]
fn it_enables_greeting_with_with_greeting() {
let app = App::new().with_greeting();
assert!(app.greeting);
}
#[cfg(feature = "proto-2026-07-28-rc")]
#[test]
fn with_max_state_bytes_sets_the_option() {
let app = App::new().with_max_state_bytes(4096);
assert_eq!(app.options.max_state_bytes(), 4096);
}
/// Deferred MRTR commits must run only for a genuine success — never for a
/// protocol-level error nor for an in-band tool error (`isError: true`),
/// which tool wrappers fold a handler `Err` into.
#[cfg(feature = "proto-2026-07-28-rc")]
#[test]
fn mrtr_should_commit_excludes_errors() {
use crate::error::Error;
use crate::types::{RequestId, Response};
use serde_json::json;
let id = RequestId::Number(1);
// Genuine success → commit.
let ok = Ok(Response::success(
id.clone(),
json!({ "content": [], "isError": false }),
));
assert!(super::mrtr_should_commit(&ok));
// Success with no `isError` field at all (e.g. a non-tool result) → commit.
let plain = Ok(Response::success(id.clone(), json!({ "ok": true })));
assert!(super::mrtr_should_commit(&plain));
// In-band tool error folded into Ok → do NOT commit.
let tool_err = Ok(Response::success(
id.clone(),
json!({ "content": [], "isError": true }),
));
assert!(!super::mrtr_should_commit(&tool_err));
// Protocol-level error response → do NOT commit.
let proto_err = Ok(Response::error(id.clone(), Error::new(-32603, "boom")));
assert!(!super::mrtr_should_commit(&proto_err));
// Handler `Err` → do NOT commit.
let hard_err: Result<Response, Error> = Err(Error::new(-32603, "boom"));
assert!(!super::mrtr_should_commit(&hard_err));
}
/// Security guards in [`super::seed_mrtr_ctx`] that the e2e happy path never
/// exercises: an expired `requestState` and a principal-bound state replayed
/// under a different principal. Driven deterministically (no clock advance,
/// no auth harness) by hand-encoding the signed blob.
#[cfg(feature = "proto-2026-07-28-rc")]
mod mrtr_seed_guards {
use crate::app::App;
use crate::error::ErrorCode;
use crate::types::mrtr::state::{StateCodec, StatePayload, now_secs, request_binding};
use crate::types::{Request, RequestId};
const SECRET: &[u8] = b"unit-secret";
const METHOD: &str = "tools/call";
fn options() -> crate::app::options::RuntimeMcpOptions {
App::new()
.with_request_state_secret(SECRET)
.options
.into_runtime()
}
fn salient() -> serde_json::Value {
serde_json::json!({ "name": "greet", "arguments": {} })
}
fn request_with_state(state: &str) -> Request {
let mut params = salient();
params["_meta"] = serde_json::json!({
"requestState": state,
"clientCapabilities": { "elicitation": true }
});
Request::new(Some(RequestId::Number(1)), METHOD, Some(params))
}
fn encode(payload: &StatePayload) -> String {
StateCodec::new(SECRET).encode(payload).expect("encode")
}
#[test]
fn expired_request_state_is_rejected() {
let payload = StatePayload {
answers: Default::default(),
requested: Default::default(),
memos: Default::default(),
effects: Default::default(),
exp: now_secs().saturating_sub(1), // already in the past
req: request_binding(METHOD, &salient()),
principal: None,
};
let req = request_with_state(&encode(&payload));
let err = super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), None)
.expect_err("expired state must be rejected");
assert_eq!(err.code, ErrorCode::InvalidParams);
assert!(format!("{err}").contains("expired"), "{err}");
}
#[test]
fn principal_mismatch_is_rejected() {
// State minted for "alice" (valid, unexpired, correctly bound)...
let payload = StatePayload {
answers: Default::default(),
requested: Default::default(),
memos: Default::default(),
effects: Default::default(),
exp: now_secs() + 300,
req: request_binding(METHOD, &salient()),
principal: Some("alice".into()),
};
let req = request_with_state(&encode(&payload));
// ...replayed by "bob".
let err =
super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), Some("bob"))
.expect_err("principal mismatch must be rejected");
assert_eq!(err.code, ErrorCode::InvalidParams);
assert!(format!("{err}").contains("principal mismatch"), "{err}");
}
/// Builds the `_meta` JSON with the given request state (if any) and
/// `inputResponses` map of key → accepted [`ElicitResult`].
fn request_with_responses(state: Option<&str>, response_keys: &[&str]) -> Request {
use crate::types::elicitation::ElicitResult;
let responses: serde_json::Map<String, serde_json::Value> = response_keys
.iter()
.map(|k| {
(
(*k).to_owned(),
serde_json::to_value(ElicitResult::accept()).expect("serialize result"),
)
})
.collect();
let mut meta = serde_json::json!({
"clientCapabilities": { "elicitation": true },
"inputResponses": responses,
});
if let Some(state) = state {
meta["requestState"] = serde_json::json!(state);
}
let mut params = salient();
params["_meta"] = meta;
Request::new(Some(RequestId::Number(1)), METHOD, Some(params))
}
fn state_with(answers: &[&str], requested: &[&str]) -> String {
use crate::types::elicitation::ElicitResult;
let answers = answers
.iter()
.map(|k| ((*k).to_owned(), ElicitResult::accept()))
.collect();
let payload = StatePayload {
answers,
requested: requested.iter().map(|k| (*k).to_owned()).collect(),
memos: Default::default(),
effects: Default::default(),
exp: now_secs() + 300,
req: request_binding(METHOD, &salient()),
principal: None,
};
encode(&payload)
}
#[test]
fn input_responses_without_request_state_are_rejected() {
// No validated state: nothing solicited these answers.
let req = request_with_responses(None, &["ask_name"]);
let err = super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), None)
.expect_err("unbound inputResponses must be rejected");
assert_eq!(err.code, ErrorCode::InvalidParams);
assert!(format!("{err}").contains("without a requestState"), "{err}");
}
#[test]
fn unsolicited_input_response_key_is_rejected() {
// State requested `ask_name`; client answers an unrelated key.
let state = state_with(&[], &["ask_name"]);
let req = request_with_responses(Some(&state), &["ask_age"]);
let err = super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), None)
.expect_err("unsolicited key must be rejected");
assert_eq!(err.code, ErrorCode::InvalidParams);
assert!(format!("{err}").contains("did not request"), "{err}");
}
#[test]
fn re_answering_a_resolved_input_is_rejected() {
// `ask_name` already resolved in the signed answers log; the client
// tries to overwrite it (even though it is also in `requested`).
let state = state_with(&["ask_name"], &["ask_name"]);
let req = request_with_responses(Some(&state), &["ask_name"]);
let err = super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), None)
.expect_err("re-answering must be rejected");
assert_eq!(err.code, ErrorCode::InvalidParams);
assert!(format!("{err}").contains("already-resolved"), "{err}");
}
#[test]
fn solicited_input_response_is_accepted() {
// The happy path: client answers exactly the requested key.
let state = state_with(&[], &["ask_name"]);
let req = request_with_responses(Some(&state), &["ask_name"]);
let ctx = super::super::seed_mrtr_ctx(&req, METHOD, &salient(), &options(), None)
.expect("solicited response must be accepted");
assert!(ctx.answers.contains_key("ask_name"));
}
}
#[cfg(feature = "proto-2026-07-28-rc")]
#[test]
fn rc_registers_discover_not_initialize() {
let app = App::new();
assert!(app.handlers.contains_key(crate::commands::DISCOVER));
assert!(!app.handlers.contains_key(crate::commands::INIT));
}
#[cfg(not(feature = "proto-2026-07-28-rc"))]
#[test]
fn default_registers_initialize() {
let app = App::new();
assert!(app.handlers.contains_key(crate::commands::INIT));
}
#[test]
fn it_disables_greeting_with_without_greeting() {
let app = App::new().without_greeting();
assert!(!app.greeting);
}
#[test]
fn batch_filtering_notifications_yield_no_response_slots() {
use crate::types::notification::Notification;
// Build a notification-only batch
let batch = MessageBatch::new(vec![
MessageEnvelope::Notification(Notification::new("notifications/foo", None)),
MessageEnvelope::Notification(Notification::new("notifications/bar", None)),
])
.expect("non-empty batch must be constructable");
// Replicate the filter logic from execute_batch:
// Request → Some(response slot), Notification/Response → None
let response_slots: Vec<MessageEnvelope> = batch
.into_iter()
.filter_map(|envelope| match envelope {
MessageEnvelope::Request(_) => Some(envelope),
_ => None,
})
.collect();
assert!(
response_slots.is_empty(),
"notification-only batch must produce zero response slots"
);
}
#[test]
fn batch_filtering_requests_yield_response_slots() {
use crate::types::{Request, RequestId};
// Build a request-only batch
let req1 = Request::new(Some(RequestId::Number(1)), "tools/list", None::<()>);
let req2 = Request::new(Some(RequestId::Number(2)), "ping", None::<()>);
let batch = MessageBatch::new(vec![
MessageEnvelope::Request(req1),
MessageEnvelope::Request(req2),
])
.expect("non-empty batch must be constructable");
// Replicate the filter: only Request envelopes produce response slots
let response_slots: Vec<MessageEnvelope> = batch
.into_iter()
.filter_map(|envelope| match envelope {
MessageEnvelope::Request(_) => Some(envelope),
_ => None,
})
.collect();
assert_eq!(
response_slots.len(),
2,
"two requests must produce two response slots"
);
}
}