termshot 1.2.0

Terminal screenshot CLI and MCP server with ANSI rendering, redaction, themes, and composition
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
use crate::capture::LineSelection;
use crate::config::Config;
use crate::executor;
use crate::redaction::{
    ManualRedactionSpec, ManualRedactions, REDACTION_DISABLED_MSG, RedactionEngine, RedactionMap,
    explicit_request_is_blocked, resolve_should_redact,
};
use crate::renderer::{
    ChromeOptions, ComposeLayout, ExtendedRenderOptions, RedactionRequest, RenderContext, Renderer,
    TextOptions, fallback_output_name,
};
use rmcp::{
    ErrorData as McpError, ServerHandler, handler::server::router::tool::ToolRouter,
    handler::server::wrapper::Parameters, model::*, schemars, service::ServiceExt, tool,
    tool_handler, tool_router, transport::io::stdio,
};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, Mutex};
use std::time::Duration;

/// Every parameter struct below denies unknown fields, so a caller that sends
/// a parameter this server does not expose - a stale `embed_description`, a
/// typo, or a field from an older schema - gets a clear error instead of a
/// screenshot silently rendered with different settings than it asked for.
/// (`embed_description` in particular is deliberately global config only.)
/// The `execute_and_screenshot` parameters published in 1.0.0.
///
/// Kept at its original shape so Rust callers using exhaustive struct literals
/// remain source-compatible. The MCP tool now publishes
/// [`ExecuteAndScreenshotRequest`], which adds `cwd` and permits either
/// `command` or `commands`.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ExecuteAndScreenshotParams {
    /// Shell command to execute.
    pub command: String,

    /// Terminal width in columns. Defaults to server config value (120).
    #[serde(default)]
    pub cols: Option<u16>,

    /// Terminal height in rows. Defaults to server config value (40).
    #[serde(default)]
    pub rows: Option<u16>,

    /// Maximum time in seconds to wait for the command to finish. Defaults to 30.
    #[serde(default)]
    pub timeout_secs: Option<u64>,

    /// If true, run the command in an interactive login shell so the user's
    /// real shell prompt is rendered. If false, run the command directly.
    /// Defaults to true.
    #[serde(default)]
    pub show_prompt: Option<bool>,

    /// Theme name for rendering. Uses default theme from config if not specified.
    #[serde(default)]
    pub theme: Option<String>,

    /// Optional list of commands. If provided, each command is executed on its
    /// own line and receives its own shell prompt. If omitted, `command` is
    /// used.
    #[serde(default)]
    pub commands: Option<Vec<String>>,

    /// Chrome preset: none, minimal, gnome, macos, report.
    #[serde(default)]
    pub chrome: Option<String>,

    /// Optional chrome title.
    #[serde(default)]
    pub title: Option<String>,

    /// Whether to add a UTC timestamp watermark below the terminal content.
    #[serde(default)]
    pub timestamp: Option<bool>,

    /// Draw soft rounded corners (default: true). With chrome the window frame
    /// is rounded; without chrome the terminal content itself gets rounded
    /// corners on a transparent background. Set false for square corners.
    #[serde(default)]
    pub rounded: Option<bool>,

    /// Enable or disable redaction of sensitive data (IPs, keys, tokens, ...)
    /// for this screenshot. When omitted, the server's config decides (auto
    /// redaction). Set to false to force redaction off.
    #[serde(default)]
    pub redact: Option<bool>,

    /// Specific redaction rule names to apply (default: all enabled rules).
    /// Providing this implies redaction is enabled.
    #[serde(default)]
    pub redaction_rules: Option<Vec<String>>,

    /// Manual redactions applied to this screenshot: regex patterns and/or
    /// explicit cell ranges, exactly the specifications `redact_screenshot`
    /// and the CLI's repeatable `--redaction '<JSON>'` option take. They are
    /// applied in order (patterns first, then cell ranges) on top of any
    /// rule-based redaction. Providing this masks the screenshot even when
    /// `redact` is omitted; add `redact: true` (or `redaction_rules`) to run
    /// the built-in rules as well. Conflicts with `redact: false`.
    #[serde(default)]
    pub redactions: Option<Vec<ManualRedactionSpec>>,

    /// Also redact the returned terminal text. By default only the PNG image is
    /// redacted and the returned text keeps the ORIGINAL (unredacted) content
    /// so you can see what was there and decide what to redact (e.g. via
    /// redact_screenshot). Defaults to false.
    #[serde(default)]
    pub redact_text: Option<bool>,

    /// Whether to draw a short `[LABEL]` tag (e.g. `[IP]`, `[KEY]`) over each
    /// redaction block. Defaults to true. Set to false to draw plain solid
    /// blocks with no text overlay.
    #[serde(default)]
    pub show_labels: Option<bool>,

    /// Strip ANSI color codes from the returned terminal text. By default the
    /// raw output is returned WITH colors preserved. Defaults to false.
    #[serde(default)]
    pub strip_ansi: Option<bool>,

    /// Descriptive filename for the screenshot (without extension). Should be
    /// specific enough to identify the content at a glance among other
    /// screenshots in the same project: when a report folder holds 20 images,
    /// each name should tell you what is in it without opening it. Consider the
    /// context (which project, which phase, which comparison) when naming.
    /// Examples: secretsdump-corp-local-before-hardening, nmap-initial-scan-dmz,
    /// git-log-after-refactor, finding-03-sqli-login-page. When omitted, a
    /// fallback name is derived as `{working-dir}-{first-command-word}`. The
    /// name is sanitized (lowercased, symbols to hyphens) and made unique
    /// (`-2`, `-3`, ...) within the output directory.
    #[serde(default)]
    pub output_name: Option<String>,

    /// Trim the rendered image width to the rightmost content, keeping the
    /// same padding on the right as on the left, instead of using the full
    /// terminal width. Defaults to true. Set to false to keep the full `cols`
    /// width.
    #[serde(default)]
    pub auto_crop: Option<bool>,

    /// Show only the FIRST N lines of the output. By default the screenshot
    /// shows EVERY line the command produced, including everything that
    /// scrolled out of the `rows`-high viewport (`rows` controls where lines
    /// wrap, not how much is shown). Mutually exclusive with `tail_lines`.
    #[serde(default)]
    pub head_lines: Option<usize>,

    /// Show only the LAST N lines of the output (like `tail -n`). By default
    /// every retained line is shown. Mutually exclusive with `head_lines`.
    #[serde(default)]
    pub tail_lines: Option<usize>,
}

