sysknife-cli 0.2.14

Approval-gated AI system administration CLI and MCP server
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
//! MCP server entry point for `sysknife mcp-server`.
//!
//! Exposes five tools plus one discovery resource:
//!
//! - `sysknife_plan`         — turn a natural-language intent into a risk-labelled plan.
//! - `sysknife_execute`      — execute a plan returned by `sysknife_plan`.
//! - `sysknife_history`      — list past audit-log entries (read-only).
//! - `sysknife_doctor`       — daemon connectivity + config diagnostics (read-only).
//! - `sysknife_audit_verify` — verify the audit-log hash chain (read-only).
//!
//! Typical agentic loop:
//!
//! 1. Call `sysknife_plan { intent }` — show the plan to the user, explain risk.
//! 2. **STOP** — wait for explicit user approval before doing anything else.
//! 3. The user runs `sysknife approve <transaction-id>` for each accepted step.
//! 4. Call `sysknife_execute` with the exact steps and one-time receipts.
//!
//! The three read-only tools (`sysknife_history`, `sysknife_doctor`,
//! `sysknife_audit_verify`) are safe to call without going through the
//! plan/approve/execute loop — they only inspect state.
//!
//! The server uses stdio transport so any MCP client (Claude Desktop,
//! Cursor, …) can launch it as a local subprocess.
//!
//! Example `claude_desktop_config.json` entry:
//!
//! ```json
//! {
//!   "mcpServers": {
//!     "sysknife": { "command": "sysknife", "args": ["mcp-server"] }
//!   }
//! }
//! ```

use std::path::PathBuf;

use rmcp::{
    handler::server::wrapper::{Json, Parameters},
    model::{
        Implementation, ListResourceTemplatesResult, ListResourcesResult, PaginatedRequestParams,
        ReadResourceRequestParams, ReadResourceResult, Resource, ResourceContents,
        ServerCapabilities, ServerInfo,
    },
    schemars, tool, tool_handler, tool_router,
    transport::stdio,
    ErrorData, ServerHandler, ServiceExt,
};
use serde::{Deserialize, Serialize};
use sysknife_types::{ApprovalReceipt, RiskLevel, TransactionId};

use sysknife_brain::config::BrainConfig;
use sysknife_brain::planner::LlmPlanner;
use sysknife_brain::state_client::StateClient as _;

use crate::client::{DaemonClient, DescribeInfo};
use crate::error::CliError;
use crate::runner::{resolve_socket_target, verify_postgres, verify_sqlite, Verifier};

// ---------------------------------------------------------------------------
// sysknife_plan — input / output types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct PlanInput {
    /// Natural-language intent, e.g. "show disk usage" or "add vim to my system".
    pub intent: String,
}

/// One action step in the proposed plan.
#[derive(Debug, Default, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(default)]
pub struct PlanStepOutput {
    /// Canonical action name from the SysKnife catalogue.
    pub action_name: String,
    /// Human-readable description of what this step does.
    pub summary: String,
    /// Risk level: `"low"`, `"medium"`, or `"high"`.
    pub risk_level: String,
    /// Action-specific parameters.
    pub params: serde_json::Value,
    /// Formatted shell command that will run on the VM, e.g. `"timedatectl"`.
    pub command: String,
    /// Daemon-issued identity of the immutable persisted preview.
    pub transaction_id: String,
    /// Preview-time warnings for this step (e.g. reboot-required, platform
    /// caveats). Surfaced so the calling agent can relay them to the operator
    /// before approval; empty when the preview produced none.
    pub warnings: Vec<String>,
}

/// The full plan returned by `sysknife_plan`.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct PlanOutput {
    /// The original natural-language intent.
    pub intent: String,
    /// One-line summary of the plan.
    pub summary: String,
    /// Longer explanation of why this plan was chosen.
    pub explanation: String,
    /// Ordered list of steps to execute.
    pub steps: Vec<PlanStepOutput>,
}

// ---------------------------------------------------------------------------
// sysknife_execute — input / output types
// ---------------------------------------------------------------------------

/// A single step to execute, taken verbatim from `sysknife_plan` output.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct StepToExecute {
    /// Transaction ID returned by `sysknife_plan` for this exact step.
    pub transaction_id: String,
    /// Canonical action name from the SysKnife catalogue, e.g. `"GetDiskUsage"`.
    pub action_name: String,
    /// Action-specific parameters (pass through from the plan unchanged).
    pub params: serde_json::Value,
    /// One-time receipt from an explicit `sysknife approve <transaction-id>`.
    pub approval_receipt: String,
}

/// Input to `sysknife_execute`.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct ExecuteInput {
    /// Steps to execute — take the `steps` array from `sysknife_plan` output.
    pub steps: Vec<StepToExecute>,
}

/// Execution result for a single step.
#[derive(Debug, Serialize, schemars::JsonSchema)]
pub struct StepResult {
    /// Action that was executed.
    pub action_name: String,
    /// Final status: `"succeeded"`, `"failed"`, `"needs_reboot"`, etc.
    pub status: String,
    /// Human-readable summary from the daemon.
    pub summary: String,
    /// Progress lines collected during execution (ANSI stripped).
    pub output: Vec<String>,
    /// Warnings emitted by the daemon for this step.
    pub warnings: Vec<String>,
    /// Whether this step requires a reboot to take effect.
    pub needs_reboot: bool,
    /// Daemon transaction ID for audit purposes.
    pub transaction_id: String,
}

/// Output of `sysknife_execute`.
#[derive(Debug, Serialize, schemars::JsonSchema)]
pub struct ExecuteOutput {
    /// Results for each executed step, in order.
    pub steps: Vec<StepResult>,
    /// True if any step requires a reboot to take effect.
    pub needs_reboot: bool,
}

// ---------------------------------------------------------------------------
// sysknife_history — input / output types
// ---------------------------------------------------------------------------

/// Input to `sysknife_history`. All fields optional; mirrors the CLI flags
/// on `sysknife history`.
#[derive(Debug, Deserialize, schemars::JsonSchema)]
pub struct HistoryInput {
    /// Filter by job status (e.g. `"succeeded"`, `"failed"`, `"canceled"`).
    pub status: Option<String>,
    /// Filter by action name (e.g. `"InstallPackages"`).
    pub action: Option<String>,
    /// Show only entries after this UTC RFC 3339 timestamp
    /// (e.g. `"2026-01-15T10:30:00Z"`).
    pub since: Option<String>,
    /// Maximum number of entries to return. Defaults to 20.
    pub limit: Option<u32>,
}

