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
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
//! Model Context Protocol (MCP) Server Implementation
//!
//! This module provides a comprehensive MCP server that exposes IronShell's
//! OS tools database through the Model Context Protocol, enabling AI agents
//! to discover and execute tools in a standardized way.
//!
//! Features:
//! - Full MCP protocol compliance
//! - Tool discovery and execution
//! - Schema generation for function calling
//! - Safety level enforcement
//! - Cross-platform command translation
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value as JsonValue};
use std::collections::HashMap;
use std::sync::Arc;
use crate::os_tools::{OSTool, OSToolsDatabase, OperatingSystem, SafetyLevel, ToolCategory};
/// A coded error for the MCP module (`builtin` = "mcp"). The remote client and
/// the serve command build these so a caller can tell a failed remote call (`Io`)
/// from a bad address (`BadArg`) or a policy refusal (`PolicyDeny`).
fn mcp_coded(code: crate::safety::ErrorCode, message: String, hint: &str) -> anyhow::Error {
anyhow::Error::new(crate::safety::SafetyError {
code,
message,
builtin: "mcp".to_string(),
hint: hint.to_string(),
approval: None,
did_you_mean: Vec::new(),
expected: String::new(),
got: String::new(),
extra: serde_json::Map::new(),
})
}
/// Check caller-supplied OS tool arguments before anything is spawned.
///
/// A parameter that declares allowed values (`enum_values`, such as curl's
/// `method`) must hold one of them. A string value beginning with `-` is
/// refused, because the tool would parse it as an option: `method: "-o"` made
/// curl write its response to whatever path the next argument named. The one
/// exception is a parameter declared as a flag, which here means a parameter
/// whose name begins with `-`; no OS tool declares one today.
fn validate_tool_args(tool: &OSTool, args: &HashMap<String, JsonValue>) -> Result<()> {
for param in &tool.parameters {
let Some(value) = args.get(¶m.name) else {
continue;
};
if !param.enum_values.is_empty() {
let allowed = matches!(value, JsonValue::String(s) if param.enum_values.contains(s));
if !allowed {
return Err(mcp_coded(
crate::safety::ErrorCode::BadArg,
format!(
"{}: '{}' must be one of [{}]",
tool.name,
param.name,
param.enum_values.join(", ")
),
"pass one of the listed values for this parameter",
));
}
}
if param.name.starts_with('-') {
continue;
}
let strings: Vec<&str> = match value {
JsonValue::String(s) => vec![s.as_str()],
JsonValue::Array(items) => items.iter().filter_map(|v| v.as_str()).collect(),
_ => Vec::new(),
};
if let Some(bad) = strings.iter().find(|s| s.starts_with('-')) {
return Err(mcp_coded(
crate::safety::ErrorCode::BadArg,
format!(
"{}: '{}' is an option-like value {:?}, which the tool would read as a flag",
tool.name, param.name, bad
),
"pass a value that does not begin with '-'; a path that does is reachable as ./-name",
));
}
}
Ok(())
}
/// The argv of a call to the `curl` OS tool, built from its declared parameters
/// alone: `method` becomes `-X <method>`, each `headers` item `-H <item>`, `data`
/// `--data-raw <data>`, and `url` follows `--`, so no value is read as an option.
/// The values used to be passed as bare arguments, so curl took `GET` for a URL.
///
/// `--data-raw` rather than `--data`, because `--data` reads a file for a value
/// beginning with `@`. A header beginning with `@` names a file of headers, so it
/// is refused. `output` is refused too: curl would write the response to that
/// path, which the argument checks never judge against the workspace, and the
/// response is returned as the tool's output anyway.
///
/// Pure, so the mapping can be tested without a network.
fn curl_argv(args: &HashMap<String, JsonValue>) -> Result<Vec<String>> {
if args.contains_key("output") {
return Err(curl_refusal(
"output",
"is not supported: the response is returned as the tool's output",
));
}
// A string the tool would read as an option is refused, and so is any other type.
let text = |name: &str, value: &JsonValue| -> Result<String> {
match value {
JsonValue::String(s) if s.starts_with('-') => Err(curl_refusal(
name,
"begins with '-', which curl would read as an option",
)),
JsonValue::String(s) => Ok(s.clone()),
_ => Err(curl_refusal(name, "must be a string")),
}
};
let mut argv = Vec::new();
if let Some(method) = args.get("method") {
argv.push("-X".to_string());
argv.push(text("method", method)?);
}
let headers: Vec<&JsonValue> = match args.get("headers") {
None => Vec::new(),
Some(JsonValue::Array(items)) => items.iter().collect(),
Some(single) => vec![single],
};
for header in headers {
let line = text("headers", header)?;
if line.starts_with('@') {
return Err(curl_refusal(
"headers",
"begins with '@', which curl reads as a file of headers",
));
}
argv.push("-H".to_string());
argv.push(line);
}
if let Some(data) = args.get("data") {
let body = match data {
JsonValue::Number(n) => text("data", &JsonValue::String(n.to_string()))?,
other => text("data", other)?,
};
argv.push("--data-raw".to_string());
argv.push(body);
}
let url = match args.get("url") {
Some(value) => text("url", value)?,
None => return Err(curl_refusal("url", "is required")),
};
// Only HTTP(S): curl also reads file://, dict://, gopher:// and others, and
// a file:// URL would return a local file as the tool's output.
let lower = url.to_ascii_lowercase();
if !(lower.starts_with("http://") || lower.starts_with("https://")) {
return Err(curl_refusal("url", "must be an http:// or https:// URL"));
}
argv.push("--".to_string());
argv.push(url);
Ok(argv)
}
fn curl_refusal(param: &str, why: &str) -> anyhow::Error {
mcp_coded(
crate::safety::ErrorCode::BadArg,
format!("curl: '{param}' {why}"),
"pass a value of the declared type that does not begin with '-' (or '@' for headers)",
)
}
const MCP_REMOTE_UNREACHABLE: &str =
"the remote MCP server could not be reached; check the endpoint URL and that the server is running";
const MCP_REMOTE_STATUS: &str =
"the remote MCP server answered with an error status; check the endpoint and the server's logs";
const MCP_REMOTE_BODY: &str =
"the remote MCP server sent a body this client cannot parse; check that it speaks MCP over this endpoint";
/// How long a catalogue tool may run for one `mcp_call` before it is killed.
const MCP_TOOL_TIMEOUT_SECS: u64 = 60;
/// The most output of one stream a tool result carries back to the caller.
const MCP_TOOL_OUTPUT_CAP: usize = 256 * 1024;
/// The longest JSON-RPC request line `ish mcp stdio` reads. A client line was
/// read whole, so one with no newline could exhaust memory.
const MCP_MAX_REQUEST_BYTES: usize = 16 * 1024 * 1024;
// ============================================================================
// MCP Protocol Types
// ============================================================================
/// MCP Tool definition for protocol communication
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpTool {
pub name: String,
pub description: String,
#[serde(rename = "inputSchema")]
pub input_schema: JsonValue,
}
/// MCP Tool call request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolCall {
pub name: String,
pub arguments: HashMap<String, JsonValue>,
}
/// MCP Tool call result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolResult {
pub content: Vec<McpContent>,
#[serde(rename = "isError", skip_serializing_if = "Option::is_none")]
pub is_error: Option<bool>,
}
/// MCP Content block
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum McpContent {
#[serde(rename = "text")]
Text { text: String },
#[serde(rename = "image")]
Image { data: String, mime_type: String },
#[serde(rename = "resource")]
Resource {
uri: String,
mime_type: Option<String>,
},
}
/// MCP Resource definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpResource {
pub uri: String,
pub name: String,
pub description: Option<String>,
#[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
}
/// MCP Prompt definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpPrompt {
pub name: String,
pub description: Option<String>,
pub arguments: Option<Vec<McpPromptArgument>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpPromptArgument {
pub name: String,
pub description: Option<String>,
pub required: Option<bool>,
}
/// MCP Server capabilities
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpCapabilities {
pub tools: Option<McpToolsCapability>,
pub resources: Option<McpResourcesCapability>,
pub prompts: Option<McpPromptsCapability>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolsCapability {
#[serde(rename = "listChanged")]
pub list_changed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpResourcesCapability {
pub subscribe: bool,
#[serde(rename = "listChanged")]
pub list_changed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpPromptsCapability {
#[serde(rename = "listChanged")]
pub list_changed: bool,
}
/// MCP Server information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpServerInfo {
pub name: String,
pub version: String,
}
/// The MCP protocol versions this server speaks, newest first.
pub const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];
/// The protocol version `initialize` answers with: the client's requested
/// version when the server supports it, otherwise the newest version it
/// supports. A missing or unknown request gets the newest.
pub fn negotiate_protocol_version(requested: Option<&str>) -> &'static str {
requested
.and_then(|r| {
SUPPORTED_PROTOCOL_VERSIONS
.iter()
.copied()
.find(|v| *v == r)
})
.unwrap_or(SUPPORTED_PROTOCOL_VERSIONS[0])
}
/// MCP Initialize response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpInitializeResult {
#[serde(rename = "protocolVersion")]
pub protocol_version: String,
pub capabilities: McpCapabilities,
#[serde(rename = "serverInfo")]
pub server_info: McpServerInfo,
}
// ============================================================================
// MCP Server Implementation
// ============================================================================
/// MCP Server configuration
#[derive(Debug, Clone)]
pub struct McpConfig {
/// Maximum safety level allowed for tool execution
pub max_safety_level: SafetyLevel,
/// Whether to allow admin-requiring tools
pub allow_admin_tools: bool,
/// Allowed tool categories (None = all)
pub allowed_categories: Option<Vec<ToolCategory>>,
/// Explicitly blocked tools
pub blocked_tools: Vec<String>,
/// Timeout for tool execution in seconds
pub execution_timeout: u64,
}
impl Default for McpConfig {
fn default() -> Self {
Self {
max_safety_level: SafetyLevel::Caution,
allow_admin_tools: false,
allowed_categories: None,
blocked_tools: vec![
"rm".to_string(),
"del".to_string(),
"format".to_string(),
"dd".to_string(),
],
execution_timeout: 30,
}
}
}
/// IronShell MCP Server
pub struct McpServer {
tools_db: Arc<OSToolsDatabase>,
config: McpConfig,
/// Registered tools (filtered by config)
registered_tools: HashMap<String, McpTool>,
}
impl McpServer {
/// Create a new MCP server with default configuration
pub fn new() -> Self {
Self::with_config(McpConfig::default())
}
/// Create a new MCP server with custom configuration
pub fn with_config(config: McpConfig) -> Self {
let tools_db = Arc::new(OSToolsDatabase::new());
let mut server = Self {
tools_db,
config,
registered_tools: HashMap::new(),
};
server.register_all_tools();
server
}
/// Register all available tools based on configuration
fn register_all_tools(&mut self) {
let current_os = OperatingSystem::current();
for (name, tool) in &self.tools_db.tools {
// Skip blocked tools
if self.config.blocked_tools.contains(name) {
continue;
}
// Check safety level
if !self.is_safety_level_allowed(&tool.safety_level) {
continue;
}
// Check admin requirement
if tool.requires_admin && !self.config.allow_admin_tools {
continue;
}
// Check category filter
if let Some(ref allowed) = self.config.allowed_categories {
if !allowed.contains(&tool.category) {
continue;
}
}
// Check OS compatibility
if !tool.supported_os.contains(¤t_os) {
continue;
}
// Register the tool
self.registered_tools
.insert(name.clone(), self.tool_to_mcp_tool(tool));
}
}
/// Check if a safety level is allowed
fn is_safety_level_allowed(&self, level: &SafetyLevel) -> bool {
match (&self.config.max_safety_level, level) {
(SafetyLevel::Safe, SafetyLevel::Safe) => true,
(SafetyLevel::Caution, SafetyLevel::Safe | SafetyLevel::Caution) => true,
(
SafetyLevel::Dangerous,
SafetyLevel::Safe | SafetyLevel::Caution | SafetyLevel::Dangerous,
) => true,
(SafetyLevel::Critical, _) => true,
_ => false,
}
}
/// Convert an OSTool to MCP tool format
fn tool_to_mcp_tool(&self, tool: &OSTool) -> McpTool {
McpTool {
name: tool.name.clone(),
description: tool.description.clone(),
input_schema: tool.to_openai_function_schema()["function"]["parameters"].clone(),
}
}
/// Handle MCP initialize request
pub fn initialize(&self) -> McpInitializeResult {
McpInitializeResult {
protocol_version: negotiate_protocol_version(None).to_string(),
capabilities: McpCapabilities {
tools: Some(McpToolsCapability { list_changed: true }),
resources: Some(McpResourcesCapability {
subscribe: false,
list_changed: true,
}),
prompts: Some(McpPromptsCapability {
list_changed: false,
}),
},
server_info: McpServerInfo {
name: "ironshell-mcp".to_string(),
version: env!("CARGO_PKG_VERSION").to_string(),
},
}
}
/// List all available tools
pub fn list_tools(&self) -> Vec<McpTool> {
self.registered_tools.values().cloned().collect()
}
/// The name of the compact-mode meta-tool that invokes any builtin by name.
pub const META_INVOKE_TOOL: &'static str = "ironshell";
/// Whether the MCP tool surface is in compact discovery mode (the default).
/// `IRONSHELL_MCP_TOOLS=all` (or `full`) restores the flat per-builtin listing.
fn tools_compact_mode() -> bool {
match std::env::var("IRONSHELL_MCP_TOOLS") {
Ok(v) => !(v.eq_ignore_ascii_case("all") || v.eq_ignore_ascii_case("full")),
Err(_) => true,
}
}
/// Expose IronShell's builtins to an MCP agent. By **default** this is the
/// *compact discovery surface* — three meta-tools instead of ~1k individual
/// tool definitions, which otherwise cost ~26k tokens of standing context every
/// session (measured: `examples/standing_context.rs`). The agent indexes the
/// catalog via `ontology_manifest`, expands a slice with `ontology_describe`,
/// and invokes any builtin through the `ironshell` meta-tool — all routed through
/// [`Self::call_builtin`], so effect policy / approval / jail / audit apply
/// unchanged. Set `IRONSHELL_MCP_TOOLS=all` for the flat, per-builtin `x-effect`
/// listing (every operation's danger level visible up front).
pub fn list_builtin_tools(&self) -> Vec<McpTool> {
if Self::tools_compact_mode() {
Self::compact_discovery_tools()
} else {
Self::full_builtin_tools()
}
}
/// The compact discovery surface (default): `ontology_manifest` +
/// `ontology_describe` (progressive disclosure of the catalog) and the `ironshell`
/// invoke meta-tool. Effect classes remain discoverable per-category in the
/// manifest and per-builtin via describe; enforcement is unchanged on call.
fn compact_discovery_tools() -> Vec<McpTool> {
vec![
McpTool {
name: "ontology_manifest".to_string(),
description: "List IronShell's builtin categories (name, count, effect classes) — the compact index of the full toolset. Call with no args, then ontology_describe(\"<category>\") to expand a slice.".to_string(),
input_schema: serde_json::json!({ "type": "object", "properties": {} }),
},
McpTool {
name: "ontology_describe".to_string(),
description: "Expand one slice of the ontology: a category name -> its builtins (name, signature, effect); or a builtin name -> full detail (params, examples, effect class). Arg: name, a category or builtin name; or args, an array holding that one name.".to_string(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "a category or builtin name" },
"args": { "type": "array", "description": "[query]: a category or builtin name" }
},
}),
},
McpTool {
name: Self::META_INVOKE_TOOL.to_string(),
description: "Invoke any IronShell builtin by name (discover names via ontology_manifest / ontology_describe, and check a builtin's effect class there before invoking a destructive one). Runs under the same effect policy / approval / workspace jail / audit as every builtin.".to_string(),
input_schema: serde_json::json!({
"type": "object",
"properties": {
"name": { "type": "string", "description": "builtin name to invoke; `builtin` is accepted as an alias of `name`" },
"builtin": { "type": "string", "description": "alias of `name`" },
"args": {
"type": ["array", "object"],
"description": "the arguments: an array in parameter order, or an object keyed by parameter name (subject is the piped value)"
}
},
"anyOf": [{ "required": ["name"] }, { "required": ["builtin"] }],
}),
},
]
}
/// The flat per-builtin listing (`IRONSHELL_MCP_TOOLS=all`): every builtin as its
/// own MCP tool, annotated with its safety effect class under `x-effect`.
fn full_builtin_tools() -> Vec<McpTool> {
crate::agent_api::builtin_tool_specs()
.into_iter()
.filter_map(|spec| {
let name = spec.get("name").and_then(|v| v.as_str())?.to_string();
let desc = spec
.get("description")
.and_then(|v| v.as_str())
.unwrap_or("");
let sig = spec.get("signature").and_then(|v| v.as_str()).unwrap_or("");
let effect = spec
.get("effect")
.and_then(|v| v.as_str())
.unwrap_or("pure");
// The proven return shape, when there is one. Lets an agent
// compose against the result without a discovery call first.
let returns = spec.get("returns").and_then(|v| v.as_str());
let mut input_schema = serde_json::json!({
"type": "object",
"properties": {
"args": { "type": "array", "description": "positional arguments" }
},
"x-effect": effect,
});
if let (Some(r), Some(obj)) = (returns, input_schema.as_object_mut()) {
obj.insert("x-returns".to_string(), serde_json::json!(r));
}
Some(McpTool {
name,
description: format!("{} | {}", sig, desc),
input_schema,
})
})
.collect()
}
/// Invoke an IronShell builtin as an MCP tool. `args` is a JSON array of
/// positional arguments. The call goes through `builtins::call`, so guarded
/// builtins enforce policy/approval/jail and emit audit entries; a refusal
/// is returned as an error result carrying the structured `E_*` code.
pub fn call_builtin(&self, name: &str, args: &JsonValue) -> McpToolResult {
let values: Vec<crate::value::Value> = match args {
JsonValue::Array(a) => a.iter().map(crate::value::Value::from_json).collect(),
JsonValue::Null => vec![],
other => vec![crate::value::Value::from_json(other)],
};
self.run_builtin(name, values, None)
}
/// Run a builtin with its values and an optional piped subject, and render
/// the outcome as an MCP result.
fn run_builtin(
&self,
name: &str,
values: Vec<crate::value::Value>,
input: Option<crate::value::Value>,
) -> McpToolResult {
let mut env = crate::env::Env::new();
match crate::builtins::call_with_input(name, values, input, &mut env) {
Ok(v) => {
let v = crate::agent_api::redact_for_agent(v);
// Agent mode mirrors the CLI/HTTP default: tabular results render
// as compact AECON (MCP content is plain text, so no JSON
// re-escaping cost). Scalars keep their display form.
// Deterministic mode (`--deterministic` / IRONSHELL_DETERMINISTIC)
// wins over both, as in `ish -c`: the whole value as canonical JSON,
// byte-stable for equal values.
let text = if crate::agent_api::deterministic_mode() {
crate::builtins::render_canonical(&v).unwrap_or_else(|| "null".to_string())
} else if name == "ontology_describe" {
// The discovery tools speak JSON; the record's display form
// (`{aliases: null, builtin: pick}`) is not.
serde_json::to_string(&v.to_json()).unwrap_or_else(|_| v.to_display_string())
} else if crate::safety::current_mode() == crate::safety::Mode::Agent
&& matches!(
v,
crate::value::Value::Array(_) | crate::value::Value::Table(_)
)
{
let budget = std::env::var("IRONSHELL_TOKEN_BUDGET")
.ok()
.and_then(|s| s.parse::<usize>().ok())
.filter(|m| *m > 0);
crate::builtins::render_agent(&v, budget)
.unwrap_or_else(|| v.to_display_string())
} else {
v.to_display_string()
};
McpToolResult {
content: vec![McpContent::Text { text }],
is_error: Some(false),
}
}
Err(e) => McpToolResult {
content: vec![McpContent::Text {
text: format!("{}", e),
}],
is_error: Some(true),
},
}
}
/// The builtin a call to the `ironshell` meta-tool names, and the key that
/// named it: `name`, or `builtin` as an alias. Empty when neither is a
/// non-empty string.
fn meta_builtin_key(arguments: &JsonValue) -> (&'static str, &str) {
for key in ["name", "builtin"] {
if let Some(s) = arguments.get(key).and_then(JsonValue::as_str) {
if !s.is_empty() {
return (key, s);
}
}
}
("name", "")
}
/// Route an MCP `tools/call` by tool name. The compact-mode `ironshell` meta-tool
/// unwraps `{name, args}` and invokes that builtin; any other name is treated as
/// a builtin invoked with its `args` array. Every path goes through
/// [`Self::call_builtin`], so effect policy / approval / jail / audit apply
/// uniformly whether the agent is in compact or full mode.
pub fn route_tool_call(&self, name: &str, arguments: &JsonValue) -> McpToolResult {
if name == Self::META_INVOKE_TOOL {
let (key, inner) = Self::meta_builtin_key(arguments);
if inner.is_empty() {
return McpToolResult {
content: vec![McpContent::Text {
text: "ironshell: missing 'name' (the builtin to invoke)".to_string(),
}],
is_error: Some(true),
};
}
// With `args`, the builtin's arguments are all in `args`, so a key
// beside it is refused rather than dropped.
if let Some(map) = arguments.as_object() {
if map.contains_key("args") {
if let Some(extra) = map
.keys()
.find(|k| k.as_str() != key && k.as_str() != "args")
{
return Self::unknown_argument("ironshell", extra, "name, args");
}
}
}
let mut rest = arguments.clone();
if let Some(map) = rest.as_object_mut() {
map.remove(key);
}
return self.route_named(inner, &rest);
}
self.route_named(name, arguments)
}
/// Run `name` with MCP `arguments`, in one of three forms:
///
/// - an object with an `args` array: the positional list;
/// - an empty object: no arguments;
/// - any other object: each key is a parameter, by the name the schema
/// advertises (`subject` is the piped value). A builtin with no declared
/// signature has no names to map, so the object is one argument, as before.
///
/// A bare array or `null` is the positional list itself.
fn route_named(&self, name: &str, arguments: &JsonValue) -> McpToolResult {
let Some(map) = arguments.as_object() else {
return self.call_builtin(name, arguments);
};
if let Some(args) = map.get("args") {
if let Some(extra) = map.keys().find(|k| k.as_str() != "args") {
return Self::unknown_argument(name, extra, "args");
}
// An object here is named, as in agent execute: each key is a
// parameter, mapped by the same conversion that `args` objects use.
return match args {
JsonValue::Object(named) => {
match crate::agent_api::named_args_to_positional(name, named) {
Ok(positional) => self.call_builtin(name, &JsonValue::Array(positional)),
Err(e) => McpToolResult {
content: vec![McpContent::Text {
text: format!("{}", e),
}],
is_error: Some(true),
},
}
}
_ => self.call_builtin(name, args),
};
}
if map.is_empty() {
return self.call_builtin(name, &JsonValue::Array(vec![]));
}
let Some(sig) = crate::signature::signature_of(name) else {
return self.call_builtin(name, arguments);
};
match Self::named_arguments(sig, map) {
Ok((input, values)) => self.run_builtin(name, values, input),
Err(e) => McpToolResult {
content: vec![McpContent::Text {
text: format!("{}", e),
}],
is_error: Some(true),
},
}
}
/// The refusal for a key the tool does not take, naming the keys it does.
fn unknown_argument(tool: &str, key: &str, valid: &str) -> McpToolResult {
McpToolResult {
content: vec![McpContent::Text {
text: format!("unknown argument '{key}' for '{tool}'; valid arguments: {valid}"),
}],
is_error: Some(true),
}
}
/// Map a named-argument object onto a declared signature: the `subject`
/// becomes the piped input, and the parameters become the positional values
/// in declaration order. A null is the same as an absent key. A variadic
/// parameter given an array is spread over its values, unless it takes
/// arrays itself. A parameter left out before a later one is refused, since
/// the positions would otherwise shift.
fn named_arguments(
sig: &crate::signature::Signature,
map: &serde_json::Map<String, JsonValue>,
) -> Result<(Option<crate::value::Value>, Vec<crate::value::Value>)> {
use crate::value::Value;
let takes_subject = sig.subject.is_some();
for key in map.keys() {
let known =
(key == "subject" && takes_subject) || sig.params.iter().any(|p| p.name == key);
if !known {
return Err(crate::safety::bad_arg_with_hint(
sig.name,
&sig.render(),
&format!("unknown argument '{key}'"),
"pass each argument under the name the signature gives it",
));
}
}
let input = if takes_subject {
map.get("subject")
.filter(|v| !v.is_null())
.map(Value::from_json)
} else {
None
};
let mut values = Vec::new();
let mut gap: Option<&str> = None;
for p in sig.params {
let Some(v) = map.get(p.name).filter(|v| !v.is_null()) else {
if gap.is_none() {
gap = Some(p.name);
}
continue;
};
if let Some(missing) = gap {
return Err(crate::safety::bad_arg_with_hint(
sig.name,
&sig.render(),
&format!("'{}' given without '{missing}'", p.name),
&format!("give '{missing}' too: parameters are positional"),
));
}
match v {
JsonValue::Array(items) if p.variadic && p.ty != crate::signature::Ty::Array => {
values.extend(items.iter().map(Value::from_json));
}
_ => values.push(Value::from_json(v)),
}
}
Ok((input, values))
}
/// Run a strict **JSON-RPC 2.0 over stdio** MCP server (the canonical MCP
/// transport, complementing the HTTP server). Reads newline-delimited requests
/// from stdin and dispatches:
///
/// - `initialize` → protocol/capabilities/serverInfo;
/// - `tools/list` → the builtin tool surface ([`Self::list_builtin_tools`]);
/// - `tools/call` → routes through [`Self::call_builtin`], so policy / jail /
/// approval / audit apply exactly as on the REPL and HTTP paths;
/// - `ping` → `{}`.
///
/// Writes one JSON-RPC response line per request to stdout. Notifications
/// (messages with no `id`, e.g. `notifications/initialized`) get no reply.
/// Loops until stdin EOF. Runs in whatever safety mode the process is in;
/// `ish mcp stdio` implies agent mode unless `IRONSHELL_MODE` is set.
pub fn serve_stdio(&self) -> std::io::Result<()> {
use std::io::BufRead;
let stdin = std::io::stdin();
let stdout = std::io::stdout();
let mut out = stdout.lock();
let mut handle = stdin.lock();
let mut raw = Vec::new();
loop {
raw.clear();
let limit = MCP_MAX_REQUEST_BYTES as u64 + 1;
if std::io::Read::take(&mut handle, limit).read_until(b'\n', &mut raw)? == 0 {
break; // EOF
}
if raw.len() > MCP_MAX_REQUEST_BYTES && !raw.ends_with(b"\n") {
// Discard the rest of the over-long line, then refuse it.
let mut rest = Vec::new();
loop {
rest.clear();
let n =
std::io::Read::take(&mut handle, 1 << 20).read_until(b'\n', &mut rest)?;
if n == 0 || rest.ends_with(b"\n") {
break;
}
}
Self::write_message(
&mut out,
&Self::rpc_error(
JsonValue::Null,
-32600,
&format!("request longer than {MCP_MAX_REQUEST_BYTES} bytes"),
),
)?;
continue;
}
let buf = String::from_utf8_lossy(&raw);
let line = buf.trim();
if line.is_empty() {
continue;
}
let req: JsonValue = match serde_json::from_str(line) {
Ok(v) => v,
Err(e) => {
Self::write_message(
&mut out,
&Self::rpc_error(JsonValue::Null, -32700, &format!("parse error: {}", e)),
)?;
continue;
}
};
// A repeated key would be resolved to its last value, and a reader
// of the line could take the first: refuse it, as agent execute does.
if let Some(repeated) = crate::agent_api::first_repeated_key(line) {
let id = req.get("id").cloned().unwrap_or(JsonValue::Null);
Self::write_message(
&mut out,
&Self::rpc_error(id, -32600, &format!("duplicate key \"{repeated}\"")),
)?;
continue;
}
if let Some(response) = self.handle_rpc(&req) {
Self::write_message(&mut out, &response)?;
}
}
Ok(())
}
/// Dispatch one JSON-RPC request, returning the response (or `None` for a
/// notification, which gets no reply). Pure w.r.t. I/O so it is unit-testable.
pub fn handle_rpc(&self, req: &JsonValue) -> Option<JsonValue> {
// Notifications carry no `id` → no response.
let id = match req.get("id") {
Some(v) if !v.is_null() => v.clone(),
_ => return None,
};
let method = req.get("method").and_then(|m| m.as_str()).unwrap_or("");
let response = match method {
"initialize" => Self::rpc_ok(id, self.stdio_initialize(req.get("params"))),
"tools/list" => Self::rpc_ok(
id,
serde_json::json!({
"tools": serde_json::to_value(self.list_builtin_tools())
.unwrap_or_else(|_| serde_json::json!([])),
}),
),
"tools/call" => match self.stdio_tools_call(req.get("params")) {
Ok(result) => Self::rpc_ok(id, result),
Err((code, msg, data)) => Self::rpc_error_data(id, code, &msg, data),
},
"ping" => Self::rpc_ok(id, serde_json::json!({})),
other => Self::rpc_error(id, -32601, &format!("method not found: {}", other)),
};
Some(response)
}
fn stdio_initialize(&self, params: Option<&JsonValue>) -> JsonValue {
let requested = params
.and_then(|p| p.get("protocolVersion"))
.and_then(JsonValue::as_str);
serde_json::json!({
"protocolVersion": negotiate_protocol_version(requested),
"capabilities": { "tools": { "listChanged": false } },
"serverInfo": { "name": "ironshell", "version": env!("CARGO_PKG_VERSION") },
})
}
/// Handle a `tools/call`: extract the tool name and positional args
/// (`arguments.args` if present, else the whole `arguments`), route through
/// `call_builtin`, and serialize the [`McpToolResult`].
///
/// A name that is neither the `ironshell` meta-tool nor a builtin is a
/// protocol error (`-32602`), not a tool result: the call never reached a
/// tool. Its did-you-mean suggestions go in `error.data`.
fn stdio_tools_call(
&self,
params: Option<&JsonValue>,
) -> Result<JsonValue, (i64, String, Option<JsonValue>)> {
let params = params.ok_or((-32602, "missing params".to_string(), None))?;
let name = params.get("name").and_then(|v| v.as_str()).ok_or((
-32602,
"missing tool name".to_string(),
None,
))?;
if name != Self::META_INVOKE_TOOL && !crate::builtins::is_served(name) {
let suggestions = crate::builtins::did_you_mean(name);
let data = (!suggestions.is_empty())
.then(|| json!({ "code": "E_UNKNOWN_BUILTIN", "did_you_mean": suggestions }));
return Err((-32602, format!("unknown tool: {}", name), data));
}
let arguments = params
.get("arguments")
.cloned()
.unwrap_or_else(|| JsonValue::Array(vec![]));
// The meta-tool without a builtin name is a protocol error too, in the
// same error object as an unknown tool, not a tool result.
if name == Self::META_INVOKE_TOOL && Self::meta_builtin_key(&arguments).1.is_empty() {
return Err((
-32602,
"ironshell: missing 'name' (the builtin to invoke)".to_string(),
Some(json!({ "code": "E_BAD_ARG" })),
));
}
let result = self.route_tool_call(name, &arguments);
serde_json::to_value(result).map_err(|e| (-32603, format!("serialize result: {}", e), None))
}
fn rpc_ok(id: JsonValue, result: JsonValue) -> JsonValue {
serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result })
}
fn rpc_error(id: JsonValue, code: i64, message: &str) -> JsonValue {
Self::rpc_error_data(id, code, message, None)
}
fn rpc_error_data(
id: JsonValue,
code: i64,
message: &str,
data: Option<JsonValue>,
) -> JsonValue {
let mut error = serde_json::json!({ "code": code, "message": message });
if let (Some(data), Some(obj)) = (data, error.as_object_mut()) {
obj.insert("data".to_string(), data);
}
serde_json::json!({ "jsonrpc": "2.0", "id": id, "error": error })
}
fn write_message(out: &mut impl std::io::Write, msg: &JsonValue) -> std::io::Result<()> {
let s = serde_json::to_string(msg).unwrap_or_else(|_| "{}".to_string());
writeln!(out, "{}", s)?;
out.flush()
}
/// Get a specific tool by name
pub fn get_tool(&self, name: &str) -> Option<&McpTool> {
self.registered_tools.get(name)
}
/// Call a tool with arguments
pub fn call_tool(&self, call: McpToolCall) -> McpToolResult {
// Check if tool exists
let tool = match self.tools_db.get_tool(&call.name) {
Some(t) => t,
None => {
return McpToolResult {
content: vec![McpContent::Text {
text: format!("Tool '{}' not found", call.name),
}],
is_error: Some(true),
};
}
};
// Check if tool is registered (passes safety checks)
if !self.registered_tools.contains_key(&call.name) {
return McpToolResult {
content: vec![McpContent::Text {
text: format!(
"Tool '{}' is not available (blocked by security policy)",
call.name
),
}],
is_error: Some(true),
};
}
// Execute the tool
match self.execute_tool(tool, &call.arguments) {
Ok(output) => McpToolResult {
content: vec![McpContent::Text { text: output }],
is_error: Some(false),
},
Err(e) => McpToolResult {
content: vec![McpContent::Text {
text: format!("Tool execution failed: {}", e),
}],
is_error: Some(true),
},
}
}
/// Execute a tool with the given arguments.
///
/// Every route to an OS tool ends in `call_tool` and then here (the HTTP
/// server, `mcp_call` and the tests), so the argument checks and the effect
/// gate live in this one place rather than at each caller. Both run before
/// anything is spawned.
fn execute_tool(&self, tool: &OSTool, args: &HashMap<String, JsonValue>) -> Result<String> {
// Malformed input is refused first, so a bad call never reaches the
// approval step.
validate_tool_args(tool, args)?;
// The effect gate every program-running builtin passes (see
// `safety::guard_exec`). The targets are the program and the caller's
// argument values; the blast radius is the argument object. In agent
// mode this returns E_NEEDS_APPROVAL unless the call is approved.
let cmd_name = tool.command_for_current_os();
let mut targets = vec![cmd_name.clone()];
let mut keys: Vec<&String> = args.keys().collect();
keys.sort();
for key in keys {
targets.push(match &args[key] {
JsonValue::String(s) => s.clone(),
other => other.to_string(),
});
}
crate::safety::guard(crate::safety::GuardCtx {
builtin: &tool.name,
effect: crate::safety::Effect::Exec,
what: "exec",
targets,
blast_radius: serde_json::to_value(args).unwrap_or(JsonValue::Null),
reversible: false,
// The targets are a program and its arguments, not a jailed path.
fs_paths: false,
})?;
// Build command
let mut cmd = crate::safety::child_command(&cmd_name);
if tool.name == "curl" {
// curl's declared parameters map to its own flags; see `curl_argv`.
for arg in curl_argv(args)? {
cmd.arg(arg);
}
} else {
// Add arguments based on tool parameters. Values were validated above:
// strings are never option-like and enum parameters hold a declared value.
for param in &tool.parameters {
if let Some(value) = args.get(¶m.name) {
match value {
JsonValue::String(s) => {
cmd.arg(s);
}
JsonValue::Bool(true) => {
// Add flag for boolean true
if let Some(ref default) = param.default_value {
if default == "false" {
// This is a flag that should be added
let flag =
format!("-{}", param.name.chars().next().unwrap_or('?'));
cmd.arg(flag);
}
}
}
JsonValue::Number(n) => {
cmd.arg(n.to_string());
}
JsonValue::Array(arr) => {
for item in arr {
if let JsonValue::String(s) = item {
cmd.arg(s);
}
}
}
_ => {}
}
}
}
}
// A tool that hangs must not hang the caller. `Command::output` waited
// forever; the deadline below kills it.
let output =
crate::safety::output_with_timeout(cmd, MCP_TOOL_TIMEOUT_SECS).map_err(|e| {
crate::safety::io_budget_error(&e)
.unwrap_or_else(|| crate::safety::spawn_error("mcp_call", &cmd_name, &e))
})?;
// Output is capped as well: a tool that printed without limit filled the
// agent's context with it.
let capped = |bytes: &[u8]| -> String {
let take = bytes.len().min(MCP_TOOL_OUTPUT_CAP);
let mut text = String::from_utf8_lossy(&bytes[..take]).into_owned();
if bytes.len() > take {
text.push_str(&format!(
"\n[output truncated at {MCP_TOOL_OUTPUT_CAP} bytes; {} bytes dropped]",
bytes.len() - take
));
}
text
};
let stdout = capped(&output.stdout);
let stderr = capped(&output.stderr);
if output.status.success() {
Ok(stdout)
} else {
if stderr.is_empty() {
Ok(stdout)
} else {
Err(crate::safety::tool_failed(
"mcp_call",
&cmd_name,
output.status.code(),
&stderr,
))
}
}
}
/// List available resources
pub fn list_resources(&self) -> Vec<McpResource> {
vec![
McpResource {
uri: "ironshell://tools".to_string(),
name: "Available Tools".to_string(),
description: Some("List of all available OS tools".to_string()),
mime_type: Some("application/json".to_string()),
},
McpResource {
uri: "ironshell://categories".to_string(),
name: "Tool Categories".to_string(),
description: Some("List of tool categories".to_string()),
mime_type: Some("application/json".to_string()),
},
McpResource {
uri: "ironshell://system-info".to_string(),
name: "System Information".to_string(),
description: Some("Current system information".to_string()),
mime_type: Some("application/json".to_string()),
},
]
}
/// Read a resource
pub fn read_resource(&self, uri: &str) -> Result<McpContent> {
match uri {
"ironshell://tools" => {
let tools: Vec<_> = self.registered_tools.keys().collect();
Ok(McpContent::Text {
text: serde_json::to_string_pretty(&tools)?,
})
}
"ironshell://categories" => {
let categories: Vec<_> = self.tools_db.categories.keys().collect();
Ok(McpContent::Text {
text: serde_json::to_string_pretty(&categories)?,
})
}
"ironshell://system-info" => {
let info = json!({
"os": format!("{:?}", OperatingSystem::current()),
"tool_count": self.registered_tools.len(),
"server_version": env!("CARGO_PKG_VERSION"),
});
Ok(McpContent::Text {
text: serde_json::to_string_pretty(&info)?,
})
}
_ => Err(anyhow!("Unknown resource: {}", uri)),
}
}
/// List available prompts
pub fn list_prompts(&self) -> Vec<McpPrompt> {
vec![
McpPrompt {
name: "find-tool".to_string(),
description: Some("Find the best tool for a task".to_string()),
arguments: Some(vec![McpPromptArgument {
name: "task".to_string(),
description: Some("Description of the task to accomplish".to_string()),
required: Some(true),
}]),
},
McpPrompt {
name: "explain-tool".to_string(),
description: Some("Get detailed explanation of a tool".to_string()),
arguments: Some(vec![McpPromptArgument {
name: "tool_name".to_string(),
description: Some("Name of the tool to explain".to_string()),
required: Some(true),
}]),
},
]
}
/// Get a prompt
pub fn get_prompt(
&self,
name: &str,
args: &HashMap<String, String>,
) -> Result<Vec<McpContent>> {
match name {
"find-tool" => {
let task = args
.get("task")
.ok_or_else(|| anyhow!("Missing 'task' argument"))?;
let tools = self.search_tools_for_task(task);
let response = format!(
"Based on the task '{}', here are the recommended tools:\n\n{}",
task,
tools
.iter()
.map(|t| format!("- **{}**: {}", t.name, t.description))
.collect::<Vec<_>>()
.join("\n")
);
Ok(vec![McpContent::Text { text: response }])
}
"explain-tool" => {
let tool_name = args
.get("tool_name")
.ok_or_else(|| anyhow!("Missing 'tool_name' argument"))?;
let tool = self
.tools_db
.get_tool(tool_name)
.ok_or_else(|| anyhow!("Tool '{}' not found", tool_name))?;
let explanation = format!(
"# {}\n\n{}\n\n## Category\n{:?}\n\n## Safety Level\n{:?}\n\n## Examples\n{}\n\n## Parameters\n{}",
tool.name,
tool.description,
tool.category,
tool.safety_level,
tool.examples.iter()
.map(|e| format!("- `{}` - {}", e.command, e.description))
.collect::<Vec<_>>()
.join("\n"),
tool.parameters.iter()
.map(|p| format!("- **{}** ({:?}): {}", p.name, p.param_type, p.description))
.collect::<Vec<_>>()
.join("\n")
);
Ok(vec![McpContent::Text { text: explanation }])
}
_ => Err(anyhow!("Unknown prompt: {}", name)),
}
}
/// Search tools relevant to a task description
fn search_tools_for_task(&self, task: &str) -> Vec<&McpTool> {
let task_lower = task.to_lowercase();
let keywords: Vec<&str> = task_lower.split_whitespace().collect();
let mut scored_tools: Vec<(&McpTool, usize)> = self
.registered_tools
.values()
.map(|tool| {
let tool_text = format!("{} {}", tool.name, tool.description).to_lowercase();
let score = keywords.iter().filter(|kw| tool_text.contains(*kw)).count();
(tool, score)
})
.filter(|(_, score)| *score > 0)
.collect();
scored_tools.sort_by(|a, b| b.1.cmp(&a.1));
scored_tools
.into_iter()
.take(5)
.map(|(tool, _)| tool)
.collect()
}
/// Get all tools for a category
pub fn get_tools_by_category(&self, category: &ToolCategory) -> Vec<&McpTool> {
self.registered_tools
.values()
.filter(|tool| {
if let Some(os_tool) = self.tools_db.get_tool(&tool.name) {
os_tool.category == *category
} else {
false
}
})
.collect()
}
/// Get tool count
pub fn tool_count(&self) -> usize {
self.registered_tools.len()
}
/// Get the underlying tools database
pub fn tools_db(&self) -> &OSToolsDatabase {
&self.tools_db
}
}
impl Default for McpServer {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// MCP Client for connecting to external MCP servers
// ============================================================================
/// MCP Client for connecting to external MCP servers
pub struct McpClient {
endpoint: String,
client: reqwest::blocking::Client,
}
impl McpClient {
/// Create a new MCP client
pub fn new(endpoint: &str) -> Self {
crate::tls::install_provider();
Self {
endpoint: endpoint.trim_end_matches('/').to_string(),
client: reqwest::blocking::Client::builder()
.timeout(std::time::Duration::from_secs(30))
.build()
.expect("Failed to create HTTP client"),
}
}
/// Initialize connection to MCP server
pub fn initialize(&self) -> Result<McpInitializeResult> {
let url = format!("{}/mcp/v1/initialize", self.endpoint);
let response = self
.client
.post(&url)
.json(&json!({
"protocolVersion": "2024-11-05",
"capabilities": {},
"clientInfo": {
"name": "ironshell",
"version": env!("CARGO_PKG_VERSION")
}
}))
.send()
.map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to connect to MCP server: {}", e),
MCP_REMOTE_UNREACHABLE,
)
})?;
if !response.status().is_success() {
return Err(mcp_coded(
crate::safety::ErrorCode::Io,
format!("MCP server returned error: {}", response.status()),
MCP_REMOTE_STATUS,
));
}
response.json().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to parse response: {}", e),
MCP_REMOTE_BODY,
)
})
}
/// List tools from remote MCP server
pub fn list_tools(&self) -> Result<Vec<McpTool>> {
let url = format!("{}/mcp/v1/tools/list", self.endpoint);
let response = self.client.get(&url).send().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to list tools: {}", e),
MCP_REMOTE_UNREACHABLE,
)
})?;
if !response.status().is_success() {
return Err(mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to list tools: {}", response.status()),
MCP_REMOTE_STATUS,
));
}
#[derive(Deserialize)]
struct ToolsResponse {
tools: Vec<McpTool>,
}
let result: ToolsResponse = response.json().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to parse tools: {}", e),
MCP_REMOTE_BODY,
)
})?;
Ok(result.tools)
}
/// Call a tool on remote MCP server
pub fn call_tool(
&self,
name: &str,
arguments: HashMap<String, JsonValue>,
) -> Result<McpToolResult> {
let url = format!("{}/mcp/v1/tools/call", self.endpoint);
let response = self
.client
.post(&url)
.json(&json!({
"name": name,
"arguments": arguments
}))
.send()
.map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to call tool: {}", e),
MCP_REMOTE_UNREACHABLE,
)
})?;
if !response.status().is_success() {
return Err(mcp_coded(
crate::safety::ErrorCode::Io,
format!("Tool call failed: {}", response.status()),
MCP_REMOTE_STATUS,
));
}
response.json().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to parse result: {}", e),
MCP_REMOTE_BODY,
)
})
}
/// List resources from remote MCP server
pub fn list_resources(&self) -> Result<Vec<McpResource>> {
let url = format!("{}/mcp/v1/resources/list", self.endpoint);
let response = self.client.get(&url).send().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to list resources: {}", e),
MCP_REMOTE_UNREACHABLE,
)
})?;
if !response.status().is_success() {
return Err(mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to list resources: {}", response.status()),
MCP_REMOTE_STATUS,
));
}
#[derive(Deserialize)]
struct ResourcesResponse {
resources: Vec<McpResource>,
}
let result: ResourcesResponse = response.json().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to parse resources: {}", e),
MCP_REMOTE_BODY,
)
})?;
Ok(result.resources)
}
/// Read a resource from remote MCP server
pub fn read_resource(&self, uri: &str) -> Result<Vec<McpContent>> {
let url = format!("{}/mcp/v1/resources/read", self.endpoint);
let response = self
.client
.post(&url)
.json(&json!({ "uri": uri }))
.send()
.map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to read resource: {}", e),
MCP_REMOTE_UNREACHABLE,
)
})?;
if !response.status().is_success() {
return Err(mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to read resource: {}", response.status()),
MCP_REMOTE_STATUS,
));
}
#[derive(Deserialize)]
struct ReadResponse {
contents: Vec<McpContent>,
}
let result: ReadResponse = response.json().map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::Io,
format!("Failed to parse resource: {}", e),
MCP_REMOTE_BODY,
)
})?;
Ok(result.contents)
}
}
// ============================================================================
// Helper Functions
// ============================================================================
/// Create an MCP server with all tools (maximum safety)
pub fn create_full_mcp_server() -> McpServer {
McpServer::with_config(McpConfig {
max_safety_level: SafetyLevel::Critical,
allow_admin_tools: true,
allowed_categories: None,
blocked_tools: vec![],
execution_timeout: 60,
})
}
/// Create an MCP server with safe tools only
pub fn create_safe_mcp_server() -> McpServer {
McpServer::with_config(McpConfig {
max_safety_level: SafetyLevel::Safe,
allow_admin_tools: false,
allowed_categories: None,
blocked_tools: vec![],
execution_timeout: 30,
})
}
/// Create an MCP server for specific categories
pub fn create_category_mcp_server(categories: Vec<ToolCategory>) -> McpServer {
McpServer::with_config(McpConfig {
max_safety_level: SafetyLevel::Caution,
allow_admin_tools: false,
allowed_categories: Some(categories),
blocked_tools: vec![],
execution_timeout: 30,
})
}
// ============================================================================
// MCP HTTP Server (for `ish mcp serve`)
// ============================================================================
#[cfg(feature = "native")]
pub mod server {
use super::*;
use axum::{
extract::State,
http::{header, StatusCode},
response::IntoResponse,
routing::{get, post},
Json, Router,
};
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tower_http::cors::{Any, CorsLayer};
use tower_http::timeout::TimeoutLayer;
/// MCP HTTP Server configuration
#[derive(Debug, Clone)]
pub struct McpServerConfig {
pub host: String,
pub port: u16,
pub enable_cors: bool,
/// Bearer token required on every route except `/health`.
///
/// `None` mints one at startup and prints it -- the server is never
/// reachable without a credential, matching `agent_api`.
pub auth_token: Option<String>,
pub safety_level: SafetyLevel,
pub allow_admin: bool,
}
impl Default for McpServerConfig {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 3001,
// Off by default. `allow_origin(Any)` on a server that executes
// builtins means any page the user visits can drive it; a
// library caller taking Default should not opt into that
// silently.
enable_cors: false,
auth_token: None,
safety_level: SafetyLevel::Caution,
allow_admin: false,
}
}
}
/// Shared state for the HTTP server
//
// No lock: the server never mutates the tool set after startup, and a read
// guard held across a blocking tool call would stall any writer for the
// length of that call.
struct AppState {
mcp: Arc<McpServer>,
}
/// A request may wait this long on a tool before the caller gets 408. It
/// sits above the tool's own deadline so an ordinary timeout still comes
/// back as the tool's coded error.
const MCP_REQUEST_TIMEOUT: Duration = Duration::from_secs(90);
/// Requests in flight at once. Each can hold a blocking-pool thread for up
/// to the tool deadline.
const MCP_MAX_CONCURRENT_REQUESTS: usize = 16;
/// How long a request waits for a slot before it is answered 503.
const MCP_QUEUE_WAIT: Duration = Duration::from_secs(30);
/// Start the MCP HTTP server
/// Mint a bearer token, matching `agent_api`'s construction.
fn generate_mcp_token() -> Result<String> {
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
let mut bytes = [0u8; 32];
crate::safety::ic_fill_random("mcp", &mut bytes)?;
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
/// Constant-time comparison, so a token cannot be recovered a byte at a
/// time by timing the response.
fn mcp_tokens_match(presented: &str, expected: &str) -> bool {
let (a, b) = (presented.as_bytes(), expected.as_bytes());
if a.len() != b.len() {
return false;
}
let mut diff = 0u8;
for (x, y) in a.iter().zip(b.iter()) {
diff |= x ^ y;
}
diff == 0
}
pub async fn start_mcp_server(config: McpServerConfig) -> Result<()> {
// Resolved first so the bind is refused before anything else happens --
// in particular before a bearer token is minted and printed for a server
// that is not going to start.
let addr: SocketAddr = format!("{}:{}", config.host, config.port)
.parse()
.map_err(|e| {
mcp_coded(
crate::safety::ErrorCode::BadArg,
format!("Invalid address: {}", e),
"pass a host and port that form a socket address, such as 127.0.0.1:3002",
)
})?;
// A non-loopback bind is now opt-in rather than merely warned about.
// Warning is the right response to a risk the operator chose; this one
// is more often an accident (`--host 0.0.0.0` copied from a tutorial),
// and the consequence is builtin execution plus a plaintext bearer
// token exposed to the network. TLS would protect the token in transit
// but not the decision to expose the endpoint at all, which is the part
// actually worth a deliberate act.
if !addr.ip().is_loopback()
&& !matches!(
std::env::var("IRONSHELL_ALLOW_REMOTE_BIND").as_deref(),
Ok("1") | Ok("true")
)
{
return Err(crate::safety::policy_deny(
"mcp",
format!(
concat!(
"refusing to bind {} - this server executes builtins over ",
"plaintext HTTP, so binding beyond loopback exposes both the ",
"operations and the bearer token to anything that can route ",
"here. If that is genuinely intended, set ",
"IRONSHELL_ALLOW_REMOTE_BIND=true; prefer an SSH tunnel or a ",
"reverse proxy terminating TLS."
),
addr.ip()
),
"bind to 127.0.0.1, or set IRONSHELL_ALLOW_REMOTE_BIND=true if this exposure is intended",
));
}
let mcp_config = McpConfig {
max_safety_level: config.safety_level.clone(),
allow_admin_tools: config.allow_admin,
allowed_categories: None,
blocked_tools: vec![],
execution_timeout: 30,
};
let mcp = McpServer::with_config(mcp_config);
let state = Arc::new(AppState { mcp: Arc::new(mcp) });
let mut app = Router::new()
// MCP Protocol endpoints
.route("/mcp/v1/initialize", post(handle_initialize))
.route("/mcp/v1/tools", get(handle_list_tools))
.route("/mcp/v1/builtins", get(handle_list_builtin_tools))
.route("/mcp/v1/tools/:name/execute", post(handle_call_tool))
.route("/mcp/v1/resources", get(handle_list_resources))
.route("/mcp/v1/resources/:uri", get(handle_read_resource))
.route("/mcp/v1/prompts", get(handle_list_prompts))
.route("/mcp/v1/prompts/:name", post(handle_get_prompt))
// Health check
.route("/health", get(handle_health))
// Info endpoint
.route("/", get(handle_info))
.with_state(state);
// The same admission scheme as agent_api: a per-request deadline, then
// one semaphore shared by every route. Both sit inside the auth layer
// added below, so an unauthenticated request never waits for a slot.
app = app.layer(TimeoutLayer::new(MCP_REQUEST_TIMEOUT));
let permits = Arc::new(tokio::sync::Semaphore::new(MCP_MAX_CONCURRENT_REQUESTS));
app = app.layer(axum::middleware::from_fn(move |req, next| {
crate::agent_api::server::admit(
permits.clone(),
MCP_MAX_CONCURRENT_REQUESTS,
MCP_QUEUE_WAIT,
req,
next,
)
}));
// Security headers. These servers return JSON, never a page, so the
// policy is simply "this is not a document": no sniffing, no framing,
// no subresources, no referrer. `no-store` because responses routinely
// carry file contents and command output that should not sit in an
// intermediary cache.
app = app.layer(axum::middleware::from_fn(
|req: axum::extract::Request, next: axum::middleware::Next| async move {
let mut res = next.run(req).await;
let h = res.headers_mut();
h.insert(
"x-content-type-options",
header::HeaderValue::from_static("nosniff"),
);
h.insert("x-frame-options", header::HeaderValue::from_static("DENY"));
h.insert(
"content-security-policy",
header::HeaderValue::from_static("default-src 'none'; frame-ancestors 'none'"),
);
h.insert(
"referrer-policy",
header::HeaderValue::from_static("no-referrer"),
);
h.insert(
"cache-control",
header::HeaderValue::from_static("no-store"),
);
res
},
));
// Authentication, applied before CORS so it wraps every route.
//
// This server had none, and `POST /mcp/v1/tools/:name/execute` runs
// builtins. With `--cors` that was demonstrably exploitable: a page on
// https://evil.example POSTed here and read `C:/Windows/win.ini` off
// the disk, cross-origin, unauthenticated. `agent_api` carries a
// comment explaining that its own `allow_origin(Any)` is only tolerable
// *because* a bearer token is required -- the reasoning was right there
// and this server did not have the token.
//
// Loopback binding is not a defence: the browser making the request is
// on the same machine, which is the entire point of the CORS control.
let token = Arc::new(match config.auth_token.clone() {
Some(t) if !t.trim().is_empty() => t,
_ => {
let t = generate_mcp_token()?;
println!("MCP bearer token: {t}");
println!(
"Send it as `Authorization: Bearer <token>` on every route except /health."
);
t
}
});
let auth_token = Arc::clone(&token);
app = app.layer(axum::middleware::from_fn(
move |req: axum::extract::Request, next: axum::middleware::Next| {
let expected = Arc::clone(&auth_token);
async move {
if req.uri().path() == "/health" {
return next.run(req).await;
}
let presented = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(str::trim)
.unwrap_or("");
if mcp_tokens_match(presented, &expected) {
next.run(req).await
} else {
(
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
Json(serde_json::json!({
"error": "unauthorized",
"detail": "Send `Authorization: Bearer <token>`. The token is printed when the server starts.",
})),
)
.into_response()
}
}
},
));
if config.enable_cors {
app = app.layer(
CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any),
);
}
if !addr.ip().is_loopback() {
println!(
"⚠Binding {} — this server executes builtins, so it is now
âš reachable by anything that can route to this host. The bearer
âš token is the only thing standing in front of it, and it travels
âš in plaintext over HTTP: anything on the path can read it.",
addr.ip()
);
}
if config.enable_cors {
println!(
"âš CORS is enabled: any web page the user visits may call this
âš server from their browser. It is safe only because the bearer
âš token is required and a cross-origin page cannot read it."
);
}
println!("🚀 IronShell MCP Server starting on http://{}", addr);
println!(" Protocol: MCP {}", SUPPORTED_PROTOCOL_VERSIONS[0]);
println!(" Safety level: {:?}", config.safety_level);
// MCP's own `--safety` level gates which *tools* are exposed. It is a
// different question from the effect gate and the workspace jail, which
// are keyed on the execution mode, so both are printed.
match crate::safety::current_mode() {
crate::safety::Mode::Agent => println!(
" Effect gate: agent mode — writes confined to {}",
crate::safety::workspace_root().display()
),
other => println!(
"⚠Effect gate: {other:?} mode (IRONSHELL_MODE set explicitly) — OFF. Unset IRONSHELL_MODE to get the agent profile."
),
}
println!();
println!("Endpoints:");
println!(" POST /mcp/v1/initialize - Initialize MCP session");
println!(" GET /mcp/v1/tools - List available tools");
println!(" POST /mcp/v1/tools/:name - Execute a tool");
println!(" GET /mcp/v1/resources - List resources");
println!(" GET /mcp/v1/prompts - List prompts");
println!(" GET /health - Health check");
println!();
let listener = tokio::net::TcpListener::bind(addr).await?;
crate::serve::serve_until(
listener,
app,
crate::serve::shutdown_signal(),
crate::serve::DRAIN,
)
.await?;
Ok(())
}
// Handler implementations
async fn handle_info() -> impl IntoResponse {
Json(json!({
"name": "ironshell-mcp",
"version": env!("CARGO_PKG_VERSION"),
"protocol": format!("MCP {}", SUPPORTED_PROTOCOL_VERSIONS[0]),
"description": "IronShell Model Context Protocol Server"
}))
}
async fn handle_health() -> impl IntoResponse {
Json(json!({
"status": "healthy",
"version": env!("CARGO_PKG_VERSION")
}))
}
async fn handle_initialize(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let mcp = &state.mcp;
Json(mcp.initialize())
}
async fn handle_list_tools(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let mcp = &state.mcp;
Json(json!({
"tools": mcp.list_tools()
}))
}
/// Discover IronShell builtins as MCP tools (effect-tagged). Kept separate
/// from `/tools` so the OS-tool list stays small; builtins are executed via
/// the same `/tools/:name/execute` route (it falls back to builtins).
async fn handle_list_builtin_tools(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let mcp = &state.mcp;
Json(json!({
"tools": mcp.list_builtin_tools()
}))
}
#[derive(Deserialize)]
struct ToolCallRequest {
arguments: HashMap<String, JsonValue>,
}
async fn handle_call_tool(
State(state): State<Arc<AppState>>,
axum::extract::Path(name): axum::extract::Path<String>,
Json(payload): Json<ToolCallRequest>,
) -> impl IntoResponse {
// If `name` is a registered OS tool, run it; otherwise treat it as an
// IronShell builtin and route through the safety-guarded dispatch
// (effect policy, approval, jail, audit all apply). Builtin args come
// from the conventional `args` array in the request.
//
// Running a tool blocks on a child process for up to its deadline, so it
// runs on the blocking pool rather than an async worker.
let mcp = Arc::clone(&state.mcp);
let result = tokio::task::spawn_blocking(move || {
if mcp.get_tool(&name).is_some() {
mcp.call_tool(McpToolCall {
name,
arguments: payload.arguments,
})
} else {
let arguments = serde_json::json!(payload.arguments);
mcp.route_tool_call(&name, &arguments)
}
})
.await
.unwrap_or_else(|e| McpToolResult {
content: vec![McpContent::Text {
text: format!("tool task failed: {e}"),
}],
is_error: Some(true),
});
if result.is_error.unwrap_or(false) {
(StatusCode::BAD_REQUEST, Json(result))
} else {
(StatusCode::OK, Json(result))
}
}
async fn handle_list_resources(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let mcp = &state.mcp;
Json(json!({
"resources": mcp.list_resources()
}))
}
async fn handle_read_resource(
State(state): State<Arc<AppState>>,
axum::extract::Path(uri): axum::extract::Path<String>,
) -> impl IntoResponse {
let mcp = &state.mcp;
// URL decode the URI
let decoded_uri = urlencoding::decode(&uri)
.map(|s| s.into_owned())
.unwrap_or(uri);
match mcp.read_resource(&decoded_uri) {
Ok(content) => (StatusCode::OK, Json(json!({ "content": content }))),
Err(e) => (
StatusCode::NOT_FOUND,
Json(json!({ "error": e.to_string() })),
),
}
}
async fn handle_list_prompts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let mcp = &state.mcp;
Json(json!({
"prompts": mcp.list_prompts()
}))
}
#[derive(Deserialize)]
struct PromptRequest {
arguments: HashMap<String, String>,
}
async fn handle_get_prompt(
State(state): State<Arc<AppState>>,
axum::extract::Path(name): axum::extract::Path<String>,
Json(payload): Json<PromptRequest>,
) -> impl IntoResponse {
let mcp = &state.mcp;
match mcp.get_prompt(&name, &payload.arguments) {
Ok(content) => (StatusCode::OK, Json(json!({ "messages": content }))),
Err(e) => (
StatusCode::BAD_REQUEST,
Json(json!({ "error": e.to_string() })),
),
}
}
}
// ============================================================================
// Tests
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mcp_server_creation() {
let server = McpServer::new();
assert!(server.tool_count() > 0);
}
#[test]
fn test_mcp_initialize() {
let server = McpServer::new();
let result = server.initialize();
assert_eq!(result.protocol_version, "2025-06-18");
assert_eq!(result.server_info.name, "ironshell-mcp");
}
#[test]
fn test_mcp_list_tools() {
let server = McpServer::new();
let tools = server.list_tools();
assert!(!tools.is_empty());
}
#[test]
fn test_mcp_get_tool() {
let server = create_full_mcp_server();
// ls should be available on Unix-like systems
#[cfg(not(windows))]
{
let tool = server.get_tool("ls");
assert!(tool.is_some());
}
#[cfg(windows)]
{
let tool = server.get_tool("dir");
assert!(tool.is_some());
}
}
#[test]
fn test_mcp_list_resources() {
let server = McpServer::new();
let resources = server.list_resources();
assert!(!resources.is_empty());
}
#[test]
fn test_mcp_list_prompts() {
let server = McpServer::new();
let prompts = server.list_prompts();
assert_eq!(prompts.len(), 2);
}
#[test]
fn test_safe_server_blocks_dangerous() {
let server = create_safe_mcp_server();
// Dangerous tools should not be registered
assert!(server.get_tool("nmap").is_none());
}
#[test]
fn test_full_server_allows_all() {
let server = create_full_mcp_server();
// Should have more tools than safe server
let safe_server = create_safe_mcp_server();
assert!(server.tool_count() >= safe_server.tool_count());
}
#[test]
fn test_category_filter() {
let server = create_category_mcp_server(vec![ToolCategory::TextProcessing]);
let tools = server.list_tools();
// Should only have text processing tools
for tool in &tools {
let os_tool = server.tools_db().get_tool(&tool.name).unwrap();
assert_eq!(os_tool.category, ToolCategory::TextProcessing);
}
}
#[test]
fn test_search_tools_for_task() {
let server = McpServer::new();
let tools = server.search_tools_for_task("search for text in files");
assert!(!tools.is_empty());
}
fn args_of(pairs: &[(&str, JsonValue)]) -> HashMap<String, JsonValue> {
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.clone()))
.collect()
}
fn strings(items: &[&str]) -> Vec<String> {
items.iter().map(|s| s.to_string()).collect()
}
#[test]
fn curl_maps_declared_parameters_to_flags_with_the_url_last() {
let args = args_of(&[
("url", json!("https://api.example.com/data")),
("method", json!("POST")),
(
"headers",
json!(["Content-Type: application/json", "Accept: */*"]),
),
("data", json!("{\"key\":\"value\"}")),
]);
let argv = curl_argv(&args).expect("a well-formed call builds");
assert_eq!(
argv,
strings(&[
"-X",
"POST",
"-H",
"Content-Type: application/json",
"-H",
"Accept: */*",
"--data-raw",
"{\"key\":\"value\"}",
"--",
"https://api.example.com/data",
])
);
}
#[test]
fn curl_refuses_a_url_that_is_not_http() {
for url in [
"file:///etc/passwd",
"FILE:///c:/windows/win.ini",
"gopher://127.0.0.1:6379/_x",
"dict://127.0.0.1:11211/stat",
"example.com",
] {
let args = args_of(&[("url", json!(url))]);
assert!(curl_argv(&args).is_err(), "{url} must not reach curl");
}
assert!(curl_argv(&args_of(&[("url", json!("HTTPS://example.com"))])).is_ok());
}
#[test]
fn curl_with_only_a_url_is_a_plain_get() {
let argv = curl_argv(&args_of(&[("url", json!("https://example.com"))])).unwrap();
assert_eq!(argv, strings(&["--", "https://example.com"]));
}
#[test]
fn curl_sends_data_literally_and_never_reads_a_file_for_it() {
let args = args_of(&[
("url", json!("https://example.com")),
("data", json!("@/etc/passwd")),
]);
let argv = curl_argv(&args).unwrap();
assert!(
argv.windows(2).any(|w| w == ["--data-raw", "@/etc/passwd"]),
"{argv:?}"
);
assert!(!argv.iter().any(|a| a == "--data"), "{argv:?}");
}
#[test]
fn curl_refuses_a_value_that_would_become_a_flag() {
for (name, value) in [
("url", json!("-K/tmp/evil.conf")),
("method", json!("-o")),
("headers", json!(["-H"])),
("data", json!("-o")),
("data", json!(-5)),
] {
let args = args_of(&[("url", json!("https://example.com")), (name, value)]);
let err = curl_argv(&args).expect_err(name);
let coded = err
.downcast_ref::<crate::safety::SafetyError>()
.expect("a coded refusal");
assert!(
matches!(coded.code, crate::safety::ErrorCode::BadArg),
"{name}: {coded:?}"
);
}
}
#[test]
fn curl_refuses_output_and_headers_that_name_a_file() {
let to_file = args_of(&[
("url", json!("https://example.com")),
("output", json!("/tmp/x")),
]);
assert!(curl_argv(&to_file).is_err(), "output must not reach curl");
let from_file = args_of(&[
("url", json!("https://example.com")),
("headers", json!(["@/etc/hosts"])),
]);
assert!(
curl_argv(&from_file).is_err(),
"@file headers must not reach curl"
);
}
#[test]
fn curl_refuses_an_option_like_value_at_the_validation_gate_too() {
// The catalogue entry itself, through the check that runs before the gate.
let db = OSToolsDatabase::new();
let tool = db.get_tool("curl").expect("curl is in the catalogue");
for (name, value) in [("url", json!("-o")), ("data", json!("-K"))] {
let args = args_of(&[(name, value)]);
assert!(validate_tool_args(tool, &args).is_err(), "{name}");
}
}
}