/// Current MCP request for `execute_and_screenshot`.
///
/// This is separate from [`ExecuteAndScreenshotParams`] to preserve the
/// published Rust API while allowing the wire protocol to evolve.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ExecuteAndScreenshotRequest {
    /// One shell command to execute. Prefer passing either `command` or
    /// `commands`. If an older client sends both, `commands` takes precedence
    /// for compatibility. The command is typed into the real interactive shell
    /// when `show_prompt` is true.
    #[serde(default)]
    pub command: Option<String>,

    /// Several commands to execute in order. Prefer passing either `commands`
    /// or `command`; this field takes precedence if both are sent for
    /// compatibility with the original required-`command` schema. Each command
    /// receives its own real shell prompt when `show_prompt` is true.
    #[serde(default)]
    pub commands: Option<Vec<String>>,

    /// Working directory for the child shell and its initial prompt. Relative
    /// paths resolve from the MCP server's launch directory; `~` is supported.
    ///
    /// Set this when the directory is meaningful context. If the full source
    /// path is incidental or sensitive, use a short staging directory that
    /// contains the needed inputs, or disable the prompt. Do not put `cd ...`
    /// in the command merely to alter the prompt, and never print or synthesize
    /// a fake prompt.
    #[serde(default)]
    pub cwd: Option<String>,

    /// Terminal width in columns. Defaults to server config value (120).
    #[serde(default)]
    pub cols: Option<u16>,

    /// Terminal height in rows. Defaults to server config value (40).
    #[serde(default)]
    pub rows: Option<u16>,

    /// Maximum time in seconds to wait for the command to finish. Defaults to
    /// 30.
    #[serde(default)]
    pub timeout_secs: Option<u64>,

    /// If true (default), run in the user's real interactive login shell so
    /// their configured prompt, aliases, and PATH are captured. A prompt is
    /// shown before each captured command; the final prompt after the last
    /// command is always removed automatically. No trailing-prompt option or
    /// image cropping is needed.
    ///
    /// Never echo, print, or manually style a prompt. With `show_prompt:
    /// false`, prompt-like text is ordinary command output and cannot be
    /// identified or removed safely.
    #[serde(default)]
    pub show_prompt: Option<bool>,

    /// Theme name for rendering. Uses default theme from config if unspecified.
    #[serde(default)]
    pub theme: Option<String>,

    /// Chrome preset: none, minimal, gnome, macos, report.
    #[serde(default)]
    pub chrome: Option<String>,

    /// Optional chrome title.
    #[serde(default)]
    pub title: Option<String>,

    /// Whether to add a UTC timestamp watermark below the terminal content.
    #[serde(default)]
    pub timestamp: Option<bool>,

    /// Draw soft rounded corners (default: true).
    #[serde(default)]
    pub rounded: Option<bool>,

    /// Enable or disable built-in sensitive-data redaction. When omitted, the
    /// server's config decides.
    #[serde(default)]
    pub redact: Option<bool>,

    /// Specific built-in/configured redaction rules to apply.
    #[serde(default)]
    pub redaction_rules: Option<Vec<String>>,

    /// Manual regex or coordinate redactions applied while rendering.
    #[serde(default)]
    pub redactions: Option<Vec<ManualRedactionSpec>>,

    /// Also redact returned terminal text. The PNG alone is redacted by
    /// default.
    #[serde(default)]
    pub redact_text: Option<bool>,

    /// Draw labels over redaction blocks. Defaults to true.
    #[serde(default)]
    pub show_labels: Option<bool>,

    /// Strip ANSI codes from returned text. Defaults to false.
    #[serde(default)]
    pub strip_ansi: Option<bool>,

    /// Descriptive PNG base name. When omitted, the fallback uses `cwd` (when
    /// supplied) and the first command word.
    #[serde(default)]
    pub output_name: Option<String>,

    /// Trim image width to the rightmost content. Defaults to true.
    #[serde(default)]
    pub auto_crop: Option<bool>,

    /// Show only the first N logical output lines.
    #[serde(default)]
    pub head_lines: Option<usize>,

    /// Show only the last N logical output lines.
    #[serde(default)]
    pub tail_lines: Option<usize>,
}