/// One row in the history listing.
///
/// Populated from the daemon's structured `query_history` IPC, so
/// `created_at` and `risk_level` carry real values. They stay `Option` only
/// for wire tolerance (a future or partial row may omit them).
#[derive(Debug, Default, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
#[serde(default)]
pub struct HistoryEntry {
    /// Daemon transaction ID.
    pub transaction_id: String,
    /// Canonical action name from the SysKnife catalogue.
    pub action: String,
    /// Final job status (`"succeeded"`, `"failed"`, etc.).
    pub status: String,
    /// Human-readable summary from the daemon.
    pub summary: String,
    /// ISO-8601 timestamp when the transaction was created.
    pub created_at: Option<String>,
    /// Risk level the daemon assigned (`"low"` | `"medium"` | `"high"`).
    pub risk_level: Option<String>,
}

/// Output wrapper for `sysknife_history`.
///
/// MCP requires the tool's output schema to have an `object` root type;
/// returning a bare `Vec<HistoryEntry>` produces an `array` root and
/// makes the rmcp `ToolRouter` panic at construction time.  Wrapping
/// the vec in a single-field struct gives the schema an object root
/// with one named property, satisfying the spec without any extra
/// runtime cost.
#[derive(Debug, Default, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
pub struct HistoryOutput {
    pub entries: Vec<HistoryEntry>,
}

// ---------------------------------------------------------------------------
// sysknife_doctor — output types
// ---------------------------------------------------------------------------

/// Output of `sysknife_doctor`. Snapshot of daemon connectivity, brain
/// provider, and audit-chain health at the moment the tool was called.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
pub struct DoctorReport {
    /// Resolved daemon socket target, e.g. `"Unix(\"/run/sysknife/daemon.sock\")"`.
    pub daemon_socket: String,
    /// `true` iff the daemon answered `query_state` within the socket timeout.
    pub daemon_reachable: bool,
    /// Configured brain provider (`"anthropic"`, `"openai"`, `"ollama"`, …).
    pub brain_provider: String,
    /// Configured brain model identifier.
    pub brain_model: String,
    /// Detected Linux distribution, e.g. `"Ubuntu 24.04"` or `"Fedora 41"`.
    /// Set to `"unknown (<reason>)"` when `/etc/os-release` cannot be read.
    pub distro: String,
    /// Resolved audit DB path. For Postgres deployments, the literal string
    /// `"postgres"` instead of a filesystem path.
    pub audit_db_path: String,
    /// `"intact"` | `"broken"` | `"unknown"`. `"unknown"` covers all
    /// `CannotVerify` cases (missing key file, unreachable DB, etc.).
    pub audit_chain_status: String,
    /// Non-fatal warnings collected during the diagnostic run. Anything
    /// that could not be checked (state, brain config, audit chain, …)
    /// adds one entry here so the operator sees what was skipped and why.
    pub warnings: Vec<String>,
}

// ---------------------------------------------------------------------------
// sysknife_audit_verify — output types
// ---------------------------------------------------------------------------

/// Output of `sysknife_audit_verify`. Mirrors the JSON shape produced by
/// the CLI's `sysknife audit verify --json` command.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema, PartialEq, Eq)]
pub struct AuditVerifyReport {
    /// One of `"intact"`, `"broken"`, `"cannot_verify"`.
    pub status: String,
    /// Number of audit rows the verifier successfully checked. `0` for
    /// `cannot_verify` outcomes that fail before the first row is read.
    pub rows_checked: u64,
    /// Sequence number of the first row that broke the chain. Only set
    /// when `status == "broken"`.
    pub first_broken_seq: Option<u64>,
    /// Transaction ID of the first broken row. Only set when
    /// `status == "broken"`.
    pub first_broken_transaction_id: Option<String>,
    /// What verification expected for the first broken row (the literal
    /// `"valid ed25519 signature"`).
    pub expected: Option<String>,
    /// The hex Ed25519 signature actually stored for the first broken row.
    pub actual: Option<String>,
    /// Human-readable explanation. Only set when `status == "cannot_verify"`.
    pub reason: Option<String>,
    /// Number of approval events (grant / consume / revoke) checked in the
    /// second chain.
    pub events_checked: u64,
    /// Result of the approval-event chain walk: `"intact"`, `"broken"`, or
    /// `"cannot_verify"`. Reported separately from `status` so a clean
    /// authorisation trail can never paper over a tampered approval trail.
    pub approval_events_status: String,
    /// `"consistent"` or `"missing_event"`: whether every event tip committed
    /// by a transaction row is still present in the event chain.
    pub binding_status: String,
    /// Backend label: a filesystem path for SQLite, the literal `"postgres"`
    /// for Postgres deployments.
    pub backend: String,
}

// ---------------------------------------------------------------------------
// Server
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct SysknifeMcpServer;

const SYSKNIFE_DISCOVERY_URI: &str = "sysknife://about";
const SYSKNIFE_DISCOVERY_NAME: &str = "about";
const SYSKNIFE_DISCOVERY_TITLE: &str = "SysKnife MCP server";
const SYSKNIFE_DISCOVERY_DESCRIPTION: &str = "Discovery resource for Codex and other MCP clients.";
const SYSKNIFE_DISCOVERY_BODY: &str = "SysKnife exposes a small tool set for planning and executing Linux system administration tasks.\n\nUse `sysknife_plan` first and present the plan to the user. The user must run `sysknife approve <transaction-id>` in a terminal for every accepted step. Call `sysknife_execute` only with the one-time receipts printed by those commands. MCP cannot issue approval receipts.\n\nAvailable read-only tools: `sysknife_history`, `sysknife_doctor`, and `sysknife_audit_verify`.";

fn sysknife_about_resource() -> Resource {
    rmcp::model::Resource::new(SYSKNIFE_DISCOVERY_URI, SYSKNIFE_DISCOVERY_NAME)
        .with_title(SYSKNIFE_DISCOVERY_TITLE)
        .with_description(SYSKNIFE_DISCOVERY_DESCRIPTION)
        .with_mime_type("text/plain")
}

