newt-mcp-server 0.8.2

Newt-Agent stdio MCP server — code.read / code.edit / code.search / goal.run
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
//! MCP protocol handlers: initialize, tools/list, and tools/call.
//!
//! Registers all JSON-RPC methods that the newt MCP server exposes.
//!
//! `goal_run` is the only handler that needs runtime state — it
//! borrows a [`BackendRegistry`] (to pick a backend) and a [`Router`]
//! (to classify the prompt into a [`Tier`]). The other tools
//! (`code_read` / `code_edit` / `code_search`) are pure file I/O and
//! need no shared state.

use std::path::Path;
use std::sync::Arc;

use agent_bridle::{Caveats, Grant, Registry, ToolError};
use newt_core::router::{Router, Tier};
use newt_inference::BackendRegistry;
use newt_mcp_client::McpToolset;
use serde_json::Value;
use tokio::sync::Mutex;

use crate::caveats::GrantedCaveats;
use crate::server::McpServer;

/// Register the core MCP protocol handlers on `server`.
///
/// `registry` and `router` are wired into the `goal_run` handler;
/// every other handler ignores them.
///
/// `shell_run` is the one tool that no longer runs free: it is dispatched
/// through agent-bridle's Caveats-confined brush shell, under a granted
/// [`Caveats`] leash sourced from `~/.newt/config.toml` (see
/// [`crate::caveats`]). The bridle [`Registry`] and the granted leash are
/// built once here and shared (via `Arc`) into the `tools/call` closure.
///
/// `toolset` (#1021 PR 5.3) is the session's connected remote MCP servers
/// (e.g. `modulex`) — `McpToolset::empty()` when none/no persona. `persona_tools`
/// is the active persona's `tools:` allow-list (`None` = unconstrained, the
/// zero-cost path for every non-persona session): it restricts BOTH the
/// built-in catalog above and the remote MCP tools to exactly the persona's
/// list, via [`newt_core::agentic::persona_tool_allowed`] — the same
/// predicate the TUI's advertise/execute symmetry depends on, so this
/// server's `tools/list` and `tools/call` can't drift apart either.
pub fn register_handlers(
    server: &mut McpServer,
    registry: Arc<BackendRegistry>,
    router: Arc<Router>,
    toolset: Arc<Mutex<McpToolset>>,
    persona_tools: Arc<Option<Vec<String>>>,
) {
    let granted = GrantedCaveats::load();
    // Surface, loudly, whether shell_run is confined or running with full
    // ambient authority. An unconfined default is a WARNING.
    granted.warn_to_stderr();

    register_initialize(server);
    register_tools_list(
        server,
        toolset.clone(),
        persona_tools.clone(),
        &granted.caveats.fs_read,
    );
    register_tools_call(
        server,
        registry,
        router,
        bridle_registry(),
        Arc::new(granted.caveats),
        toolset,
        persona_tools,
    );
}

// ── initialize ─────────────────────────────────────────────────────────────

fn register_initialize(server: &mut McpServer) {
    server.register("initialize", |_params| async move {
        Ok(serde_json::json!({
            "protocolVersion": "2024-11-05",
            "capabilities": { "tools": {} },
            "serverInfo": {
                "name": "newt-mcp-server",
                "version": env!("CARGO_PKG_VERSION")
            }
        }))
    });
}

// ── tools/list ─────────────────────────────────────────────────────────────

/// Restrict `tools` (MCP-native `{name, description, inputSchema}` entries)
/// to a persona's allow-list. `allow = None` returns `tools` untouched.
fn filter_persona_tool_list(tools: Vec<Value>, allow: Option<&[String]>) -> Vec<Value> {
    let Some(allow) = allow else { return tools };
    tools
        .into_iter()
        .filter(|t| match t.get("name").and_then(Value::as_str) {
            Some(name) => newt_core::agentic::persona_tool_allowed(name, allow),
            None => true,
        })
        .collect()
}

fn register_tools_list(
    server: &mut McpServer,
    toolset: Arc<Mutex<McpToolset>>,
    persona_tools: Arc<Option<Vec<String>>>,
    read_scope: &agent_bridle::Scope<String>,
) {
    let legacy_git_allowed = newt_core::agentic::check_git_read_scope("open", read_scope).is_ok();
    server.register("tools/list", move |_params| {
        let toolset = toolset.clone();
        let persona_tools = persona_tools.clone();
        async move {
            let Value::Array(mut tools) = tool_definitions() else {
                unreachable!("tool_definitions always returns a JSON array");
            };
            if !legacy_git_allowed {
                tools.retain(|tool| tool["name"] != "git");
            }
            tools.extend(toolset.lock().await.mcp_tool_list());
            let tools = filter_persona_tool_list(tools, persona_tools.as_deref());
            Ok(serde_json::json!({ "tools": tools }))
        }
    });
}