impl From<ExecuteAndScreenshotParams> for ExecuteAndScreenshotRequest {
    fn from(params: ExecuteAndScreenshotParams) -> Self {
        let command = params.commands.is_none().then_some(params.command);
        Self {
            command,
            commands: params.commands,
            cwd: None,
            cols: params.cols,
            rows: params.rows,
            timeout_secs: params.timeout_secs,
            show_prompt: params.show_prompt,
            theme: params.theme,
            chrome: params.chrome,
            title: params.title,
            timestamp: params.timestamp,
            rounded: params.rounded,
            redact: params.redact,
            redaction_rules: params.redaction_rules,
            redactions: params.redactions,
            redact_text: params.redact_text,
            show_labels: params.show_labels,
            strip_ansi: params.strip_ansi,
            output_name: params.output_name,
            auto_crop: params.auto_crop,
            head_lines: params.head_lines,
            tail_lines: params.tail_lines,
        }
    }
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RenderAnsiParams {
    /// Path to a file containing raw terminal output with ANSI escape sequences.
    pub input_path: String,

    /// Terminal width in columns for rendering. Defaults to 120.
    #[serde(default)]
    pub cols: Option<u16>,

    /// Terminal height in rows for rendering. Defaults to 40.
    #[serde(default)]
    pub rows: Option<u16>,

    /// Theme name for rendering. Uses default theme from config if not specified.
    #[serde(default)]
    pub theme: Option<String>,

    /// Chrome preset: none, minimal, gnome, macos, report.
    #[serde(default)]
    pub chrome: Option<String>,

    /// Optional chrome title.
    #[serde(default)]
    pub title: Option<String>,

    /// Whether to add a UTC timestamp watermark below the terminal content.
    #[serde(default)]
    pub timestamp: Option<bool>,

    /// Draw soft rounded corners (default: true). With chrome the window frame
    /// is rounded; without chrome the terminal content itself gets rounded
    /// corners on a transparent background. Set false for square corners.
    #[serde(default)]
    pub rounded: Option<bool>,

    /// Strip ANSI color codes from the returned terminal text. By default the
    /// raw output is returned WITH colors preserved. Defaults to false.
    #[serde(default)]
    pub strip_ansi: Option<bool>,

    /// Optional descriptive base name for the output PNG (without extension).
    /// When omitted, a name is derived from the input file name. The name is
    /// sanitized and made unique within the output directory.
    #[serde(default)]
    pub output_name: Option<String>,

    /// Trim the rendered image width to the rightmost content, keeping the
    /// same padding on the right as on the left, instead of using the full
    /// terminal width. Defaults to true. Set to false to keep the full `cols`
    /// width.
    #[serde(default)]
    pub auto_crop: Option<bool>,

    /// Enable or disable redaction of sensitive data for this render. When
    /// omitted, the server's config decides (auto redaction). Set to false to
    /// force redaction off.
    #[serde(default)]
    pub redact: Option<bool>,

    /// Specific redaction rule names to apply (default: all enabled rules).
    /// Providing this implies redaction is enabled.
    #[serde(default)]
    pub redaction_rules: Option<Vec<String>>,

    /// Manual redactions applied to this render: regex patterns and/or explicit
    /// cell ranges, exactly the specifications `redact_screenshot` and the
    /// CLI's repeatable `--redaction '<JSON>'` option take. They are applied in
    /// order (patterns first, then cell ranges) on top of any rule-based
    /// redaction. Providing this masks the render even when `redact` is
    /// omitted; add `redact: true` (or `redaction_rules`) to run the built-in
    /// rules as well. Conflicts with `redact: false`.
    #[serde(default)]
    pub redactions: Option<Vec<ManualRedactionSpec>>,

    /// Also redact the returned terminal text. By default only the PNG image
    /// is redacted and the returned text keeps the ORIGINAL content.
    #[serde(default)]
    pub redact_text: Option<bool>,

    /// Whether to draw a short `[LABEL]` tag over each redaction block.
    /// Defaults to true.
    #[serde(default)]
    pub show_labels: Option<bool>,

    /// Render only the FIRST N lines of the file. By default every line is
    /// rendered, including everything that scrolled out of the `rows`-high
    /// viewport. Mutually exclusive with `tail_lines`.
    #[serde(default)]
    pub head_lines: Option<usize>,

    /// Render only the LAST N lines of the file (like `tail -n`). By default
    /// every line is rendered. Mutually exclusive with `head_lines`.
    #[serde(default)]
    pub tail_lines: Option<usize>,
}

/// A single selective redaction for `redact_screenshot`: either a regex
/// pattern (redacts every match) or an explicit cell range.
///
/// This is the enum published in 1.0.0 and it keeps exactly the variants and
/// fields it was published with, so an old literal - written with no `..` and
/// no knowledge of per-redaction colors - still compiles.
///
/// New work should use [`ManualRedactionSpec`], the specification the CLI's
/// `--redaction` option and the `redact_screenshot` tool schema share: it adds
/// a per-redaction `color` and accepts `label` as an alias for a pattern's
/// `replacement`. Converting is infallible ([`From`]), because everything this
/// type can express the shared one can.
#[derive(Debug, Clone, Deserialize, schemars::JsonSchema)]
#[serde(untagged)]
pub enum RedactionSpec {
    /// Redact every match of a regex pattern.
    Pattern {
        /// Regex pattern to match against the terminal text.
        pattern: String,
        /// Replacement marker used to derive the on-image `[LABEL]` tag.
        #[serde(default)]
        replacement: Option<String>,
        /// Number of leading matched characters to leave unmasked. When set,
        /// only the characters after the prefix are blocked out (e.g. show
        /// `AKIA****` for an AWS key). Defaults to 0 (mask everything).
        #[serde(default)]
        keep_prefix: Option<usize>,
        /// Number of trailing matched characters to leave unmasked. When set,
        /// only the characters before the suffix are blocked out. Defaults to
        /// 0 (mask everything).
        #[serde(default)]
        keep_suffix: Option<usize>,
    },
    /// Redact an explicit cell range on a single row (0-based).
    ///
    /// Coordinates are validated against the screenshot before anything is
    /// drawn: a row at or past its last row, a column at or past its last
    /// column, or a `col_start` that is not before `col_end` is rejected with
    /// an error naming the screenshot's real dimensions.
    Coordinate {
        /// Row index (0-based), counted in the screenshot as rendered: row 0 is
        /// the topmost line the PNG shows, which for a `head_lines` /
        /// `tail_lines` capture is the first line of that selection. Must be
        /// less than the number of rows the screenshot shows.
        row: u16,
        /// First column to redact (0-based, inclusive). Must be less than both
        /// `col_end` and the screenshot's width.
        col_start: u16,
        /// One past the last column to redact (exclusive). Must be greater than
        /// `col_start` and no greater than the screenshot's width.
        col_end: u16,
        /// Short label drawn over the redaction block.
        #[serde(default)]
        label: Option<String>,
    },
}

/// A 1.0.0 specification is a shared one that never sets a color.
impl From<RedactionSpec> for ManualRedactionSpec {
    fn from(spec: RedactionSpec) -> Self {
        match spec {
            RedactionSpec::Pattern {
                pattern,
                replacement,
                keep_prefix,
                keep_suffix,
            } => ManualRedactionSpec::Pattern {
                pattern,
                replacement,
                keep_prefix,
                keep_suffix,
                color: None,
            },
            RedactionSpec::Coordinate {
                row,
                col_start,
                col_end,
                label,
            } => ManualRedactionSpec::Coordinate {
                row,
                col_start,
                col_end,
                label,
                color: None,
            },
        }
    }
}

/// The parameters `redact_screenshot` was published with in 1.0.0.
///
/// Kept verbatim - including `redactions: Vec<RedactionSpec>` - so a 1.0.0
/// literal still compiles, and [`ScreenshotServer::redact_screenshot`] still
/// takes it. The published tool schema describes
/// [`RedactScreenshotRequest`], which carries the shared
/// [`ManualRedactionSpec`]; `From`/[`RedactScreenshotParams::into_request`]
/// converts between the two, and both run the same implementation.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RedactScreenshotParams {
    /// Path to a screenshot PNG produced by THIS server instance in the current
    /// session (via execute_and_screenshot or render_ansi). The raw output and
    /// render metadata are kept in memory, so this only works for screenshots
    /// created since the server last started, and not for CLI-produced images.
    pub screenshot_path: String,

    /// Redactions to apply: regex patterns and/or explicit cell ranges.
    pub redactions: Vec<RedactionSpec>,

    /// Also redact the returned terminal text. By default the returned text is
    /// the ORIGINAL (unredacted) content; only the PNG is redacted. Defaults to
    /// false.
    #[serde(default)]
    pub redact_text: Option<bool>,

    /// Whether to draw a label over each redaction block. Defaults to true.
    /// For a regex `pattern`, the label is the `replacement` field (drawn only
    /// when provided); for a coordinate redaction it is the `label` field. Set
    /// to false to draw plain solid blocks with no text overlay.
    #[serde(default)]
    pub show_labels: Option<bool>,

    /// Strip ANSI color codes from the returned terminal text. By default the
    /// raw output is returned WITH colors preserved. Defaults to false.
    #[serde(default)]
    pub strip_ansi: Option<bool>,
}

impl RedactScreenshotParams {
    /// Convert the 1.0.0 parameters into the request the tool takes today.
    pub fn into_request(self) -> RedactScreenshotRequest {
        self.into()
    }
}

impl From<RedactScreenshotParams> for RedactScreenshotRequest {
    fn from(params: RedactScreenshotParams) -> Self {
        Self {
            screenshot_path: params.screenshot_path,
            redactions: params
                .redactions
                .into_iter()
                .map(ManualRedactionSpec::from)
                .collect(),
            redact_text: params.redact_text,
            show_labels: params.show_labels,
            strip_ansi: params.strip_ansi,
        }
    }
}