#[tool_router]
impl SysknifeMcpServer {
    /// Plan a Linux system administration intent.
    ///
    /// Returns a JSON object with the proposed steps, each carrying an
    /// `action_name`, `summary`, `risk_level` ("low" | "medium" | "high"),
    /// `params`, `command` (the resolved shell command), and a daemon-issued
    /// `transaction_id`. No action is executed. The user must approve each
    /// transaction from a separate terminal before execution.
    #[tool(
        description = "Plan a Linux system administration intent. Returns typed steps with risk levels, resolved commands, and daemon transaction IDs. IMPORTANT: Present the plan, then STOP. The user must run `sysknife approve <transaction-id>` in a real terminal for each accepted step. Do not execute from chat approval alone."
    )]
    async fn sysknife_plan(
        &self,
        Parameters(PlanInput { intent }): Parameters<PlanInput>,
    ) -> Result<Json<PlanOutput>, ErrorData> {
        let value = plan_intent_inner(&intent)
            .await
            .map_err(|e| ErrorData::internal_error(e, None))?;
        let mut output: PlanOutput = serde_json::from_value(value).map_err(|e| {
            ErrorData::internal_error(format!("output deserialization error: {e}"), None)
        })?;
        let client = DaemonClient::new(resolve_socket_target());
        enrich_with_commands(&mut output, &client)
            .await
            .map_err(|e| ErrorData::internal_error(e, None))?;
        Ok(Json(output))
    }

    /// Execute a plan produced by `sysknife_plan`.
    ///
    /// Pass each exact step from `sysknife_plan` with the one-time receipt
    /// printed by `sysknife approve <transaction-id>`. MCP cannot issue these
    /// receipts itself. On failure mid-plan execution stops immediately.
    ///
    /// Returns per-step results including output lines, warnings, and
    /// whether a reboot is required.
    #[tool(
        description = "Execute exact steps produced by sysknife_plan. Every step requires a one-time receipt from an explicit `sysknife approve <transaction-id>` CLI confirmation; MCP cannot approve its own mutations."
    )]
    async fn sysknife_execute(
        &self,
        Parameters(ExecuteInput { steps }): Parameters<ExecuteInput>,
    ) -> Result<Json<ExecuteOutput>, ErrorData> {
        execute_steps_inner(steps)
            .await
            .map(Json)
            .map_err(|e| ErrorData::internal_error(e, None))
    }

    /// List past SysKnife audit-log entries.
    ///
    /// Read-only and safe to call without first calling `sysknife_plan`;
    /// it never mutates system state. Mirrors `sysknife history`.
    #[tool(
        description = "List past SysKnife audit-log entries. Read-only and safe to call without prior sysknife_plan. Filters: status (succeeded/failed/canceled/...), action (canonical action name), since (UTC RFC 3339 timestamp), limit (default 20). Returns a list of HistoryEntry rows."
    )]
    async fn sysknife_history(
        &self,
        Parameters(input): Parameters<HistoryInput>,
    ) -> Result<Json<HistoryOutput>, ErrorData> {
        history_inner(input)
            .await
            .map(|entries| Json(HistoryOutput { entries }))
            .map_err(|e| ErrorData::internal_error(e, None))
    }

    /// Daemon connectivity + configuration diagnostics.
    ///
    /// Read-only and safe to call without first calling `sysknife_plan`;
    /// it never mutates system state. Mirrors `sysknife doctor` plus an
    /// audit-chain quick-check.
    #[tool(
        description = "Diagnose SysKnife: pings the daemon, reports the configured brain provider/model, the audit DB path, and a quick audit-chain status (intact/broken/unknown). Read-only and safe to call without prior sysknife_plan."
    )]
    async fn sysknife_doctor(&self) -> Result<Json<DoctorReport>, ErrorData> {
        Ok(Json(doctor_inner().await))
    }

    /// Verify the audit-log hash chain.
    ///
    /// Read-only and safe to call without first calling `sysknife_plan`;
    /// it never mutates system state. Mirrors `sysknife audit verify`.
    #[tool(
        description = "Verify the tamper-evident Ed25519-signed hash chain over the audit log. Returns status (intact/broken/cannot_verify), rows_checked, and, on broken, the first offending row. Read-only and safe to call without prior sysknife_plan."
    )]
    async fn sysknife_audit_verify(&self) -> Result<Json<AuditVerifyReport>, ErrorData> {
        Ok(Json(audit_verify_inner().await))
    }
}

/// Identity this server reports in `initialize`.
///
/// `Implementation::from_build_env()` resolves `CARGO_PKG_*` at the crate where
/// the macro expands — which is `rmcp` — so the server introduced itself to
/// every client, and to directory listings, as "rmcp" at rmcp's version. The
/// struct is `#[non_exhaustive]`, so the fields are overwritten rather than
/// rebuilt, which also keeps any future field at its upstream default.
fn sysknife_implementation() -> Implementation {
    let mut implementation = Implementation::from_build_env();
    implementation.name = "sysknife".to_string();
    implementation.version = env!("CARGO_PKG_VERSION").to_string();
    implementation
}