/// Return the JSON array of tool definitions (shared by tools/list).
fn tool_definitions() -> Value {
    let tools = vec![
        serde_json::json!({
            "name": "code_read",
            "description": "Read a file's contents",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "File path to read"
                    }
                },
                "required": ["path"]
            }
        }),
        serde_json::json!({
            "name": "code_edit",
            "description": "Apply a unified diff patch to a file",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "File path to edit"
                    },
                    "patch": {
                        "type": "string",
                        "description": "Unified diff to apply"
                    }
                },
                "required": ["path", "patch"]
            }
        }),
        serde_json::json!({
            "name": "code_search",
            "description": "Search files for a regex pattern",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Regex pattern"
                    },
                    "path": {
                        "type": "string",
                        "description": "Root directory to search"
                    }
                },
                "required": ["query", "path"]
            }
        }),
        serde_json::json!({
            "name": "git",
            "description": "Run a git operation via the embedded engine (grit-lib), gated by GitCaveats derived from the granted Caveats leash. Requires unrestricted fs_read because legacy repository reads are not path-confined. ops: status | log | diff | add | commit | branch. Local-only; network ops (clone/fetch/push) are fail-closed. A write op (add/commit/branch) under a read-only grant is DENIED (isError). Returns structured JSON.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "op": { "type": "string", "enum": ["status", "log", "diff", "add", "commit", "branch"] },
                    "repo": { "type": "string", "description": "Repository path (default: current directory)" },
                    "limit": { "type": "integer", "description": "log: max commits (default 20)" },
                    "staged": { "type": "boolean", "description": "diff: staged (index vs HEAD) instead of worktree (default false)" },
                    "paths": { "type": "array", "items": { "type": "string" }, "description": "add: repo-relative paths to stage" },
                    "message": { "type": "string", "description": "commit: commit message" },
                    "name": { "type": "string", "description": "branch: new branch name" }
                },
                "required": ["op"]
            }
        }),
        serde_json::json!({
            "name": "goal_run",
            "description": "Run a tier-routed inference turn",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "prompt": {
                        "type": "string",
                        "description": "The prompt"
                    },
                    "tier": {
                        "type": "string",
                        "description": "Optional tier override",
                        "enum": ["FAST", "STANDARD", "COMPLEX", "REVIEW"]
                    }
                },
                "required": ["prompt"]
            }
        }),
        serde_json::json!({
            "name": "fs_list",
            "description": "List directory contents (dirs first, then files, alphabetical). Returns name, kind, and size_bytes for each entry.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "path": {
                        "type": "string",
                        "description": "Directory path to list"
                    }
                },
                "required": ["path"]
            }
        }),
        serde_json::json!({
            "name": "shell_run",
            "description": "Run a shell command and capture stdout/stderr. Returns exit_code, stdout, stderr, timed_out. Max timeout 300s. CAVEATS-CONFINED: the command runs inside agent-bridle's brush shell under the granted Caveats leash (from ~/.newt/config.toml [caveats]); a command outside the granted exec/fs scope is DENIED (isError) rather than executed.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "cmd": {
                        "type": "string",
                        "description": "Shell command to execute, confined in-process by the agent-bridle capability interceptor (exec + fs scopes)"
                    },
                    "cwd": {
                        "type": "string",
                        "description": "Working directory (default: current directory)"
                    },
                    "timeout_secs": {
                        "type": "integer",
                        "description": "Timeout in seconds (default 30, max 300)"
                    }
                },
                "required": ["cmd"]
            }
        }),
        serde_json::json!({
            "name": "web_fetch",
            "description": "Fetch an http(s) URL and return its main content as clean markdown. CAVEATS-CONFINED: reachable hosts are gated by the granted `net` scope (host allowlist + SSRF screen); an out-of-scope host is DENIED (isError) rather than fetched. Returns { url, final_url, status, title, markdown } — the markdown is untrusted page content.",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "url": {
                        "type": "string",
                        "description": "The http(s) URL to fetch"
                    },
                    "max_bytes": {
                        "type": "integer",
                        "description": "Optional cap on bytes downloaded (default 5 MiB, max 25 MiB)"
                    }
                },
                "required": ["url"]
            }
        }),
    ];

    Value::Array(tools)
}

// ── tools/call ─────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn register_tools_call(
    server: &mut McpServer,
    registry: Arc<BackendRegistry>,
    router: Arc<Router>,
    bridle: Arc<Registry>,
    granted: Arc<Caveats>,
    toolset: Arc<Mutex<McpToolset>>,
    persona_tools: Arc<Option<Vec<String>>>,
) {
    // Mint once, reused across every `shell_run` / `web_fetch` call this
    // session (AB-001, #264): a grant minted per call would reset the
    // `max_calls` budget on every dispatch instead of accounting it
    // cross-call, as the session's single `granted` leash always did.
    let grant = Arc::new(bridle.mint_grant((*granted).clone()));
    server.register("tools/call", move |params| {
        // Move clones into the async block so each invocation owns its
        // own Arc (the outer closure is `Fn`, not `FnOnce`).
        let registry = registry.clone();
        let router = router.clone();
        let bridle = bridle.clone();
        let granted = granted.clone();
        let grant = grant.clone();
        let toolset = toolset.clone();
        let persona_tools = persona_tools.clone();
        async move {
            let name = params
                .get("name")
                .and_then(|n| n.as_str())
                .unwrap_or("")
                .to_string();
            let arguments = params
                .get("arguments")
                .cloned()
                .unwrap_or_else(|| Value::Object(Default::default()));

            // #1021 PR 5.3: re-check the SAME allow-list `tools/list`
            // filtered by — advertisement-hiding a tool doesn't stop it
            // being called directly, so this is the load-bearing half.
            if let Some(allow) = persona_tools.as_deref() {
                if !newt_core::agentic::persona_tool_allowed(&name, allow) {
                    anyhow::bail!("tool `{name}` is not permitted by the active persona");
                }
            }

            match name.as_str() {
                "code_read" => handle_code_read(&arguments),
                "code_edit" => handle_code_edit(&arguments),
                "code_search" => handle_code_search(&arguments),
                "goal_run" => handle_goal_run(&arguments, &registry, &router).await,
                "fs_list" => handle_fs_list(&arguments),
                "git" => handle_git(&arguments, &granted),
                "shell_run" => Ok(handle_shell_run(arguments, &bridle, &grant).await),
                "web_fetch" => Ok(handle_web_fetch(arguments, &bridle, &grant).await),
                other if newt_mcp_client::split_namespaced(other).is_some() => {
                    let mut toolset = toolset.lock().await;
                    if !toolset.handles(other) {
                        anyhow::bail!("unknown tool: {other}");
                    }
                    Ok(mcp_text_content(&toolset.call(other, &arguments).await))
                }
                other => anyhow::bail!("unknown tool: {other}"),
            }
        }
    });
}

// ── Tool implementations ───────────────────────────────────────────────────