/// The parameters the `redact_screenshot` tool takes, and the ones its
/// published schema describes.
///
/// Identical to the 1.0.0 [`RedactScreenshotParams`] except that its
/// redactions are [`ManualRedactionSpec`]s - the specification the CLI's
/// `--redaction` option parses - so the tool and the CLI accept exactly the
/// same JSON. It is a separate struct because changing the field type in place
/// would break every 1.0.0 literal, and it is taken by a separate handler
/// ([`ScreenshotServer::redact_screenshot_tool`]) so that the 1.0.0
/// [`ScreenshotServer::redact_screenshot`] keeps its published signature.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct RedactScreenshotRequest {
    /// Path to a screenshot PNG produced by THIS server instance in the current
    /// session (via execute_and_screenshot or render_ansi). The raw output and
    /// render metadata are kept in memory, so this only works for screenshots
    /// created since the server last started, and not for CLI-produced images.
    pub screenshot_path: String,

    /// Redactions to apply: regex patterns and/or explicit cell ranges. This
    /// is the same specification the CLI takes through its repeatable
    /// `--redaction '<JSON>'` option on `exec` and `render`.
    pub redactions: Vec<ManualRedactionSpec>,

    /// Also redact the returned terminal text. By default the returned text is
    /// the ORIGINAL (unredacted) content; only the PNG is redacted. Defaults to
    /// false.
    #[serde(default)]
    pub redact_text: Option<bool>,

    /// Whether to draw a label over each redaction block. Defaults to true.
    /// For a regex `pattern`, the label is the `replacement` field (drawn only
    /// when provided); for a coordinate redaction it is the `label` field. Set
    /// to false to draw plain solid blocks with no text overlay.
    #[serde(default)]
    pub show_labels: Option<bool>,

    /// Strip ANSI color codes from the returned terminal text. By default the
    /// raw output is returned WITH colors preserved. Defaults to false.
    #[serde(default)]
    pub strip_ansi: Option<bool>,
}

#[derive(Debug, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ComposeScreenshotsParams {
    /// Paths to two or more PNG screenshots to combine, in order.
    pub paths: Vec<String>,

    /// Layout: "vertical" (stacked top-to-bottom, tmux-style) or "horizontal"
    /// (side by side). Defaults to "vertical".
    #[serde(default)]
    pub layout: Option<String>,

    /// Divider thickness in pixels drawn between adjacent panes (tmux-style
    /// split). Defaults to 2. Set to 0 for no divider line.
    #[serde(default)]
    pub divider: Option<u32>,

    /// Theme name whose background color fills the canvas. Uses the server's
    /// default theme when omitted.
    #[serde(default)]
    pub theme: Option<String>,

    /// Wrap the composed result in a single outer window frame. Chrome preset:
    /// "none", "minimal", "gnome", "macos", "report". Inputs should be raw
    /// (chrome-less) screenshots so only this outer frame is drawn. Omit for no
    /// outer chrome.
    #[serde(default)]
    pub chrome: Option<String>,

    /// Optional title for the outer chrome frame (only used with `chrome`).
    #[serde(default)]
    pub title: Option<String>,

    /// Output PNG path. When omitted, a file is auto-generated in the output
    /// directory.
    #[serde(default)]
    pub output: Option<String>,
}

/// A screenshot's source data retained in memory so it can be re-rendered
/// (e.g. by `redact_screenshot`) without any on-disk sidecar files.
#[derive(Clone)]
struct CachedRender {
    data: Vec<u8>,
    /// The 1.0.0 [`RenderMeta`] plus the line selection and truncation flag the
    /// screenshot was rendered with, so a re-render reproduces exactly the rows
    /// the image shows.
    context: RenderContext,
    /// Monotonic insertion counter, used to evict the oldest entries first.
    serial: u64,
}

/// Maximum number of screenshots kept in the in-memory render cache.
const MAX_CACHE_ENTRIES: usize = 32;
/// Maximum total size of the raw terminal bytes held by the render cache.
const MAX_CACHE_BYTES: usize = 32 * 1024 * 1024;

/// Canonical cache key for a screenshot path, so `./out/x.png` and
/// `/abs/out/x.png` resolve to the same entry.
fn cache_key(path: &Path) -> String {
    std::fs::canonicalize(path)
        .unwrap_or_else(|_| path.to_path_buf())
        .display()
        .to_string()
}

/// Drop the oldest cache entries until the entry-count and byte budgets hold.
/// Bounding the cache keeps a long-lived server from growing without limit and
/// limits how long plaintext captures linger in memory.
fn evict_cache(cache: &mut HashMap<String, CachedRender>) {
    let over_budget = |cache: &HashMap<String, CachedRender>| {
        cache.len() > MAX_CACHE_ENTRIES
            || cache.values().map(|c| c.data.len()).sum::<usize>() > MAX_CACHE_BYTES
    };
    while over_budget(cache) && cache.len() > 1 {
        let oldest = cache
            .iter()
            .min_by_key(|(_, c)| c.serial)
            .map(|(k, _)| k.clone());
        match oldest {
            Some(key) => {
                cache.remove(&key);
            }
            None => break,
        }
    }
}

#[derive(Clone)]
pub struct ScreenshotServer {
    config: Arc<Config>,
    renderer: Arc<Renderer>,
    /// Raw terminal bytes + render metadata for screenshots produced this
    /// session, keyed by PNG path. Populated by execute_and_screenshot /
    /// render_ansi and consumed by redact_screenshot. Lost on restart.
    render_cache: Arc<Mutex<HashMap<String, CachedRender>>>,
    tool_router: ToolRouter<Self>,
}

#[tool_router]
impl ScreenshotServer {
    pub fn new(config: Config, renderer: Renderer) -> Self {
        Self {
            config: Arc::new(config),
            renderer: Arc::new(renderer),
            render_cache: Arc::new(Mutex::new(HashMap::new())),
            tool_router: Self::tool_router(),
        }
    }

    /// Remember a rendered screenshot's source bytes + metadata in memory so it
    /// can later be re-rendered by `redact_screenshot`.
    ///
    /// The cache holds raw terminal bytes (plaintext, including anything the
    /// image redacts), so it is bounded: the oldest entries are evicted once
    /// [`MAX_CACHE_ENTRIES`] or [`MAX_CACHE_BYTES`] is exceeded, rather than
    /// keeping every capture for the lifetime of the process.
    fn remember_render(&self, path: &Path, data: &[u8], context: RenderContext) {
        let mut cache = match self.render_cache.lock() {
            Ok(cache) => cache,
            Err(_) => {
                tracing::warn!("Render cache lock poisoned; screenshot will not be re-renderable");
                return;
            }
        };
        let key = cache_key(path);
        let serial = cache.values().map(|c| c.serial).max().unwrap_or(0) + 1;
        cache.insert(
            key,
            CachedRender {
                data: data.to_vec(),
                context,
                serial,
            },
        );
        evict_cache(&mut cache);
    }