#[tool_handler]
impl ServerHandler for SysknifeMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(
            ServerCapabilities::builder()
                .enable_tools()
                .enable_resources()
                .build(),
        )
        // Not `Implementation::from_build_env()`: that macro resolves
        // `CARGO_PKG_*` at the crate where it is expanded, which is `rmcp`, so
        // the server introduced itself to every client as "rmcp" at rmcp's
        // version. Directory listings and client UIs show this string.
        .with_server_info(sysknife_implementation())
        .with_instructions(
            "SysKnife provides planning and execution tools for Linux system administration.",
        )
    }

    async fn list_resources(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> Result<ListResourcesResult, ErrorData> {
        Ok(ListResourcesResult {
            resources: vec![sysknife_about_resource()],
            next_cursor: None,
            meta: None,
        })
    }

    async fn list_resource_templates(
        &self,
        _request: Option<PaginatedRequestParams>,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> Result<ListResourceTemplatesResult, ErrorData> {
        Ok(ListResourceTemplatesResult {
            resource_templates: Vec::new(),
            next_cursor: None,
            meta: None,
        })
    }

    async fn read_resource(
        &self,
        ReadResourceRequestParams { uri, .. }: ReadResourceRequestParams,
        _context: rmcp::service::RequestContext<rmcp::service::RoleServer>,
    ) -> Result<ReadResourceResult, ErrorData> {
        match uri.as_str() {
            SYSKNIFE_DISCOVERY_URI => Ok(ReadResourceResult::new(vec![ResourceContents::text(
                SYSKNIFE_DISCOVERY_BODY,
                uri,
            )])),
            _ => Err(ErrorData::resource_not_found(
                "resource_not_found",
                Some(serde_json::json!({ "uri": uri })),
            )),
        }
    }
}

// ---------------------------------------------------------------------------
// sysknife_plan helper
// ---------------------------------------------------------------------------

async fn plan_intent_inner(intent: &str) -> Result<serde_json::Value, String> {
    let config = BrainConfig::from_env().map_err(|e| format!("config error: {e}"))?;

    let state_client = DaemonClient::new(resolve_socket_target());

    // Detect the running distro and pass a hint to the planner so it picks
    // the right action family up front.  Failure is non-fatal.
    let distro = sysknife_core::distro::detect().ok();

    let mut planner = LlmPlanner::from_config(config, Box::new(state_client))
        .map_err(|e| format!("planner init error: {e}"))?;
    if let Some(ref d) = distro {
        planner = planner.with_distro(crate::runner::distro_id_to_hint(d));
    }

    // `plan_intent` may call `StateClient::curated_state()` (a blocking sync
    // Unix socket call) on the current async thread.  This is tolerable on
    // the multi-threaded runtime: the call is bounded by SOCKET_TIMEOUT (10 s)
    // and ties up one worker thread for at most that duration.  MCP sessions
    // are LLM-driven and sequential in practice, so concurrent saturation of
    // the thread pool is not a realistic concern here.
    let plan = planner
        .plan_intent(intent)
        .await
        .map_err(|e| format!("planning error: {e}"))?;

    // Mirror the CLI's distro-routing guard (`runner::run_intent`) so MCP
    // clients get a clear distro-mismatch message (e.g. "AptInstall is only
    // valid on Debian-family distros") instead of a raw daemon error
    // surfacing later out of `enrich_with_commands`/`preview`. The daemon
    // remains the enforcement backstop regardless of this check.
    check_plan_steps_distro(
        plan.steps().iter().map(|s| s.action_name()),
        distro.as_ref(),
    )?;

    serde_json::to_value(&plan).map_err(|e| format!("serialization error: {e}"))
}

/// Validate every plan step's action name against the detected distro,
/// reusing [`crate::distro_routing::check_action_distro`]. Extracted as a
/// small pure function (taking action-name strings rather than a full
/// `Plan`) so it can be unit-tested without constructing planner internals.
fn check_plan_steps_distro<'a>(
    action_names: impl Iterator<Item = &'a str>,
    distro: Option<&sysknife_core::distro::DistroId>,
) -> Result<(), String> {
    for action_name in action_names {
        crate::distro_routing::check_action_distro(action_name, distro)?;
    }
    Ok(())
}