/// `git` — the embedded git engine (grit-lib via `newt-git`), gated by
/// `GitCaveats` derived from the granted leash. Local ops only; a write under a
/// read-only grant returns an error (MCP `isError`).
fn handle_git(args: &Value, granted: &Caveats) -> anyhow::Result<Value> {
    use newt_git::{Author, DiffSpec, GitEngine};

    let op = args
        .get("op")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: op"))?;
    let repo = args.get("repo").and_then(|v| v.as_str()).unwrap_or(".");
    // The git surface is bounded by the granted leash: read-only when fs_write is
    // empty, full-local when writable, network always denied.
    let caps = newt_core::git_caveats::GitCaveats::from_session(granted);
    let eng = GitEngine::open(Path::new(repo), &granted.fs_read)
        .map_err(|e| anyhow::anyhow!("git open: {e}"))?;

    let result: Value = match op {
        "status" => serde_json::to_value(eng.status(&caps).map_err(gerr)?)?,
        "log" => {
            let limit = args.get("limit").and_then(Value::as_u64).unwrap_or(20) as usize;
            serde_json::to_value(eng.log(&caps, limit, None, &[]).map_err(gerr)?)?
        }
        "diff" => {
            let spec = if args.get("staged").and_then(Value::as_bool).unwrap_or(false) {
                DiffSpec::Staged
            } else {
                DiffSpec::Worktree
            };
            serde_json::to_value(eng.diff(&caps, spec, &[], false).map_err(gerr)?)?
        }
        "add" => {
            let paths: Vec<String> = args
                .get("paths")
                .and_then(Value::as_array)
                .map(|a| {
                    a.iter()
                        .filter_map(|x| x.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            serde_json::to_value(eng.add(&caps, &paths).map_err(gerr)?)?
        }
        "commit" => {
            let message = args
                .get("message")
                .and_then(|v| v.as_str())
                .ok_or_else(|| anyhow::anyhow!("git commit requires 'message'"))?;
            let identity = newt_core::AgentIdentity::resolve().unwrap_or_default();
            let author = Author {
                name: args
                    .get("author_name")
                    .and_then(|v| v.as_str())
                    .unwrap_or(identity.name.as_str())
                    .to_string(),
                email: args
                    .get("author_email")
                    .and_then(|v| v.as_str())
                    .unwrap_or(identity.email.as_str())
                    .to_string(),
            };
            serde_json::to_value(eng.commit(&caps, message, &author).map_err(gerr)?)?
        }
        "branch" => {
            let name = args
                .get("name")
                .and_then(|v| v.as_str())
                .ok_or_else(|| anyhow::anyhow!("git branch requires 'name'"))?;
            serde_json::to_value(eng.branch(&caps, name).map_err(gerr)?)?
        }
        other => anyhow::bail!("unknown git op: {other}"),
    };
    Ok(mcp_text_content(&serde_json::to_string_pretty(&result)?))
}

/// Map a `newt-git` engine error (incl. capability denial) to an `anyhow` error
/// so the dispatch surfaces it as an MCP `isError`.
fn gerr(e: newt_git::GitError) -> anyhow::Error {
    anyhow::anyhow!("git: {e}")
}

fn handle_code_read(args: &Value) -> anyhow::Result<Value> {
    let path = args
        .get("path")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: path"))?;

    let content = newt_tools::read(Path::new(path))?;
    Ok(mcp_text_content(&content))
}

fn handle_code_edit(args: &Value) -> anyhow::Result<Value> {
    let path = args
        .get("path")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: path"))?;
    let patch = args
        .get("patch")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: patch"))?;

    newt_tools::edit(Path::new(path), patch)?;
    Ok(mcp_text_content(&format!("patched {path}")))
}

fn handle_code_search(args: &Value) -> anyhow::Result<Value> {
    let query = args
        .get("query")
        .and_then(|q| q.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: query"))?;
    let path = args
        .get("path")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: path"))?;

    let hits = newt_tools::search(query, Path::new(path))?;
    let lines: Vec<String> = hits
        .iter()
        .map(|h| format!("{}:{}: {}", h.path, h.line_number, h.line))
        .collect();
    let text = if lines.is_empty() {
        "no matches".to_string()
    } else {
        lines.join("\n")
    };
    Ok(mcp_text_content(&text))
}

fn handle_fs_list(args: &Value) -> anyhow::Result<Value> {
    let path = args
        .get("path")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: path"))?;

    let entries = newt_tools::list_dir(Path::new(path))?;
    Ok(mcp_text_content(&serde_json::to_string_pretty(&entries)?))
}

/// `shell_run` — the Caveats-confined shell.
///
/// History: PR #125 implemented this as an UNCONFINED `tokio::process` `sh -c`
/// with only a timeout — full ambient authority. P1 supersedes that: the same
/// MCP tool name and input schema (`cmd`, `cwd`, `timeout_secs`) now route the
/// command through agent-bridle's brush-backed confined shell under the granted
/// [`Caveats`] leash. A command outside the granted `exec`/`fs` scope is DENIED
/// in-process by the brush `CommandInterceptor` hook — it never runs.
///
/// `cmd` is mapped to agent-bridle's **free-form `cmd` mode** (added in
/// agent-bridle#4) so it stays a drop-in for clients: pipelines, `&&`,
/// redirections, globbing all still work, but every external spawn passes the
/// interceptor's `before_exec` / `before_open` gate.
///
/// Error mapping (the load-bearing semantics): a leash **denial** is surfaced
/// as an MCP *tool error* — `{ content: [..], isError: true }` carrying the
/// reason — NOT a JSON-RPC transport fault. That keeps the denial observable to
/// the model: it sees *why* it was refused without the call collapsing into a
/// `-32603`. So this function returns a `Value` directly (the `tools/call`
/// arm wraps it in `Ok`), and never bubbles a leash error up the transport.
async fn handle_shell_run(args: Value, bridle: &Registry, grant: &Grant) -> Value {
    // Validate the one required field. A missing `cmd` is a tool-level mistake,
    // so it comes back as an in-band tool error, matching the leash-denial
    // shape rather than crashing the transport.
    if args.get("cmd").and_then(Value::as_str).is_none() {
        return mcp_error_content("missing required argument: cmd (must be a string)");
    }

    // Route to agent-bridle's free-form `cmd` mode. The shell tool already
    // reads `cmd`, `cwd`, and `timeout_secs` from this exact shape (and clamps
    // the timeout to its own 300s ceiling), so we forward the arguments
    // verbatim — no field translation needed.
    match bridle.dispatch("shell", args, grant).await {
        // The confined shell ran. Its envelope carries
        // `{ exit_code, stdout, stderr, timed_out, sandbox_kind }` plus —
        // when the leash refused a capability — the STRUCTURED denial fields
        // `{ denied: true, denials: [{ kind, target, reason }] }`.
        //
        // IMPORTANT (free-form `cmd` semantics): in free-form mode an
        // out-of-scope command is NOT a `ToolError::Denied` from `dispatch` —
        // there is no single named program to pre-check, so the brush
        // `CommandInterceptor`'s `before_exec` / `before_open` hook denies the
        // command *inside* the shell. The command genuinely does not run
        // (confinement is real), and the denial is reported through the
        // envelope's `denied` flag.
        //
        // To keep the leash observable end-to-end, we lift such an in-envelope
        // confinement denial to an MCP tool error (`isError: true`) carrying
        // the joined denial reason(s) — the same shape an argv-mode
        // `ToolError::Denied` produces. Detection reads the structured
        // `denied` field, NEVER parses stdout/stderr. An in-scope command
        // (even one that exits non-zero for its own reasons) is returned as a
        // normal success envelope.
        Ok(envelope) if is_denied(&envelope) => mcp_error_content(&denial_reason(&envelope)),
        Ok(envelope) => match serde_json::to_string_pretty(&envelope) {
            Ok(text) => mcp_text_content(&text),
            Err(e) => mcp_error_content(&format!("failed to serialize shell result: {e}")),
        },
        // An argv-mode leash denial (or budget / generation / unknown tool, or
        // an error from inside a tool that passed the leash) — surface the
        // reason in-band as an MCP tool error, never a transport fault.
        // (`ToolError::Display` is safe to show the agent.)
        Err(e @ ToolError::Denied { .. }) => mcp_error_content(&e.to_string()),
        Err(e) => mcp_error_content(&e.to_string()),
    }
}

/// Fetch a web page through agent-bridle's `web_fetch`, leashed by the `net`
/// axis. Unlike the shell tool, a capability denial here is a normal
/// `ToolError::Denied` from `dispatch` (the `net` scope is checked inside the
/// tool), so there is no in-envelope `denied` flag to lift — we map `Ok` to MCP
/// text and any `Err` to an in-band MCP tool error.
async fn handle_web_fetch(args: Value, bridle: &Registry, grant: &Grant) -> Value {
    if args.get("url").and_then(Value::as_str).is_none() {
        return mcp_error_content("missing required argument: url (must be a string)");
    }
    match bridle.dispatch("web_fetch", args, grant).await {
        // `{ url, final_url, status, title, markdown }` — untrusted page content.
        Ok(result) => match serde_json::to_string_pretty(&result) {
            Ok(text) => mcp_text_content(&text),
            Err(e) => mcp_error_content(&format!("failed to serialize web_fetch result: {e}")),
        },
        // Out-of-scope host (net denial), SSRF screen, timeout, non-2xx, etc.
        Err(e) => mcp_error_content(&e.to_string()),
    }
}

/// Whether a confined-shell envelope carries the STRUCTURED `denied: true`
/// flag — the leash's machine-readable signal that the brush `CaveatInterceptor`
/// refused an exec / open in free-form mode.
///
/// This reads the structured field agent-bridle now emits; it does NOT parse
/// stdout/stderr. The old stderr string-match (`"is not within the granted"`,
/// etc.) was fragile — a successful command that merely *printed* a denial-like
/// phrase could be misread, and any wording drift in the leash would silently
/// break detection. The structured envelope removes both hazards.
fn is_denied(envelope: &Value) -> bool {
    envelope
        .get("denied")
        .and_then(Value::as_bool)
        .unwrap_or(false)
}

/// Build a human-readable denial message from the envelope's structured
/// `denials: [{ kind, target, reason }]` list, joining each entry's `reason`.
/// Falls back to a generic message when the list is missing or empty.
fn denial_reason(envelope: &Value) -> String {
    let reasons: Vec<String> = envelope
        .get("denials")
        .and_then(Value::as_array)
        .map(|arr| {
            arr.iter()
                .filter_map(|d| d.get("reason").and_then(Value::as_str))
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default();
    if reasons.is_empty() {
        "denied: the capability leash refused an operation".to_string()
    } else {
        reasons.join("; ")
    }
}

/// Parse a `tier` argument from the JSON-RPC call. Accepts the four
/// canonical names (case-insensitive) per the tools/list schema.
fn parse_tier(s: &str) -> anyhow::Result<Tier> {
    match s.to_ascii_uppercase().as_str() {
        "FAST" => Ok(Tier::Fast),
        "STANDARD" => Ok(Tier::Standard),
        "COMPLEX" => Ok(Tier::Complex),
        "REVIEW" => Ok(Tier::Review),
        other => anyhow::bail!("invalid tier: {other} (expected FAST|STANDARD|COMPLEX|REVIEW)"),
    }
}

/// Wire `goal_run`:
///   1. validate `prompt` (required)
///   2. validate `tier` override if present, else `Router::classify`
///   3. pick a backend from the registry for that tier
///   4. await `backend.complete(...)`
///   5. wrap the reply in the MCP content envelope, prefixed with the
///      backend's `model_id` so callers can see which model answered
async fn handle_goal_run(
    args: &Value,
    registry: &BackendRegistry,
    router: &Router,
) -> anyhow::Result<Value> {
    let prompt = args
        .get("prompt")
        .and_then(|p| p.as_str())
        .ok_or_else(|| anyhow::anyhow!("missing required argument: prompt"))?
        .to_string();

    let tier = match args.get("tier").and_then(|t| t.as_str()) {
        Some(s) => parse_tier(s)?,
        None => router.classify(&prompt),
    };

    let backend = registry
        .pick(tier)
        .map_err(|e| anyhow::anyhow!(e.to_string()))?;

    let chat = newt_inference::ChatRequest::new().user(prompt);
    let reply = backend
        .complete(chat)
        .await
        .map_err(|e| anyhow::anyhow!(e.to_string()))?;

    Ok(mcp_text_content(&format!(
        "[{}] {}",
        reply.model_id, reply.content
    )))
}

/// Wrap a string in the MCP content envelope: `{ "content": [{ "type": "text", "text": ... }] }`.
fn mcp_text_content(text: &str) -> Value {
    serde_json::json!({
        "content": [{
            "type": "text",
            "text": text
        }]
    })
}

/// Wrap a reason in the MCP **tool error** envelope: the content shape plus
/// `isError: true`. This is what a leash denial looks like across the MCP
/// boundary — an in-band tool error the model can read, not a transport fault.
fn mcp_error_content(reason: &str) -> Value {
    serde_json::json!({
        "content": [{
            "type": "text",
            "text": reason
        }],
        "isError": true
    })
}

#[cfg(test)]
fn bridle_registry() -> Arc<Registry> {
    Arc::new(
        Registry::builder()
            .tool(Arc::new(agent_bridle::ShellTool::new()))
            .tool(Arc::new(agent_bridle::WebFetchTool::new()))
            .build(),
    )
}

#[cfg(not(test))]
fn bridle_registry() -> Arc<Registry> {
    Arc::new(agent_bridle::registry())
}

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

    // ── Helper ──────────────────────────────────────────────────────────────

    /// Build a fully-wired McpServer with an empty registry and default
    /// router, then send a single request through it.
    async fn rpc(request: &Value) -> Value {
        rpc_with(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            request,
        )
        .await
    }

    /// Like [`rpc`], but with a caller-supplied registry and router so
    /// goal_run tests can swap in a mock backend. No persona (empty toolset,
    /// unrestricted catalog) — see [`rpc_with_persona`] for that.
    async fn rpc_with(
        registry: Arc<BackendRegistry>,
        router: Arc<Router>,
        request: &Value,
    ) -> Value {
        rpc_with_persona(registry, router, McpToolset::empty(), None, request).await
    }

    /// Like [`rpc_with`], but with an explicit (possibly non-empty) toolset
    /// and persona `tools:` allow-list — the harness a persona-restriction
    /// test drives directly (#1021 PR 5.3).
    async fn rpc_with_persona(
        registry: Arc<BackendRegistry>,
        router: Arc<Router>,
        toolset: McpToolset,
        persona_tools: Option<Vec<String>>,
        request: &Value,
    ) -> Value {
        let mut server = McpServer::new();
        register_handlers(
            &mut server,
            registry,
            router,
            Arc::new(Mutex::new(toolset)),
            Arc::new(persona_tools),
        );

        let input = format!("{}\n", serde_json::to_string(request).unwrap());
        let mut output: Vec<u8> = Vec::new();
        server.run(input.as_bytes(), &mut output).await.unwrap();
        let text = String::from_utf8(output).unwrap();
        serde_json::from_str(text.trim()).unwrap()
    }

    /// Like [`rpc`], but wires `tools/call` with an EXPLICIT bridle leash so a
    /// test can confine `shell_run` deterministically — independent of the
    /// host's `~/.newt/config.toml`. (`register_handlers` would source the
    /// granted Caveats from the real home dir, which a test must not depend
    /// on.) This drives `register_tools_call` directly with a chosen grant.
    async fn rpc_with_caveats(granted: Caveats, request: &Value) -> Value {
        let mut server = McpServer::new();
        let toolset = Arc::new(Mutex::new(McpToolset::empty()));
        let persona_tools = Arc::new(None);
        register_initialize(&mut server);
        register_tools_list(
            &mut server,
            toolset.clone(),
            persona_tools.clone(),
            &granted.fs_read,
        );
        register_tools_call(
            &mut server,
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            bridle_registry(),
            Arc::new(granted),
            toolset,
            persona_tools,
        );

        let input = format!("{}\n", serde_json::to_string(request).unwrap());
        let mut output: Vec<u8> = Vec::new();
        server.run(input.as_bytes(), &mut output).await.unwrap();
        let text = String::from_utf8(output).unwrap();
        serde_json::from_str(text.trim()).unwrap()
    }

    /// A restrictive grant: only the platform echo carrier may exec, capped
    /// call budget. Used by the superseded-`shell_run` regression tests below.
    fn echo_only_grant() -> Caveats {
        use agent_bridle::{CountBound, Scope};
        #[cfg(windows)]
        let exec = Scope::only(["cmd.exe".to_string()]);
        #[cfg(not(windows))]
        let exec = Scope::only(["echo".to_string()]);
        Caveats {
            exec,
            max_calls: CountBound::AtMost(8),
            ..Caveats::top()
        }
    }

    fn echo_command() -> &'static str {
        #[cfg(windows)]
        {
            "cmd.exe /c echo bridled"
        }
        #[cfg(not(windows))]
        {
            "echo bridled"
        }
    }

    // ── initialize ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn initialize_returns_protocol_version() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}
        }))
        .await;

        let result = &resp["result"];
        assert_eq!(result["protocolVersion"], "2024-11-05");
        assert_eq!(result["serverInfo"]["name"], "newt-mcp-server");
        assert!(result["capabilities"]["tools"].is_object());
    }

    // ── tools/list ──────────────────────────────────────────────────────────

    #[tokio::test]
    async fn tools_list_returns_expected_tools() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}
        }))
        .await;

        let tools = resp["result"]["tools"].as_array().unwrap();
        // At least the four core tools; optional feature sets add more.
        assert!(
            tools.len() >= 4,
            "expected at least 4 tools, got {}",
            tools.len()
        );

        let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
        assert!(names.contains(&"code_read"));
        assert!(names.contains(&"code_edit"));
        assert!(names.contains(&"code_search"));
        assert!(names.contains(&"goal_run"));
        assert!(names.contains(&"fs_list"));
        assert!(names.contains(&"shell_run"));
    }

    #[tokio::test]
    async fn tools_list_has_input_schemas() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 3, "method": "tools/list", "params": {}
        }))
        .await;

        let tools = resp["result"]["tools"].as_array().unwrap();
        for tool in tools {
            assert!(
                tool["inputSchema"].is_object(),
                "tool {} missing inputSchema",
                tool["name"]
            );
        }
    }

    // ── #1021 PR 5.3: persona tool-allowlist restriction ────────────────────
    //
    // No live MCP server connection is exercised here: `AnyTransport::Mock`
    // is `#[cfg(test)]`-gated INSIDE newt-mcp-client, so it only exists in
    // that crate's own test build — a downstream crate (this one) depending
    // on it normally sees none of that, only its real (non-test) surface.
    // These tests cover what's actually reachable here: the built-in
    // catalog's persona filtering, and a namespaced call correctly failing
    // closed (`unknown tool`) against an empty (unconnected) toolset — the
    // same "not handled" path a real disconnected/misconfigured server
    // would hit.

    #[tokio::test]
    async fn persona_restricts_tools_list_to_its_allow_list() {
        let resp = rpc_with_persona(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            McpToolset::empty(),
            Some(vec!["code_read".to_string()]),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}
            }),
        )
        .await;
        let names: Vec<&str> = resp["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap())
            .collect();
        assert_eq!(names, vec!["code_read"], "only the allowed tool is listed");
    }

    #[tokio::test]
    async fn no_persona_advertises_the_full_catalog_unrestricted() {
        // Regression: `persona_tools = None` must be the exact zero-cost
        // path — every built-in tool still listed, byte-for-byte the
        // pre-#1021 behavior.
        let resp = rpc_with_persona(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            McpToolset::empty(),
            None,
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}
            }),
        )
        .await;
        let names: Vec<&str> = resp["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t["name"].as_str().unwrap())
            .collect();
        assert!(names.contains(&"code_read"));
        assert!(names.contains(&"shell_run"));
        assert!(names.contains(&"web_fetch"));
    }

    #[tokio::test]
    async fn persona_rejects_a_call_to_a_tool_outside_its_allow_list() {
        // Advertise/execute symmetry: hiding a tool from tools/list doesn't
        // stop a direct tools/call for it — this is the load-bearing half.
        let resp = rpc_with_persona(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            McpToolset::empty(),
            Some(vec!["code_read".to_string()]),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                "params": { "name": "shell_run", "arguments": { "command": "echo hi" } }
            }),
        )
        .await;
        let err = resp["error"]["message"].as_str().unwrap_or_default();
        assert!(
            err.contains("not permitted by the active persona"),
            "got: {resp}"
        );
    }

    #[tokio::test]
    async fn persona_allows_a_call_to_a_tool_inside_its_allow_list() {
        let resp = rpc_with_persona(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            McpToolset::empty(),
            Some(vec!["fs_list".to_string()]),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                "params": { "name": "fs_list", "arguments": { "path": "." } }
            }),
        )
        .await;
        assert!(resp.get("error").is_none(), "got: {resp}");
    }

    #[tokio::test]
    async fn namespaced_call_against_an_unconnected_toolset_fails_closed() {
        // A persona whose allow-list names a namespaced MCP tool, but whose
        // toolset has no connected server for it (e.g. modulex misconfigured
        // or unreachable) — the call must fail with "unknown tool", not
        // silently no-op or panic.
        let resp = rpc_with_persona(
            Arc::new(BackendRegistry::new()),
            Arc::new(Router::new()),
            McpToolset::empty(),
            Some(vec!["modulex__routine_run".to_string()]),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                "params": { "name": "modulex__routine_run", "arguments": { "routine": "morning" } }
            }),
        )
        .await;
        let err = resp["error"]["message"].as_str().unwrap_or_default();
        assert!(err.contains("unknown tool"), "got: {resp}");
    }

    // ── tools/call — code_read ──────────────────────────────────────────────

    #[tokio::test]
    async fn code_read_happy_path() {
        let tmp = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(tmp.path(), "hello from newt\n").unwrap();

        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 10, "method": "tools/call",
            "params": {
                "name": "code_read",
                "arguments": { "path": tmp.path().to_str().unwrap() }
            }
        }))
        .await;

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("hello from newt"));
    }

    #[tokio::test]
    async fn code_read_missing_file() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 11, "method": "tools/call",
            "params": {
                "name": "code_read",
                "arguments": { "path": "/tmp/newt-mcp-no-such-file-xyz" }
            }
        }))
        .await;

        assert!(resp["error"].is_object(), "expected error, got: {resp}");
        assert_eq!(resp["error"]["code"], -32603);
    }

    // ── tools/call — git (embedded engine) ──────────────────────────────────

    fn run_git(dir: &std::path::Path, args: &[&str]) {
        assert!(std::process::Command::new("git")
            .current_dir(dir)
            .args(args)
            .status()
            .unwrap()
            .success());
    }

    fn temp_repo() -> tempfile::TempDir {
        let d = tempfile::tempdir().unwrap();
        let p = d.path();
        run_git(p, &["init", "-q", "-b", "main"]);
        std::fs::write(p.join("a.txt"), "hello\n").unwrap();
        run_git(p, &["add", "a.txt"]);
        run_git(
            p,
            &[
                "-c",
                "user.name=T",
                "-c",
                "user.email=t@e",
                "commit",
                "-q",
                "-m",
                "first",
            ],
        );
        d
    }

    #[tokio::test]
    async fn git_status_returns_structured_json() {
        let repo = temp_repo();
        let resp = rpc_with_caveats(
            Caveats::top(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 40, "method": "tools/call",
                "params": {
                    "name": "git",
                    "arguments": { "op": "status", "repo": repo.path().to_str().unwrap() }
                }
            }),
        )
        .await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let v: Value = serde_json::from_str(text).unwrap();
        assert_eq!(v["branch"], "main");
        assert_eq!(v["clean"], true);
    }

    /// Real repository reads ground the advertise/execute scope boundary:
    /// the legacy MCP engine cannot honor a workspace-only read grant.
    #[tokio::test]
    async fn scoped_git_is_not_advertised_or_dispatched() {
        let repo = temp_repo();
        let mut granted = Caveats::top();
        granted.fs_read = agent_bridle::Scope::only([repo.path().to_string_lossy().into_owned()]);
        let request = serde_json::json!({
            "jsonrpc": "2.0", "id": 40, "method": "tools/call",
            "params": {
                "name": "git",
                "arguments": { "op": "status", "repo": repo.path().to_str().unwrap() }
            }
        });
        let control = rpc_with_caveats(Caveats::top(), &request).await;
        assert!(control["result"].is_object(), "{control}");
        let denied = rpc_with_caveats(granted.clone(), &request).await;
        assert!(
            denied["error"]["message"]
                .as_str()
                .is_some_and(|message| message.contains("fs_read")),
            "scoped MCP Git must refuse before discovery: {denied}"
        );
        let listed = rpc_with_caveats(
            granted,
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 41, "method": "tools/list", "params": {}
            }),
        )
        .await;
        assert!(listed["result"]["tools"]
            .as_array()
            .unwrap()
            .iter()
            .all(|tool| tool["name"] != "git"));
    }

    #[tokio::test]
    async fn git_commit_denied_under_readonly_grant() {
        use agent_bridle::Scope;
        let repo = temp_repo();
        // fs_write empty -> GitCaveats::from_session denies stage/commit (fail-closed).
        let readonly = Caveats {
            fs_write: Scope::none(),
            ..Caveats::top()
        };
        let resp = rpc_with_caveats(
            readonly,
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 41, "method": "tools/call",
                "params": {
                    "name": "git",
                    "arguments": {
                        "op": "commit",
                        "repo": repo.path().to_str().unwrap(),
                        "message": "should be refused"
                    }
                }
            }),
        )
        .await;
        assert!(
            resp["error"].is_object(),
            "read-only grant must refuse git commit, got: {resp}"
        );
    }

    // ── tools/call — code_search ────────────────────────────────────────────

    #[tokio::test]
    async fn code_search_happy_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("a.txt"), "needle in hay\nhay only\n").unwrap();
        std::fs::write(tmp.path().join("b.txt"), "more hay\nneedle again\n").unwrap();

        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 20, "method": "tools/call",
            "params": {
                "name": "code_search",
                "arguments": {
                    "query": "needle",
                    "path": tmp.path().to_str().unwrap()
                }
            }
        }))
        .await;

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("needle"), "expected hits, got: {text}");
        // Two files should have matches
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 2, "expected 2 hits, got: {text}");
    }

    #[tokio::test]
    async fn code_search_no_matches() {
        let tmp = tempfile::TempDir::new().unwrap();
        std::fs::write(tmp.path().join("a.txt"), "nothing here\n").unwrap();

        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 21, "method": "tools/call",
            "params": {
                "name": "code_search",
                "arguments": {
                    "query": "zzz_absent",
                    "path": tmp.path().to_str().unwrap()
                }
            }
        }))
        .await;

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert_eq!(text, "no matches");
    }

    // ── tools/call — code_edit ──────────────────────────────────────────────

    #[tokio::test]
    async fn code_edit_happy_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "line1\nline2\n").unwrap();

        let patch = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,2 +1,2 @@
 line1