    /// Resolve this request's redaction policy and build the matching engine.
    /// Shared by `execute_and_screenshot` and `render_ansi` so both honor the
    /// server's `[redaction] auto` setting and fail closed when redaction was
    /// explicitly requested but cannot be enabled.
    fn resolve_redaction(
        &self,
        redact: Option<bool>,
        rules: Option<&Vec<String>>,
        show_labels: bool,
    ) -> Result<Option<RedactionEngine>, McpError> {
        let redact_flag = redact == Some(true) || rules.is_some();
        let no_redact_flag = redact == Some(false);
        // The master switch wins over an explicit request, but the caller must
        // hear about it instead of receiving an unredacted screenshot.
        if explicit_request_is_blocked(&self.config.redaction, redact_flag, no_redact_flag) {
            return Err(McpError::invalid_params(
                REDACTION_DISABLED_MSG.to_string(),
                None,
            ));
        }
        if !resolve_should_redact(&self.config.redaction, redact_flag, no_redact_flag) {
            return Ok(None);
        }
        match RedactionEngine::from_config_with_labels(&self.config.redaction, show_labels) {
            Ok(engine) => {
                // An explicit rule list with an unknown name must fail loudly
                // instead of silently redacting nothing.
                if let Some(rules) = rules {
                    engine
                        .validate_rule_names(rules)
                        .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
                }
                Ok(Some(engine))
            }
            Err(e) if redact_flag => Err(McpError::internal_error(
                format!("redaction was requested but could not be enabled: {}", e),
                None,
            )),
            Err(e) => {
                // Auto-redaction is best-effort: warn and continue.
                tracing::warn!("Auto-redaction disabled: {}", e);
                Ok(None)
            }
        }
    }

    /// Execute a shell command in a real terminal and capture a PNG screenshot
    /// of the output.
    ///
    /// Manual redactions: `redactions` takes the same regex-pattern and
    /// cell-range specifications as `redact_screenshot` and the CLI's
    /// repeatable `--redaction '<JSON>'` option, applied to this screenshot as
    /// it is rendered. Passing them masks the image even without `redact`; add
    /// `redact: true` (or `redaction_rules`) to run the built-in rules too.
    ///
    /// The command runs in a PTY (pseudo-terminal), so all ANSI escape
    /// sequences (colors, formatting, cursor movement) are rendered into an
    /// image that looks like a real terminal. When `show_prompt` is true
    /// (default), it runs in an interactive login shell so the screenshot
    /// includes the user's real shell prompt before each command (username,
    /// host, directory, ...), but never the final prompt after the last
    /// command.
    /// Set `cwd` before capture when the prompt should identify a meaningful
    /// project directory. If a path is incidental, use a short staging
    /// directory or hide the prompt. Never synthesize a prompt in `command`:
    /// termshot strips the final real shell prompt, but prompt-like command
    /// output must be preserved.
    ///
    /// Redaction: by default the rendered PNG is automatically scanned and
    /// masked for known secret patterns (IPs, AWS keys, JWTs, private keys,
    /// emails, internal hostnames, API keys, ...), while the RETURNED TEXT
    /// keeps the ORIGINAL, unredacted content so you can see exactly what was
    /// on screen. Review that text and, if anything else is sensitive, call
    /// `redact_screenshot` with the returned screenshot path to mask it in the
    /// PNG. Set `redact_text: true` to also scrub the returned text, or
    /// `redact: false` to disable auto-redaction for this call.
    ///
    /// The PNG filename is best set with `output_name`: choose a name specific
    /// enough to identify the screenshot at a glance among others in the same
    /// project (e.g. `nmap-initial-scan-dmz` or `finding-03-sqli-login-page`).
    /// When omitted, a fallback name is derived as
    /// `{working-dir}-{first-command-word}` (e.g. `nrs-cargo`).
    ///
    /// Returns the saved PNG path, the exit status, an optional redaction audit
    /// summary, and the terminal text output.
    #[tool(name = "execute_and_screenshot")]
    pub async fn execute_and_screenshot_tool(
        &self,
        Parameters(params): Parameters<ExecuteAndScreenshotRequest>,
    ) -> Result<CallToolResult, McpError> {
        self.execute_and_screenshot_impl(params).await
    }

    /// Direct-call API published in 1.0.0.
    ///
    /// The MCP router uses [`ScreenshotServer::execute_and_screenshot_tool`],
    /// whose request adds `cwd` and permits `commands` without a redundant
    /// `command`. This wrapper preserves the original Rust method signature.
    pub async fn execute_and_screenshot(
        &self,
        Parameters(params): Parameters<ExecuteAndScreenshotParams>,
    ) -> Result<CallToolResult, McpError> {
        self.execute_and_screenshot_impl(params.into()).await
    }