/// Resolve and persist every step against the daemon. Planning fails closed if
/// any step cannot be described or previewed; a synthetic transaction ID must
/// never be presented as executable.
async fn enrich_with_commands(
    output: &mut PlanOutput,
    client: &DaemonClient,
) -> Result<(), String> {
    for step in &mut output.steps {
        let DescribeInfo { command, .. } =
            client
                .describe(&step.action_name, &step.params)
                .await
                .map_err(|e| format!("describe failed for {}: {e}", step.action_name))?;
        step.command = command;

        let prepared = client
            .preview(&step.action_name, &step.params)
            .await
            .map_err(|e| format!("preview failed for {}: {e}", step.action_name))?;
        // The MCP wire structs keep plain strings: their JSON Schema is what
        // the agent sees, and a bare string is the honest description of an
        // opaque identifier. The newtypes guard the internal call sites, so the
        // conversion happens once, here at the boundary.
        step.transaction_id = prepared.transaction_id.into_inner();
        step.risk_level = match prepared.preview.risk_level {
            RiskLevel::Low => "low",
            RiskLevel::Medium => "medium",
            RiskLevel::High => "high",
        }
        .to_string();
        // Carry the preview's warnings through to the plan output rather than
        // discarding them — the agent needs them to inform the operator.
        step.warnings = prepared.preview.warnings.clone();
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// sysknife_execute helper
// ---------------------------------------------------------------------------

async fn execute_steps_inner(steps: Vec<StepToExecute>) -> Result<ExecuteOutput, String> {
    let client = DaemonClient::new(resolve_socket_target());

    let mut results: Vec<StepResult> = Vec::new();
    let mut plan_needs_reboot = false;

    for step in steps {
        // Execute and collect progress lines.
        let mut output_lines: Vec<String> = Vec::new();
        let result = client
            .execute(
                &TransactionId::new(step.transaction_id.clone()),
                &step.action_name,
                &step.params,
                &ApprovalReceipt::new(step.approval_receipt.clone()),
                |line| output_lines.push(line.to_owned()),
            )
            .await
            .map_err(|e| format!("execute error for {}: {e}", step.action_name))?;

        let needs_reboot = result.needs_reboot;
        if needs_reboot {
            plan_needs_reboot = true;
        }

        // `JobState` is a plain snake_case string enum, so this cannot fail
        // today. Fail loudly rather than degrading to "unknown": silently
        // replacing a real status with a placeholder would leave the calling
        // agent unable to distinguish "the daemon said unknown" from "we lost
        // the status", which is exactly the kind of quiet drift a future
        // non-string `JobState` representation would introduce.
        let status = serde_json::to_value(result.status)
            .ok()
            .and_then(|v| v.as_str().map(String::from))
            .expect("JobState always serializes to a JSON string");

        let succeeded = matches!(result.status, sysknife_types::JobState::Succeeded);

        results.push(StepResult {
            action_name: step.action_name,
            status,
            summary: result.summary,
            output: truncate_output(output_lines),
            warnings: result.warnings,
            needs_reboot,
            transaction_id: result.transaction_id,
        });

        // Halt on first failure — do not continue executing subsequent steps.
        if !succeeded {
            break;
        }
    }

    Ok(ExecuteOutput {
        steps: results,
        needs_reboot: plan_needs_reboot,
    })
}

// ---------------------------------------------------------------------------
// Pure helpers (also tested below)
// ---------------------------------------------------------------------------

/// Maximum number of output lines returned per step in the MCP response.
///
/// Large-output actions (e.g. `GetSystemState`, `CollectDiagnostics`) can
/// produce tens of thousands of lines which exceed MCP context windows.
/// Lines beyond this limit are dropped and a single summary line is appended.
const OUTPUT_LINE_LIMIT: usize = 500;

/// Truncate `lines` to at most `OUTPUT_LINE_LIMIT` entries.
///
/// If truncation occurs, a marker line is appended so the caller knows
/// output was cut.
fn truncate_output(mut lines: Vec<String>) -> Vec<String> {
    if lines.len() > OUTPUT_LINE_LIMIT {
        let dropped = lines.len() - OUTPUT_LINE_LIMIT;
        lines.truncate(OUTPUT_LINE_LIMIT);
        lines.push(format!("[truncated: {dropped} more lines omitted]"));
    }
    lines
}

// ---------------------------------------------------------------------------
// sysknife_history helpers
// ---------------------------------------------------------------------------

/// Default history limit, matching the CLI's `HistoryArgs::limit` default.
const HISTORY_DEFAULT_LIMIT: u32 = 20;

async fn history_inner(input: HistoryInput) -> Result<Vec<HistoryEntry>, String> {
    let HistoryInput {
        status,
        action,
        since,
        limit,
    } = input;

    let since_hours = match since.as_deref() {
        None => None,
        Some(s) => match crate::runner::since_to_hours(s) {
            Some(h) => Some(h),
            None => {
                return Err(format!(
                    "since: {s:?} is not a valid past UTC RFC 3339 timestamp \
                     (accepted: 2026-01-15T10:30:00Z)"
                ));
            }
        },
    };

    let limit = limit.unwrap_or(HISTORY_DEFAULT_LIMIT);
    let client = DaemonClient::new(resolve_socket_target());
    let rows = tokio::task::spawn_blocking(move || {
        client.query_history(
            Some(limit),
            status.as_deref(),
            action.as_deref(),
            since_hours,
        )
    })
    .await
    .map_err(|e| format!("join: {e}"))?
    .map_err(|e| format!("daemon error: {e}"))?;

    Ok(rows.into_iter().map(history_entry_from_row).collect())
}

/// Map a daemon `JobHistoryEntry` to the MCP `HistoryEntry`, populating the
/// `created_at` and typed `risk_level` fields the old text-parsing path always
/// left `None`. Status is rendered lowercase to match the daemon's display.
fn history_entry_from_row(row: sysknife_daemon::transactions::JobHistoryEntry) -> HistoryEntry {
    let risk_level = match row.risk_level {
        RiskLevel::Low => "low",
        RiskLevel::Medium => "medium",
        RiskLevel::High => "high",
    };
    HistoryEntry {
        transaction_id: row.transaction_id,
        action: row.action_name,
        status: format!("{:?}", row.status).to_lowercase(),
        summary: row.summary,
        created_at: Some(row.created_at),
        risk_level: Some(risk_level.to_string()),
    }
}

// ---------------------------------------------------------------------------
// sysknife_doctor helpers
// ---------------------------------------------------------------------------

async fn doctor_inner() -> DoctorReport {
    let mut warnings: Vec<String> = Vec::new();

    let socket = resolve_socket_target();
    let socket_label = format!("{socket:?}");

    // Detect the running distro — non-fatal if /etc/os-release is absent.
    let distro = match sysknife_core::distro::detect() {
        Ok(d) => d.to_string(),
        Err(e) => {
            let label = format!("unknown ({})", e);
            warnings.push(format!("distro detection failed: {e}"));
            label
        }
    };

    // Daemon connectivity — `curated_state` is sync, so spawn_blocking.
    let client = DaemonClient::new(socket);
    let daemon_reachable = match tokio::task::spawn_blocking(move || client.curated_state()).await {
        Ok(Ok(_)) => true,
        Ok(Err(e)) => {
            warnings.push(format!("daemon unreachable: {e}"));
            false
        }
        Err(e) => {
            warnings.push(format!("daemon ping join error: {e}"));
            false
        }
    };

    // Brain provider/model — fall back to placeholders if config is missing
    // (e.g. operator hasn't run `sysknife-setup` yet).
    let (brain_provider, brain_model) = match BrainConfig::from_env() {
        Ok(cfg) => (
            cfg.provider_name().to_string(),
            cfg.model_name().to_string(),
        ),
        Err(e) => {
            warnings.push(format!("brain config unreadable: {e}"));
            ("unknown".to_string(), "unknown".to_string())
        }
    };

    // Audit DB path / chain status — same precedence rules as `run_audit_verify`.
    let lacs_config = sysknife_core::config::LacsConfig::load();
    let audit_db_path = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => "postgres".to_string(),
        _ => sysknife_core::default_database_path().display().to_string(),
    };

    let audit_chain_status = match audit_chain_quick_check(&lacs_config, &mut warnings).await {
        VerifyOutcomeKind::Intact => "intact",
        VerifyOutcomeKind::Broken => "broken",
        VerifyOutcomeKind::Unknown => "unknown",
    }
    .to_string();

    DoctorReport {
        daemon_socket: socket_label,
        daemon_reachable,
        brain_provider,
        brain_model,
        distro,
        audit_db_path,
        audit_chain_status,
        warnings,
    }
}

/// Compact summary of `VerifyOutcome` for doctor's `audit_chain_status` field.
enum VerifyOutcomeKind {
    Intact,
    Broken,
    Unknown,
}

/// Run a non-fatal audit chain check. Anything that prevents verification
/// becomes `Unknown` plus a warning entry — the doctor must never hard-fail
/// just because the audit key file is missing.
async fn audit_chain_quick_check(
    lacs_config: &sysknife_core::config::LacsConfig,
    warnings: &mut Vec<String>,
) -> VerifyOutcomeKind {
    use sysknife_daemon::audit_chain::{AuditKey, BindingOutcome, VerifyOutcome};

    let db_path = sysknife_core::default_database_path();
    let key_path = std::env::var("SYSKNIFE_AUDIT_KEY_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            db_path
                .parent()
                .unwrap_or_else(|| std::path::Path::new("."))
                .join("audit-key")
        });

    if !key_path.exists() {
        warnings.push(format!("audit key not found at {}", key_path.display()));
        return VerifyOutcomeKind::Unknown;
    }

    let key = match AuditKey::load_or_generate(&key_path) {
        Ok(k) => k,
        Err(e) => {
            warnings.push(format!("audit key load failed: {e}"));
            return VerifyOutcomeKind::Unknown;
        }
    };

    let verifier = Verifier::Private(Box::new(key));
    let outcome = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => {
            verify_postgres(s, &verifier).await
        }
        _ => verify_sqlite(&db_path, &verifier).await,
    };

    // The doctor summary reports the worst of the three checks. Reporting only
    // the transaction chain would call a deployment healthy while its approval
    // trail was broken.
    for (label, sub) in [
        ("audit chain", &outcome.chain),
        ("approval-event chain", &outcome.events),
    ] {
        if let VerifyOutcome::CannotVerify { reason } = sub {
            warnings.push(format!("{label} cannot be verified: {reason}"));
        }
    }
    if let BindingOutcome::MissingEvent {
        transaction_seq, ..
    } = &outcome.binding
    {
        warnings.push(format!(
            "transaction seq={transaction_seq} commits to an approval event that no longer exists"
        ));
    }
    match outcome.exit_code() {
        0 => VerifyOutcomeKind::Intact,
        1 => VerifyOutcomeKind::Broken,
        _ => VerifyOutcomeKind::Unknown,
    }
}