-line2
+edited
";

        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 30, "method": "tools/call",
            "params": {
                "name": "code_edit",
                "arguments": {
                    "path": file.to_str().unwrap(),
                    "patch": patch
                }
            }
        }))
        .await;

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("patched"), "expected success, got: {text}");

        let content = std::fs::read_to_string(&file).unwrap();
        assert_eq!(content, "line1\nedited\n");
    }

    #[tokio::test]
    async fn code_edit_bad_patch() {
        let tmp = tempfile::TempDir::new().unwrap();
        let file = tmp.path().join("hello.txt");
        std::fs::write(&file, "actual\n").unwrap();

        let patch = "\
--- a/hello.txt
+++ b/hello.txt
@@ -1,1 +1,1 @@
 WRONG_CONTEXT
";

        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 31, "method": "tools/call",
            "params": {
                "name": "code_edit",
                "arguments": {
                    "path": file.to_str().unwrap(),
                    "patch": patch
                }
            }
        }))
        .await;

        assert!(resp["error"].is_object(), "expected error, got: {resp}");
        assert_eq!(resp["error"]["code"], -32603);
    }

    // ── tools/call — unknown tool ───────────────────────────────────────────

    #[tokio::test]
    async fn unknown_tool_returns_error() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 50, "method": "tools/call",
            "params": {
                "name": "nonexistent_tool",
                "arguments": {}
            }
        }))
        .await;

        assert!(resp["error"].is_object(), "expected error, got: {resp}");
        assert_eq!(resp["error"]["code"], -32603);
        assert!(resp["error"]["message"]
            .as_str()
            .unwrap()
            .contains("unknown tool"));
    }

    // ── tools/call — shell_run is now Caveats-confined (P1 regression) ──────
    //
    // These prove `shell_run` ENFORCES the granted leash. They would FAIL
    // against PR #125's unconfined `sh -c` implementation, which ran any `cmd`
    // with full ambient authority and never consulted a Caveats grant.

    /// REGRESSION (P1): with a grant that includes `echo`, an in-scope `echo`
    /// RUNS under the confined shell and returns its output. Built against the
    /// agent-bridle env-seam branch (#783) the bridle ships the REAL safe-subset
    /// shell (no stub), so the in-scope command succeeds (isError unset) — the
    /// "unavailable in this build" stub error is retired.
    ///
    /// Not on Windows: see `shell_run_exec_allowlist_is_refused_on_windows`.
    #[cfg(not(windows))]
    #[tokio::test]
    async fn shell_run_in_scope_echo_succeeds() {
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 60, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": echo_command() }
                }
            }),
        )
        .await;

        assert!(
            resp["error"].is_null(),
            "result must be in-band, not a transport error: {resp}"
        );
        let result = &resp["result"];
        assert!(
            result["isError"].as_bool() != Some(true),
            "an in-scope echo must succeed, not error: {result}"
        );
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("bridled"),
            "the in-scope echo output must be returned: {text}"
        );
    }

    /// agent-bridle 0.8 refuses a non-empty exec allowlist under Windows
    /// AppContainer: the container cannot kernel-bound which images a child
    /// launches, so the L3 admission resolves the Exec axis `Unknown` and fails
    /// closed. An allowlisted `shell_run` is refused in-band, never run
    /// unconfined (`windows-appcontainer-exec-allowlist` in
    /// `docs/security/ocap-deviations.md`). Flip this back to success when
    /// agent-bridle can admit an exec allowlist on Windows.
    #[cfg(windows)]
    #[tokio::test]
    async fn shell_run_exec_allowlist_is_refused_on_windows() {
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 60, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": echo_command() }
                }
            }),
        )
        .await;

        assert!(
            resp["error"].is_null(),
            "result must be in-band, not a transport error: {resp}"
        );
        let result = &resp["result"];
        assert_eq!(result["isError"].as_bool(), Some(true), "{result}");
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("Exec axis") && !text.contains("bridled"),
            "the allowlisted echo must be refused on the Exec axis, not run: {text}"
        );
    }

    /// Out-of-scope `rm` is DENIED by the real safe-subset shell (env-seam
    /// branch, #783): it is not in the `echo`-only exec grant, so the confined
    /// shell refuses it with a capability denial lifted to an MCP `isError`
    /// (not the old stub "unavailable" error).
    #[cfg(unix)]
    #[tokio::test]
    async fn shell_run_out_of_scope_rm_is_denied() {
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 61, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": "rm -rf /tmp/newt-bridle-should-not-run" }
                }
            }),
        )
        .await;

        assert!(
            resp["error"].is_null(),
            "stub result must be in-band, not a transport error: {resp}"
        );
        let result = &resp["result"];
        assert_eq!(
            result["isError"], true,
            "out-of-scope rm must surface as an MCP tool error: {result}"
        );
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("not within the granted authority"),
            "out-of-scope rm must surface a capability denial: {text}"
        );
    }

    /// REGRESSION (P1): detection is now driven by the STRUCTURED `denied`
    /// field, exercised directly against `is_denied` / `denial_reason`. This
    /// pins the contract that we read the machine-readable envelope, never
    /// parse stdout/stderr. (A regression to stderr-grepping would make these
    /// helpers ignore the `denied`/`denials` fields and break.)
    #[test]
    fn denial_detection_reads_structured_fields_not_stderr() {
        // A denial envelope: `denied: true`, even with an EMPTY stderr and a
        // stdout that merely mentions success — the structured field wins.
        let denied = serde_json::json!({
            "exit_code": 126,
            "stdout": "all good, nothing denied here",
            "stderr": "",
            "denied": true,
            "denials": [
                { "kind": "exec", "target": "rm", "reason": "rm is not within the granted authority" }
            ]
        });
        assert!(
            is_denied(&denied),
            "structured denied:true must be detected"
        );
        assert_eq!(
            denial_reason(&denied),
            "rm is not within the granted authority"
        );

        // A clean envelope whose stdout merely PRINTS denial-like words must NOT
        // be misread as a denial — the old stderr-grep hazard, now impossible.
        let clean = serde_json::json!({
            "exit_code": 0,
            "stdout": "execution denied is not within the granted authority",
            "stderr": "open denied",
        });
        assert!(
            !is_denied(&clean),
            "absence of denied:true must mean not denied, regardless of output"
        );

        // Multiple denials are joined.
        let multi = serde_json::json!({
            "denied": true,
            "denials": [
                { "kind": "exec", "target": "rm", "reason": "exec rm denied" },
                { "kind": "open", "target": "/etc/x", "reason": "open /etc/x denied" }
            ]
        });
        assert_eq!(denial_reason(&multi), "exec rm denied; open /etc/x denied");
    }

    /// REGRESSION (P1 — the exec-bypass close): an `exec`-style invocation
    /// (`rm <marker>` / `touch <marker>`) under the `echo`-only grant is DENIED
    /// AND the program genuinely does not run — proven by the marker file NOT
    /// being created. This case SLIPPED on the old `129a1adf` pin (pre
    /// exec-bypass fix), where a free-form `exec` could escape the leash; it
    /// passing here proves the bump to the hardened agent-bridle closed the
    /// bypass *through newt's shell_run*, with the denial seen via the
    /// structured field.
    #[cfg(unix)]
    #[tokio::test]
    async fn shell_run_exec_bypass_is_denied_and_program_does_not_run() {
        let tmp = tempfile::TempDir::new().unwrap();
        let marker = tmp.path().join("exec-bypass-marker");
        let marker_str = marker.to_str().unwrap();
        assert!(!marker.exists(), "precondition: marker must not exist yet");

        // `touch <marker>` exercises an out-of-scope exec that, if it ran, would
        // create the marker. Under the echo-only grant it must be refused.
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 65, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": format!("touch {marker_str}") }
                }
            }),
        )
        .await;

        assert!(
            resp["error"].is_null(),
            "denial must be in-band, not transport: {resp}"
        );
        let result = &resp["result"];
        assert_eq!(
            result["isError"], true,
            "out-of-scope touch must be denied (isError): {result}"
        );
        // Confinement is REAL, not cosmetic: the program never ran, so the
        // marker was never created. This is the bit that would have failed on
        // the vulnerable `129a1adf` pin.
        assert!(
            !marker.exists(),
            "exec-bypass: touch must NOT have created the marker {marker_str}"
        );

        // And again with `rm` against a file we pre-create: the denial must
        // leave the file intact.
        let victim = tmp.path().join("victim");
        std::fs::write(&victim, "do not delete me").unwrap();
        let victim_str = victim.to_str().unwrap();
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 66, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": format!("rm {victim_str}") }
                }
            }),
        )
        .await;
        assert_eq!(
            resp["result"]["isError"], true,
            "out-of-scope rm must be denied: {}",
            resp["result"]
        );
        assert!(
            victim.exists(),
            "exec-bypass: rm must NOT have deleted the victim {victim_str}"
        );
    }

    /// A path-separator command (`/bin/rm`) is DENIED by the real safe-subset
    /// shell (env-seam branch, #783): the program is not in the `echo`-only exec
    /// grant, so the confined shell refuses it with a capability denial lifted to
    /// an MCP `isError` (not the old stub "unavailable" error).
    #[cfg(unix)]
    #[tokio::test]
    async fn shell_run_bin_rm_path_separator_is_denied() {
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 62, "method": "tools/call",
                "params": {
                    "name": "shell_run",
                    "arguments": { "cmd": "/bin/rm -rf /tmp/newt-bridle-should-not-run" }
                }
            }),
        )
        .await;

        let result = &resp["result"];
        assert_eq!(
            result["isError"], true,
            "path-separator rm must surface as an MCP tool error: {result}"
        );
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("not within the granted authority"),
            "path-separator rm must surface a capability denial: {text}"
        );
    }

    /// A missing `cmd` is an in-band tool error (matching the leash-denial
    /// shape), not a transport fault.
    #[tokio::test]
    async fn shell_run_missing_cmd_is_in_band_error() {
        let resp = rpc_with_caveats(
            echo_only_grant(),
            &serde_json::json!({
                "jsonrpc": "2.0", "id": 63, "method": "tools/call",
                "params": { "name": "shell_run", "arguments": {} }
            }),
        )
        .await;

        assert!(
            resp["error"].is_null(),
            "should be in-band, not transport: {resp}"
        );
        assert_eq!(resp["result"]["isError"], true);
        assert!(resp["result"]["content"][0]["text"]
            .as_str()
            .unwrap()
            .contains("cmd"));
    }

    /// The `shell_run` tools/list description now advertises the confinement.
    #[tokio::test]
    async fn shell_run_description_notes_caveats_confinement() {
        let resp = rpc(&serde_json::json!({
            "jsonrpc": "2.0", "id": 64, "method": "tools/list", "params": {}
        }))
        .await;
        let tools = resp["result"]["tools"].as_array().unwrap();
        let shell = tools
            .iter()
            .find(|t| t["name"] == "shell_run")
            .expect("shell_run present");
        let desc = shell["description"].as_str().unwrap();
        assert!(
            desc.contains("CAVEATS-CONFINED") || desc.to_lowercase().contains("caveats"),
            "shell_run description should note Caveats confinement: {desc}"
        );
    }

    // ── parse_tier — unit tests ─────────────────────────────────────────────

    #[test]
    fn parse_tier_canonical_names() {
        assert_eq!(parse_tier("FAST").unwrap(), Tier::Fast);
        assert_eq!(parse_tier("STANDARD").unwrap(), Tier::Standard);
        assert_eq!(parse_tier("COMPLEX").unwrap(), Tier::Complex);
        assert_eq!(parse_tier("REVIEW").unwrap(), Tier::Review);
    }

    #[test]
    fn parse_tier_is_case_insensitive() {
        assert_eq!(parse_tier("fast").unwrap(), Tier::Fast);
        assert_eq!(parse_tier("Complex").unwrap(), Tier::Complex);
    }

    #[test]
    fn parse_tier_rejects_unknown() {
        let err = parse_tier("BOGUS").unwrap_err().to_string();
        assert!(err.contains("invalid tier"), "got: {err}");
        assert!(err.contains("BOGUS"), "got: {err}");
    }
}