    async fn execute_and_screenshot_impl(
        &self,
        params: ExecuteAndScreenshotRequest,
    ) -> Result<CallToolResult, McpError> {
        let cols = params.cols.unwrap_or(self.config.default_cols);
        let rows = params.rows.unwrap_or(self.config.default_rows);
        validate_dimensions(cols, rows)?;
        let timeout = Duration::from_secs(
            params
                .timeout_secs
                .unwrap_or(self.config.default_timeout_secs),
        );
        let lines = line_selection(params.head_lines, params.tail_lines)?;
        let show_labels = params.show_labels.unwrap_or(true);
        // Compile the caller's `redactions` before the command runs, so an
        // invalid regex, color, or coordinate range fails without having
        // executed anything - exactly as the CLI's `--redaction` does.
        let manual = manual_redactions(params.redactions.as_deref(), params.redact, show_labels)?;
        let show_prompt = params.show_prompt.unwrap_or(true);
        let commands = request_commands(params.command, params.commands)?;
        let working_dir = params
            .cwd
            .as_deref()
            .map(|path| executor::resolve_working_directory(Path::new(path)))
            .transpose()
            .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
        let command_refs: Vec<&str> = commands.iter().map(|s| s.as_str()).collect();
        let chrome_options = chrome_options_from_params(
            &self.config,
            params.chrome,
            params.title,
            params.timestamp,
            params.rounded,
            commands.first().map(String::as_str),
        );

        let result = if show_prompt {
            executor::execute_command_in_dir(
                &command_refs,
                &self.config.shell,
                rows,
                cols,
                timeout,
                working_dir.as_deref(),
            )
            .await
        } else {
            // Each element of `commands` is an independent command line, so
            // join them with newlines (not spaces) when running without a
            // prompt, so `["pwd", "whoami"]` runs as two commands.
            executor::execute_command_simple_in_dir(
                &commands.join("\n"),
                &self.config.shell,
                rows,
                cols,
                timeout,
                working_dir.as_deref(),
            )
            .await
        };

        let exec_result = result.map_err(|e| {
            McpError::internal_error(format!("Command execution failed: {}", e), None)
        })?;

        let theme_name = params.theme.as_deref();

        // Resolve redaction: an explicit `redact` flag (or a rules list) wins;
        // otherwise fall back to the server's auto-redaction config.
        let redaction_engine =
            self.resolve_redaction(params.redact, params.redaction_rules.as_ref(), show_labels)?;
        let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
            engine,
            rules: params.redaction_rules.clone(),
        });

        let text_options = TextOptions {
            strip_ansi: params.strip_ansi.unwrap_or(false),
            redact_text: params.redact_text.unwrap_or(false),
            embed_description: self.config.embed_description,
            // An interactive capture's raw stream is a terminal session, not a
            // document: it carries readline redraws, title and bracketed-paste
            // sequences, and the trailing prompt the screenshot drops. Its text
            // comes from the screen so it matches the image exactly.
            from_screen: show_prompt,
        };

        // Derive the output PNG base name. An explicit `output_name` is the
        // preferred, descriptive choice; otherwise fall back to
        // `{cwd_basename}-{first_word_of_command}`.
        let output_name = params.output_name.clone().unwrap_or_else(|| {
            let fallback_dir = working_dir
                .as_deref()
                .map(std::path::PathBuf::from)
                .or_else(|| std::env::current_dir().ok());
            fallback_output_name(fallback_dir.as_deref(), &commands.join(" "))
        });

        let (image_path, plain_text, redactions, context) = self
            .renderer
            .render_bytes_with_extended_options(
                &exec_result.raw_output,
                cols,
                rows,
                &self.config.output_dir,
                Some(output_name.as_str()),
                theme_name,
                chrome_options.as_ref(),
                redaction_request.as_ref(),
                text_options,
                params.auto_crop.unwrap_or(true),
                ExtendedRenderOptions::default()
                    .with_lines(lines)
                    .with_optional_manual(manual.as_ref()),
            )
            .map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;

        let truncated = context.truncated;
        // Keep the source bytes + metadata in memory for later re-rendering.
        self.remember_render(&image_path, &exec_result.raw_output, context);

        let exit_info = if exec_result.timed_out {
            "TIMED OUT".to_string()
        } else {
            match exec_result.exit_code {
                Some(code) => format!("exit code: {}", code),
                None => "exit code: unknown".to_string(),
            }
        };

        let mut content = vec![
            ContentBlock::text(format!("Screenshot saved to: {}", image_path.display())),
            ContentBlock::text(format!("Status: {}", exit_info)),
        ];
        if !redactions.is_empty() {
            let summary = redactions
                .iter()
                .map(|(name, count)| format!("{}x {}", count, name))
                .collect::<Vec<_>>()
                .join(", ");
            content.push(ContentBlock::text(format!("Redacted: {}", summary)));
        }
        if truncated {
            content.push(ContentBlock::text(truncation_notice(
                self.renderer.effective_scrollback_lines(rows, cols),
            )));
        }
        content.push(ContentBlock::text(format!(
            "--- Terminal Output ---\n{}",
            plain_text
        )));

        Ok(CallToolResult::success(content))
    }

    /// Render a file containing raw ANSI terminal output to a PNG screenshot.
    ///
    /// Takes a path to a file that contains terminal output with ANSI escape
    /// sequences and renders it to a PNG image. Useful for rendering
    /// previously captured output.
    ///
    /// Manual redactions: `redactions` takes the same regex-pattern and
    /// cell-range specifications as `redact_screenshot` and the CLI's
    /// repeatable `--redaction '<JSON>'` option, applied as the image is
    /// rendered. Passing them masks the image even without `redact`; add
    /// `redact: true` (or `redaction_rules`) to run the built-in rules too.
    #[tool(name = "render_ansi")]
    pub async fn render_ansi(
        &self,
        Parameters(params): Parameters<RenderAnsiParams>,
    ) -> Result<CallToolResult, McpError> {
        let cols = params.cols.unwrap_or(self.config.default_cols);
        let rows = params.rows.unwrap_or(self.config.default_rows);
        validate_dimensions(cols, rows)?;
        let lines = line_selection(params.head_lines, params.tail_lines)?;
        let show_labels = params.show_labels.unwrap_or(true);
        // Compile the caller's `redactions` before the file is read, so an
        // invalid regex, color, or coordinate range fails up front - exactly
        // as the CLI's `--redaction` does.
        let manual = manual_redactions(params.redactions.as_deref(), params.redact, show_labels)?;
        let theme_name = params.theme.as_deref();
        let chrome_options = chrome_options_from_params(
            &self.config,
            params.chrome,
            params.title,
            params.timestamp,
            params.rounded,
            None,
        );

        let data = std::fs::read(&params.input_path).map_err(|e| {
            McpError::internal_error(
                format!("Failed to read file '{}': {}", params.input_path, e),
                None,
            )
        })?;

        // Derive the output name from an explicit override or the input file.
        let output_name = params.output_name.clone().or_else(|| {
            std::path::Path::new(&params.input_path)
                .file_stem()
                .map(|s| s.to_string_lossy().into_owned())
        });

        // Rendering a captured log honors the same redaction policy as
        // execution: this is exactly the case where the caller has not read
        // the content first.
        let redaction_engine =
            self.resolve_redaction(params.redact, params.redaction_rules.as_ref(), show_labels)?;
        let redaction_request = redaction_engine.as_ref().map(|engine| RedactionRequest {
            engine,
            rules: params.redaction_rules.clone(),
        });

        let (image_path, plain_text, redactions, context) = self
            .renderer
            .render_bytes_with_extended_options(
                &data,
                cols,
                rows,
                &self.config.output_dir,
                output_name.as_deref(),
                theme_name,
                chrome_options.as_ref(),
                redaction_request.as_ref(),
                TextOptions {
                    strip_ansi: params.strip_ansi.unwrap_or(false),
                    redact_text: params.redact_text.unwrap_or(false),
                    embed_description: self.config.embed_description,
                    // The file's bytes *are* the document here, so they are
                    // returned whole rather than clipped to the last screenful.
                    from_screen: false,
                },
                params.auto_crop.unwrap_or(true),
                ExtendedRenderOptions::default()
                    .with_lines(lines)
                    .with_optional_manual(manual.as_ref()),
            )
            .map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;

        let truncated = context.truncated;
        // Keep the source bytes + metadata in memory for later re-rendering.
        self.remember_render(&image_path, &data, context);

        let mut content = vec![ContentBlock::text(format!(
            "Screenshot saved to: {}",
            image_path.display()
        ))];
        if !redactions.is_empty() {
            let summary = redactions
                .iter()
                .map(|(name, count)| format!("{}x {}", count, name))
                .collect::<Vec<_>>()
                .join(", ");
            content.push(ContentBlock::text(format!("Redacted: {}", summary)));
        }
        if truncated {
            content.push(ContentBlock::text(truncation_notice(
                self.renderer.effective_scrollback_lines(rows, cols),
            )));
        }
        content.push(ContentBlock::text(format!(
            "--- Terminal Output ---\n{}",
            plain_text
        )));

        Ok(CallToolResult::success(content))
    }

    /// Apply selective redactions to a screenshot from this session and
    /// overwrite it in place.
    ///
    /// Agent-driven workflow: run `execute_and_screenshot` (or `render_ansi`),
    /// inspect the returned plain text, decide what is sensitive, then call
    /// this tool with the returned screenshot path plus regex patterns and/or
    /// cell coordinates. The original terminal output is re-parsed from the
    /// server's in-memory record (no sidecar files on disk), the redactions are
    /// applied, and the PNG is re-rendered. This only works for screenshots
    /// produced by this server instance since it last started.
    ///
    /// The screenshot is re-rendered from the same capture and line selection it
    /// was made with, so patterns match every line it shows - including output
    /// that scrolled out of the terminal viewport - and `row` coordinates count
    /// from the top of the image.
    ///
    /// Each redaction is either a regex `pattern` (with optional `replacement`
    /// - also accepted as `label` - used as the on-image `[LABEL]` tag) or an
    /// explicit cell range (`row`, `col_start`, `col_end`, optional `label`).
    /// Either kind may set its own `#RRGGBB` `color`. A pattern with no
    /// `replacement` draws a plain block with no label. Set `show_labels: false`
    /// to draw plain blocks for every redaction in the call.
    ///
    /// Partial redaction: a pattern may set `keep_prefix` and/or `keep_suffix`
    /// (character counts) to leave the first/last characters of each match
    /// visible and mask only the middle. For a hash like
    /// `8846f7eaee8fb117ad06bdd830b7586c`, `keep_prefix: 4` renders
    /// `8846████████████████████████████`, and for an AWS key `AKIA...`,
    /// `keep_prefix: 4` shows `AKIA████████████████`.
    ///
    /// Cell ranges are checked against what the screenshot actually renders
    /// before anything is drawn: trailing blank rows are trimmed away and (with
    /// `auto_crop`, the default) so are the empty columns to the right of the
    /// output, so a row or column that the capture retains but the image never
    /// paints is an error naming the requested coordinates and the rendered
    /// dimensions, rather than a redaction that quietly covers nothing. An
    /// empty `col_start`/`col_end` interval is refused the same way.
    ///
    /// By default the returned text is the ORIGINAL content; set `redact_text`
    /// to return the scrubbed text.
    #[tool(name = "redact_screenshot")]
    pub async fn redact_screenshot_tool(
        &self,
        Parameters(params): Parameters<RedactScreenshotRequest>,
    ) -> Result<CallToolResult, McpError> {
        self.redact_screenshot_impl(params).await
    }

    /// [`ScreenshotServer::redact_screenshot_tool`], called with the parameter
    /// struct published in 1.0.0.
    ///
    /// This is the method signature 1.0.0 exposed - `Parameters` of
    /// [`RedactScreenshotParams`], whose redactions are
    /// [`RedactionSpec`]s - kept so a Rust caller that drives the server
    /// directly still compiles. It converts to the shared specification and
    /// runs the same implementation the tool does, so the two can never
    /// disagree. The MCP wire name and schema belong to
    /// [`ScreenshotServer::redact_screenshot_tool`], which is what the router
    /// publishes.
    pub async fn redact_screenshot(
        &self,
        Parameters(params): Parameters<RedactScreenshotParams>,
    ) -> Result<CallToolResult, McpError> {
        self.redact_screenshot_impl(params.into()).await
    }

    /// The one implementation behind both entry points above.
    async fn redact_screenshot_impl(
        &self,
        params: RedactScreenshotRequest,
    ) -> Result<CallToolResult, McpError> {
        let png_path = std::path::PathBuf::from(&params.screenshot_path);
        let key = cache_key(&png_path);

        let cached = {
            let cache = self.render_cache.lock().map_err(|_| {
                McpError::internal_error("Render cache lock poisoned".to_string(), None)
            })?;
            cache.get(&key).cloned()
        };
        let CachedRender { data, context, .. } = cached.ok_or_else(|| {
            McpError::invalid_params(
                format!(
                    "No in-memory record for screenshot '{}'. It must have been produced \
                     by this server instance in the current session (records are lost on \
                     restart and are not created by the CLI).",
                    key
                ),
                None,
            )
        })?;

        let show_labels = params.show_labels.unwrap_or(true);

        // Compile the requested redactions - the same shared specification the
        // CLI's `--redaction` option parses - so an invalid regex or color is
        // refused before anything is drawn.
        let manual = ManualRedactions::new(&params.redactions, show_labels)
            .map_err(|e| McpError::invalid_params(e.to_string(), None))?;

        // The capture the re-render will draw, built once: patterns are matched
        // against it and coordinates are validated against the part of it the
        // renderer actually paints. Its size is what a `row`/`col` means here -
        // a head/tail selection or a long scrollback makes it a different shape
        // from the PTY viewport - so it has to exist before a single cell is
        // masked.
        let screen = self.renderer.capture_for(&data, &context);
        let (rendered_rows, rendered_cols) = self.renderer.rendered_bounds_for(&screen, &context);
        manual
            .validate_bounds(rendered_rows, rendered_cols)
            .map_err(|e| McpError::invalid_params(e.to_string(), None))?;

        // Build the combined redaction map: regex matches first, then manual
        // coordinate ranges.
        let mut map = RedactionMap::default();
        manual.apply_to(&screen, &mut map);
        drop(screen);

        let (plain_text, audit) = self
            .renderer
            .render_redaction_to_with_context(
                &data,
                &context,
                &map,
                &png_path,
                TextOptions {
                    strip_ansi: params.strip_ansi.unwrap_or(false),
                    redact_text: params.redact_text.unwrap_or(false),
                    embed_description: self.config.embed_description,
                    // Re-rendering returns text of the same kind the original
                    // capture did.
                    from_screen: context.meta.from_screen,
                },
            )
            .map_err(|e| McpError::internal_error(format!("Rendering failed: {}", e), None))?;

        let mut content = vec![ContentBlock::text(format!(
            "Redacted screenshot saved to: {}",
            png_path.display()
        ))];
        if !audit.is_empty() {
            let summary = audit
                .iter()
                .map(|(name, count)| format!("{}x {}", count, name))
                .collect::<Vec<_>>()
                .join(", ");
            content.push(ContentBlock::text(format!("Redacted: {}", summary)));
        }
        content.push(ContentBlock::text(format!(
            "--- Terminal Output ---\n{}",
            plain_text
        )));

        Ok(CallToolResult::success(content))
    }

    /// Compose two or more existing screenshots into a single image, placed
    /// side by side (horizontal) or stacked (vertical) like tmux split panes:
    /// adjacent with no gap, separated by a thin solid divider line. Panes are
    /// padded (never rescaled) to a common height (horizontal) or width
    /// (vertical) so the seams line up. Useful for comparing before/after runs,
    /// different themes, or related outputs.
    #[tool(name = "compose_screenshots")]
    pub async fn compose_screenshots(
        &self,
        Parameters(params): Parameters<ComposeScreenshotsParams>,
    ) -> Result<CallToolResult, McpError> {
        if params.paths.len() < 2 {
            return Err(McpError::invalid_params(
                "compose_screenshots requires at least two image paths".to_string(),
                None,
            ));
        }

        let layout = ComposeLayout::parse(params.layout.as_deref().unwrap_or("vertical"))
            .map_err(|e| McpError::invalid_params(e.to_string(), None))?;
        let divider = params.divider.unwrap_or(2);
        let paths: Vec<std::path::PathBuf> =
            params.paths.iter().map(std::path::PathBuf::from).collect();
        let output = params.output.as_ref().map(std::path::PathBuf::from);
        let chrome_options =
            chrome_options_from_params(&self.config, params.chrome, params.title, None, None, None);

        let path = self
            .renderer
            .compose_screenshots(
                &paths,
                layout,
                divider,
                params.theme.as_deref(),
                chrome_options.as_ref(),
                &self.config.output_dir,
                output.as_deref(),
                // Composition follows the server's global embed_description
                // policy; there is deliberately no per-call toggle.
                self.config.embed_description,
            )
            .map_err(|e| McpError::internal_error(format!("Compose failed: {}", e), None))?;

        Ok(CallToolResult::success(vec![ContentBlock::text(format!(
            "Composed screenshot saved to: {}",
            path.display()
        ))]))
    }
}