// ---------------------------------------------------------------------------
// sysknife_audit_verify helpers
// ---------------------------------------------------------------------------

async fn audit_verify_inner() -> AuditVerifyReport {
    use sysknife_daemon::audit_chain::AuditKey;

    let lacs_config = sysknife_core::config::LacsConfig::load();
    let backend_label = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => "postgres".to_string(),
        _ => sysknife_core::default_database_path().display().to_string(),
    };

    let db_path = sysknife_core::default_database_path();
    let key_path = std::env::var("SYSKNIFE_AUDIT_KEY_PATH")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            db_path
                .parent()
                .unwrap_or_else(|| std::path::Path::new("."))
                .join("audit-key")
        });

    if !key_path.exists() {
        return cannot_verify_report(
            backend_label,
            format!(
                "audit key not found at {}; the daemon generates this on first run, \
                 or set $SYSKNIFE_AUDIT_KEY_PATH",
                key_path.display()
            ),
        );
    }

    let key = match AuditKey::load_or_generate(&key_path) {
        Ok(k) => k,
        Err(e) => {
            return cannot_verify_report(backend_label, format!("audit key load failed: {e}"));
        }
    };

    let verifier = Verifier::Private(Box::new(key));
    let outcome = match lacs_config.storage.as_ref() {
        Some(s) if s.backend.eq_ignore_ascii_case("postgres") => {
            verify_postgres(s, &verifier).await
        }
        _ => verify_sqlite(&db_path, &verifier).await,
    };

    outcome_to_report(outcome, backend_label)
}

/// Short label for one chain walk.
fn outcome_label(outcome: &sysknife_daemon::audit_chain::VerifyOutcome) -> &'static str {
    use sysknife_daemon::audit_chain::VerifyOutcome;
    match outcome {
        VerifyOutcome::Intact { .. } => "intact",
        VerifyOutcome::Broken { .. } => "broken",
        VerifyOutcome::CannotVerify { .. } => "cannot_verify",
    }
}

fn outcome_to_report(
    verification: sysknife_daemon::audit_chain::AuditVerification,
    backend: String,
) -> AuditVerifyReport {
    use sysknife_daemon::audit_chain::{BindingOutcome, VerifyOutcome};

    let events_checked = match &verification.events {
        VerifyOutcome::Intact { rows_checked } | VerifyOutcome::Broken { rows_checked, .. } => {
            *rows_checked
        }
        VerifyOutcome::CannotVerify { .. } => 0,
    };
    let approval_events_status = outcome_label(&verification.events).to_string();
    let binding_status = match &verification.binding {
        BindingOutcome::Consistent { .. } => "consistent",
        BindingOutcome::MissingEvent { .. } => "missing_event",
    }
    .to_string();

    // The detail fields describe the first *break*, wherever it was found. A
    // broken transaction chain is reported ahead of a broken event chain
    // because it is the one checkpoints anchor.
    let overall = verification.exit_code();
    let mut report = match verification.chain {
        VerifyOutcome::Intact { rows_checked } => AuditVerifyReport {
            status: "intact".to_string(),
            rows_checked,
            first_broken_seq: None,
            first_broken_transaction_id: None,
            expected: None,
            actual: None,
            reason: None,
            backend,
            events_checked,
            approval_events_status,
            binding_status,
        },
        VerifyOutcome::Broken {
            rows_checked,
            first_broken_seq,
            first_broken_transaction_id,
            expected,
            actual,
        } => AuditVerifyReport {
            status: "broken".to_string(),
            rows_checked,
            first_broken_seq: Some(first_broken_seq),
            first_broken_transaction_id: Some(first_broken_transaction_id),
            expected: Some(expected),
            actual: Some(actual),
            reason: None,
            backend,
            events_checked,
            approval_events_status,
            binding_status,
        },
        VerifyOutcome::CannotVerify { reason } => {
            let mut r = cannot_verify_report(backend, reason);
            r.events_checked = events_checked;
            r.approval_events_status = approval_events_status;
            r.binding_status = binding_status;
            r
        }
    };

    // `status` is the headline an MCP client is most likely to read alone, so
    // it must reflect the worst of the three checks, not just the first.
    if report.status == "intact" {
        report.status = match overall {
            0 => "intact",
            1 => "broken",
            _ => "cannot_verify",
        }
        .to_string();
    }
    report
}

fn cannot_verify_report(backend: String, reason: String) -> AuditVerifyReport {
    AuditVerifyReport {
        status: "cannot_verify".to_string(),
        rows_checked: 0,
        first_broken_seq: None,
        first_broken_transaction_id: None,
        expected: None,
        actual: None,
        reason: Some(reason),
        backend,
        events_checked: 0,
        approval_events_status: "cannot_verify".to_string(),
        binding_status: "consistent".to_string(),
    }
}

// ---------------------------------------------------------------------------
// Entry point
// ---------------------------------------------------------------------------