impl ScreenshotServer {
    /// The tool definitions this server publishes, exactly as an MCP client
    /// sees them (including each tool's JSON input schema).
    pub fn tool_definitions() -> Vec<Tool> {
        Self::tool_router().list_all()
    }
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for ScreenshotServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
            .with_server_info(Implementation::from_build_env())
            .with_instructions(
                "Terminal screenshot MCP server. Use execute_and_screenshot to run \
                 commands and capture PNG screenshots of the terminal output, including \
                 the user's real shell prompt before each command, colors, and full ANSI \
                 rendering; the final prompt is removed automatically. Set its \
                 `cwd` when directory context belongs in the screenshot; if the path is \
                 incidental, use a short staging directory or hide the prompt. Never \
                 print or synthesize a prompt in the command. Use render_ansi to render \
                 previously captured terminal output from a file. Both take an optional \
                 `redactions` list (regex patterns and/or cell ranges) to mask sensitive \
                 data as the image is rendered. Use redact_screenshot \
                 to selectively redact an existing screenshot by regex pattern or cell \
                 coordinates (run execute_and_screenshot first without redaction, inspect \
                 the plain text, then redact what is sensitive). Use compose_screenshots \
                 to place two or more screenshots side by side or stacked into one image.",
            )
    }
}

/// Start the MCP server on stdio.
pub async fn run_mcp_server(config: Config, renderer: Renderer) -> anyhow::Result<()> {
    tracing::info!("Starting termshot MCP server (stdio transport)");
    let server = ScreenshotServer::new(config, renderer);
    let service = server.serve(stdio()).await?;
    service.waiting().await?;
    Ok(())
}