pub async fn run_mcp_server() -> Result<(), CliError> {
    let service = SysknifeMcpServer
        .serve(stdio())
        .await
        .map_err(|e| CliError::ExecutionFailed(format!("MCP server error: {e}")))?;

    service
        .waiting()
        .await
        .map_err(|e| CliError::ExecutionFailed(format!("MCP server wait error: {e}")))?;

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -----------------------------------------------------------------------
    // check_plan_steps_distro — MCP planning-path distro guard
    // -----------------------------------------------------------------------

    #[test]
    fn check_plan_steps_distro_rejects_mismatched_action() {
        let distro = sysknife_core::distro::DistroId::Fedora { version: 41 };
        let result = check_plan_steps_distro(["AptInstall"].into_iter(), Some(&distro));
        assert!(
            result.is_err(),
            "AptInstall on Fedora must be rejected by the MCP planning path too"
        );
        assert!(result.unwrap_err().contains("Debian-family"));
    }

    #[test]
    fn check_plan_steps_distro_allows_generic_action() {
        let distro = sysknife_core::distro::DistroId::Fedora { version: 41 };
        let result = check_plan_steps_distro(["GetSystemState"].into_iter(), Some(&distro));
        assert!(result.is_ok());
    }

    #[test]
    fn check_plan_steps_distro_allows_all_when_distro_unknown() {
        // Detection failure (None) must never block planning -- the daemon
        // is the enforcement backstop in that case.
        let result = check_plan_steps_distro(["AptInstall", "RebaseSystem"].into_iter(), None);
        assert!(result.is_ok());
    }

    #[test]
    fn check_plan_steps_distro_stops_at_first_mismatched_step() {
        let distro = sysknife_core::distro::DistroId::Ubuntu {
            major: 24,
            minor: 4,
        };
        let result = check_plan_steps_distro(
            ["GetSystemState", "RebaseSystem", "AptInstall"].into_iter(),
            Some(&distro),
        );
        assert!(result.is_err(), "RebaseSystem on Ubuntu must be rejected");
        assert!(result.unwrap_err().contains("Fedora-family"));
    }

    #[tokio::test]
    async fn enrich_with_commands_fails_closed_when_daemon_unreachable() {
        // Fail-closed contract: if the daemon cannot describe/preview a step,
        // planning must error out — it must never hand back a step carrying a
        // synthetic or empty transaction_id that a client could then try to
        // execute. This guards the MCP approval interlock.
        let mut output = PlanOutput {
            intent: "set the timezone".to_string(),
            summary: "plan".to_string(),
            explanation: String::new(),
            steps: vec![PlanStepOutput {
                action_name: "SetTimezone".to_string(),
                params: serde_json::json!({ "timezone": "UTC" }),
                ..Default::default()
            }],
        };
        // A socket path that cannot exist → describe()/preview() fail fast.
        let client = DaemonClient::new(std::path::PathBuf::from(
            "/nonexistent/sysknife-unreachable.sock",
        ));

        let result = enrich_with_commands(&mut output, &client).await;
        assert!(
            result.is_err(),
            "enrich must fail closed when the daemon is unreachable"
        );
        assert!(
            output.steps[0].transaction_id.is_empty(),
            "no synthetic transaction_id may be presented for an un-previewed step"
        );
    }

    // -----------------------------------------------------------------------
    // T11 — tool registration round-trip via the rmcp ToolRouter
    //
    // The `#[tool_router(server_handler)]` macro generates a
    // `tool_router()` method on `SysknifeMcpServer`.  Asking it for
    // `list_all()` returns the exact tool list MCP clients see during
    // `tools/list`, so this is the boundary contract: every tool name
    // and description that ships in production goes through this list.
    // Prior coverage tested only inner helpers; a regression that
    // forgot to register a tool, swapped its name, or broke its
    // description string would have shipped silently.
    // -----------------------------------------------------------------------

    #[test]
    fn rmcp_tool_router_registers_every_sysknife_tool() {
        let router = SysknifeMcpServer::tool_router();
        let tools = router.list_all();

        let names: std::collections::HashSet<String> =
            tools.iter().map(|t| t.name.to_string()).collect();
        for expected in [
            "sysknife_plan",
            "sysknife_execute",
            "sysknife_history",
            "sysknife_doctor",
            "sysknife_audit_verify",
        ] {
            assert!(
                names.contains(expected),
                "MCP tool registry missing {expected}: registered = {names:?}"
            );
        }

        // Every registered tool must carry a non-empty description so
        // clients (and the model) can pick the right one. Empty
        // descriptions silently degrade tool selection.
        for t in &tools {
            assert!(
                t.description.as_ref().is_some_and(|d| !d.is_empty()),
                "tool {} has empty description",
                t.name
            );
        }
    }

    #[test]
    fn rmcp_sysknife_plan_description_warns_to_stop_after_planning() {
        // The plan tool's description carries an advisory instruction telling
        // the calling agent to STOP after planning. This is prompt
        // engineering, not enforcement, and this test guards the wording of
        // an operator-facing hint — NOT the security boundary.
        //
        // The actual interlock is structural and lives elsewhere:
        // `PlanOutput`/`PlanStepOutput` carry no `approval_receipt` field, so
        // no code path lets `sysknife_plan` hand back something
        // `sysknife_execute` can consume; receipts come only from a separate
        // `sysknife approve <transaction-id>` run, and the daemon
        // independently rejects forged or stale ones (see
        // `mcp_tools_integrate_with_a_daemon_over_the_socket`). Deleting this
        // clause would degrade the hint, not open a bypass — do not treat it
        // as the thing keeping a human in the loop.
        let router = SysknifeMcpServer::tool_router();
        let tools = router.list_all();
        let plan = tools
            .iter()
            .find(|t| t.name == "sysknife_plan")
            .expect("sysknife_plan must be registered");
        let desc = plan
            .description
            .as_ref()
            .expect("plan tool has a description");
        assert!(
            desc.to_lowercase().contains("stop"),
            "sysknife_plan description must tell the agent to STOP after planning; got: {desc}"
        );
    }

    #[test]
    fn discovery_resource_is_present_and_readable() {
        let resource = sysknife_about_resource();
        assert_eq!(resource.uri, SYSKNIFE_DISCOVERY_URI);
        assert_eq!(resource.name, SYSKNIFE_DISCOVERY_NAME);
        assert_eq!(resource.title.as_deref(), Some(SYSKNIFE_DISCOVERY_TITLE));
        assert_eq!(
            resource.description.as_deref(),
            Some(SYSKNIFE_DISCOVERY_DESCRIPTION)
        );
        assert_eq!(resource.mime_type.as_deref(), Some("text/plain"));
    }

    #[test]
    fn the_server_introduces_itself_as_sysknife() {
        // `Implementation::from_build_env()` expands inside the rmcp crate, so
        // it reported name "rmcp" and rmcp's version — the string clients and
        // registry listings display for this server.
        let info = SysknifeMcpServer.get_info();
        assert_eq!(info.server_info.name, "sysknife");
        assert_eq!(info.server_info.version, env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn get_info_exposes_resources_capability_for_codex() {
        let info = SysknifeMcpServer.get_info();
        assert!(
            info.capabilities.resources.is_some(),
            "Codex-compatible MCP servers should advertise resources"
        );
        assert!(
            info.capabilities.tools.is_some(),
            "SysKnife must continue advertising tools"
        );
    }

    #[test]
    fn execute_input_without_approval_receipt_is_rejected() {
        let input = serde_json::json!({
            "steps": [{
                "transaction_id": "tx-1",
                "action_name": "AptInstall",
                "params": {"package": "vim"}
            }]
        });
        assert!(serde_json::from_value::<ExecuteInput>(input).is_err());
    }

    // -----------------------------------------------------------------------
    // truncate_output
    // -----------------------------------------------------------------------

    #[test]
    fn truncate_output_short_output_unchanged() {
        let lines: Vec<String> = (0..10).map(|i| format!("line {i}")).collect();
        let result = truncate_output(lines.clone());
        assert_eq!(result, lines);
    }

    #[test]
    fn truncate_output_at_limit_unchanged() {
        let lines: Vec<String> = (0..OUTPUT_LINE_LIMIT)
            .map(|i| format!("line {i}"))
            .collect();
        let result = truncate_output(lines.clone());
        assert_eq!(result, lines);
    }

    #[test]
    fn truncate_output_over_limit_adds_marker() {
        let lines: Vec<String> = (0..OUTPUT_LINE_LIMIT + 50)
            .map(|i| format!("line {i}"))
            .collect();
        let result = truncate_output(lines);
        assert_eq!(result.len(), OUTPUT_LINE_LIMIT + 1);
        assert!(result.last().unwrap().contains("truncated"));
        assert!(result.last().unwrap().contains("50"));
    }

    // -----------------------------------------------------------------------
    // P4 — MCP <-> daemon IPC integration against a fake daemon.
    //
    // Drives the real MCP tool functions (history_inner, execute_steps_inner)
    // over a real Unix socket + the production FramedStream, against a stub
    // daemon that speaks the daemon wire protocol. This exercises the actual
    // request/response shapes end to end (catching wire drift) and, crucially,
    // proves the approval interlock: when the daemon rejects a receipt, MCP
    // execute must surface an error, never report success.
    //
    // nextest runs each test in its own process, so setting SYSKNIFE_SOCKET
    // here does not leak into other tests.
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn mcp_tools_integrate_with_a_daemon_over_the_socket() {
        use sysknife_daemon::transport::framing::FramedStream;
        use tokio::net::UnixListener;

        let dir = tempfile::tempdir().unwrap();
        let sock = dir.path().join("fake-daemon.sock");
        let listener = UnixListener::bind(&sock).unwrap();

        // Stub daemon: one request per connection (the client opens a fresh
        // connection per call). query_history -> structured row; execute ->
        // error_response(stale_approval) to model a rejected receipt.
        let server = tokio::spawn(async move {
            loop {
                let (stream, _) = match listener.accept().await {
                    Ok(pair) => pair,
                    Err(_) => break,
                };
                tokio::spawn(async move {
                    let mut framed = FramedStream::new(stream);
                    let Ok(raw) = framed.recv().await else { return };
                    let req: serde_json::Value = serde_json::from_slice(&raw).unwrap();
                    let resp = match req["type"].as_str() {
                        Some("query_history") => serde_json::json!({
                            "type": "history_response",
                            "request_id": req["request_id"],
                            "entries": [{
                                "transaction_id": "tx-abc123",
                                "action_name": "GetDiskUsage",
                                "risk_level": "low",
                                "status": "succeeded",
                                "summary": "check disk usage",
                                "created_at": "2026-07-19T12:00:00Z"
                            }]
                        }),
                        Some("execute") => serde_json::json!({
                            "type": "error_response",
                            "request_id": req["request_id"],
                            "category": "stale_approval",
                            "message": "transaction is not approved for this receipt"
                        }),
                        other => serde_json::json!({
                            "type": "error_response",
                            "request_id": req["request_id"],
                            "category": "validation_failure",
                            "message": format!("unexpected request: {other:?}")
                        }),
                    };
                    let _ = framed.send(&serde_json::to_vec(&resp).unwrap()).await;
                });
            }
        });

        std::env::set_var("SYSKNIFE_SOCKET", sock.to_str().unwrap());

        // History flows through the structured IPC with typed fields populated.
        let entries = history_inner(HistoryInput {
            status: None,
            action: None,
            since: None,
            limit: Some(5),
        })
        .await
        .expect("history over socket");
        assert_eq!(entries.len(), 1);
        assert_eq!(entries[0].action, "GetDiskUsage");
        assert_eq!(
            entries[0].created_at.as_deref(),
            Some("2026-07-19T12:00:00Z")
        );
        assert_eq!(entries[0].risk_level.as_deref(), Some("low"));

        // Interlock: the daemon rejects the receipt, so execute MUST error,
        // never fabricate a success result.
        let result = execute_steps_inner(vec![StepToExecute {
            transaction_id: "tx-abc123".to_string(),
            action_name: "GetDiskUsage".to_string(),
            params: serde_json::json!({}),
            approval_receipt: "receipt-the-daemon-will-reject".to_string(),
        }])
        .await;
        assert!(
            result.is_err(),
            "a daemon-rejected receipt must surface as an MCP error, got: {result:?}"
        );
        assert!(
            result.unwrap_err().contains("stale_approval"),
            "the rejection reason must reach the caller"
        );

        std::env::remove_var("SYSKNIFE_SOCKET");
        server.abort();
    }
}