/// Resolve the request's mutually exclusive singular/plural command forms.
fn request_commands(
    command: Option<String>,
    commands: Option<Vec<String>>,
) -> Result<Vec<String>, McpError> {
    let resolved = match (command, commands) {
        (Some(_), Some(commands)) => commands,
        (Some(command), None) => vec![command],
        (None, Some(commands)) => commands,
        (None, None) => {
            return Err(McpError::invalid_params(
                "Missing command: pass `command` or a non-empty `commands` list.".to_string(),
                None,
            ));
        }
    };
    if resolved.is_empty() || resolved.iter().any(|command| command.trim().is_empty()) {
        return Err(McpError::invalid_params(
            "`command` and every entry in `commands` must contain a shell command.".to_string(),
            None,
        ));
    }
    Ok(resolved)
}

/// Turn a mutually exclusive `head_lines` / `tail_lines` pair into a line
/// selection, rejecting a request that sets both.
fn line_selection(head: Option<usize>, tail: Option<usize>) -> Result<LineSelection, McpError> {
    LineSelection::from_head_tail(head, tail)
        .map_err(|e| McpError::invalid_params(e.to_string(), None))
}

/// Error for a request that supplies `redactions` and sets `redact: false`.
///
/// The two say opposite things - mask these cells, and do not redact - so the
/// request is refused rather than answered with one of them. This is the MCP
/// spelling of the CLI's `--redaction` / `--no-redact` conflict, which clap
/// refuses the same way.
const MANUAL_REDACTION_CONFLICT_MSG: &str = "`redactions` conflicts with `redact: false`: the request asks for manual masking \
     and for redaction to be off at once. Drop `redact` (manual redactions apply on \
     their own) or drop `redactions`. This mirrors the CLI, where `--redaction` \
     conflicts with `--no-redact`.";

/// Compile a tool's caller-supplied `redactions` into the shared applicable
/// set, or `None` when none were given.
///
/// Shared by `execute_and_screenshot` and `render_ansi`, and built from exactly
/// the specifications the CLI's `--redaction` option and `redact_screenshot`
/// take, through the same [`ManualRedactions`] compiler - so a pattern or cell
/// range behaves identically from any entry point, down to the audit names.
/// Compiling here means an invalid regex, color, or empty range is refused
/// before a command is run or an image is written.
fn manual_redactions(
    specs: Option<&[ManualRedactionSpec]>,
    redact: Option<bool>,
    show_labels: bool,
) -> Result<Option<ManualRedactions>, McpError> {
    let specs = match specs {
        Some(specs) if !specs.is_empty() => specs,
        _ => return Ok(None),
    };
    if redact == Some(false) {
        return Err(McpError::invalid_params(
            MANUAL_REDACTION_CONFLICT_MSG.to_string(),
            None,
        ));
    }
    ManualRedactions::new(specs, show_labels)
        .map(Some)
        .map_err(|e| McpError::invalid_params(e.to_string(), None))
}

/// Message returned alongside a screenshot that lost output, so the caller
/// knows the image is not the whole story. `effective_lines` is the capacity
/// that actually applied, which a wide terminal can drive below the configured
/// one.
fn truncation_notice(effective_lines: usize) -> String {
    format!(
        "Warning: output exceeded the {}-line scrollback, so the oldest lines were dropped \
         before rendering. Raise `max_scrollback_lines` in the server config to keep more \
         (a wide terminal caps it), or pass head_lines/tail_lines to select one end.",
        effective_lines
    )
}

/// Minimum and maximum allowed terminal dimensions. Zero panics the vt100
/// parser and unbounded values can drive enormous image allocations.
const MIN_DIM: u16 = 1;
const MAX_DIM: u16 = 500;

/// Validate terminal cols/rows before they reach the renderer/vt100 parser.
fn validate_dimensions(cols: u16, rows: u16) -> Result<(), McpError> {
    for (label, value) in [("cols", cols), ("rows", rows)] {
        if !(MIN_DIM..=MAX_DIM).contains(&value) {
            return Err(McpError::invalid_params(
                format!(
                    "{} must be between {} and {} (got {})",
                    label, MIN_DIM, MAX_DIM, value
                ),
                None,
            ));
        }
    }
    Ok(())
}

fn chrome_options_from_params(
    config: &Config,
    chrome: Option<String>,
    title: Option<String>,
    timestamp: Option<bool>,
    rounded: Option<bool>,
    inferred_title: Option<&str>,
) -> Option<ChromeOptions> {
    let has_overrides =
        chrome.is_some() || title.is_some() || timestamp.is_some() || rounded.is_some();
    let mut options = ChromeOptions::from_config(&config.chrome);
    if let Some(preset) = chrome {
        options.enabled = preset != "none";
        options.preset = preset;
    }
    if let Some(title) = title {
        options.title = Some(title);
    } else if options.enabled {
        options.title = inferred_title.map(str::to_owned);
    }
    if let Some(timestamp) = timestamp {
        options.timestamp = timestamp;
    }
    if let Some(rounded) = rounded {
        options.rounded = rounded;
    }

    if !(has_overrides || options.enabled && inferred_title.is_some()) {
        return None;
    }
    Some(options)
}