mkit-cli 0.4.1

The mkit command-line tool: a content-addressed VCS with native attestation support
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
//! Integration tests for `mkit mcp` — the stdio Model Context Protocol
//! server. We spawn the real binary and speak newline-delimited
//! JSON-RPC over its stdin/stdout, exercising the full
//! initialize → tools/list → tools/call lifecycle against temp repos.
#![allow(clippy::unwrap_used)] // unwrap is the assertion in test helpers

use std::io::{BufRead, BufReader, Write};
use std::path::Path;
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};

use serde_json::{Value, json};

fn mkit_bin() -> &'static str {
    env!("CARGO_BIN_EXE_mkit")
}

/// A live `mkit mcp` subprocess with helpers to exchange JSON-RPC.
struct McpClient {
    child: Child,
    stdin: ChildStdin,
    stdout: BufReader<ChildStdout>,
    next_id: i64,
    _xdg: tempfile::TempDir,
}

impl McpClient {
    fn spawn(repository: Option<&Path>) -> Self {
        // Isolated XDG so the developer's real mkit config never
        // bleeds into tool subprocesses (the server passes env down).
        let xdg = tempfile::tempdir().expect("xdg tempdir");
        let mut cmd = Command::new(mkit_bin());
        cmd.arg("mcp");
        if let Some(repo) = repository {
            cmd.args(["--repository", repo.to_str().unwrap()]);
        }
        let mut child = cmd
            .env("XDG_CONFIG_HOME", xdg.path())
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::null())
            .spawn()
            .expect("spawn mkit mcp");
        let stdin = child.stdin.take().unwrap();
        let stdout = BufReader::new(child.stdout.take().unwrap());
        let mut client = Self {
            child,
            stdin,
            stdout,
            next_id: 0,
            _xdg: xdg,
        };
        // Standard MCP handshake.
        let init = client.request(
            "initialize",
            &json!({ "protocolVersion": "2024-11-05", "capabilities": {},
                    "clientInfo": { "name": "test", "version": "0" } }),
        );
        assert_eq!(
            init.pointer("/result/serverInfo/name")
                .and_then(Value::as_str),
            Some("mkit-repo")
        );
        client.notify("notifications/initialized");
        client
    }

    fn request(&mut self, method: &str, params: &Value) -> Value {
        self.next_id += 1;
        let id = self.next_id;
        let msg = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params });
        writeln!(self.stdin, "{msg}").expect("write request");
        self.stdin.flush().unwrap();
        // Responses are strictly ordered (sequential server), so the
        // next line is ours; assert the id to be safe.
        let mut line = String::new();
        self.stdout.read_line(&mut line).expect("read response");
        let resp: Value = serde_json::from_str(&line).expect("response is JSON");
        assert_eq!(
            resp.get("id").and_then(Value::as_i64),
            Some(id),
            "id mismatch: {line}"
        );
        resp
    }

    fn notify(&mut self, method: &str) {
        let msg = json!({ "jsonrpc": "2.0", "method": method });
        writeln!(self.stdin, "{msg}").expect("write notification");
        self.stdin.flush().unwrap();
    }

    /// Call a tool; returns `(text, is_error)`.
    fn call(&mut self, tool: &str, args: &Value) -> (String, bool) {
        let resp = self.request("tools/call", &json!({ "name": tool, "arguments": args }));
        let result = resp
            .get("result")
            .unwrap_or_else(|| panic!("no result: {resp}"));
        let text = result
            .pointer("/content/0/text")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string();
        let is_error = result
            .get("isError")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        (text, is_error)
    }
}

impl Drop for McpClient {
    fn drop(&mut self) {
        // Closing stdin ends the serve loop; reap the child.
        let _ = self.child.kill();
        let _ = self.child.wait();
    }
}

fn ok(client: &mut McpClient, tool: &str, args: &Value) -> String {
    let (text, is_error) = client.call(tool, args);
    assert!(!is_error, "{tool} unexpectedly failed: {text}");
    text
}

fn err(client: &mut McpClient, tool: &str, args: &Value) -> String {
    let (text, is_error) = client.call(tool, args);
    assert!(is_error, "{tool} unexpectedly succeeded: {text}");
    text
}

#[test]
fn lists_all_tools_with_annotations() {
    let repo = tempfile::tempdir().unwrap();
    let mut client = McpClient::spawn(Some(repo.path()));

    let resp = client.request("tools/list", &json!({}));
    let tools = resp.pointer("/result/tools").unwrap().as_array().unwrap();
    assert_eq!(tools.len(), 18);

    let names: Vec<&str> = tools
        .iter()
        .map(|t| t.get("name").unwrap().as_str().unwrap())
        .collect();
    for expected in [
        "mkit_status",
        "mkit_diff_unstaged",
        "mkit_diff_staged",
        "mkit_diff",
        "mkit_log",
        "mkit_show",
        "mkit_branch",
        "mkit_cat_object",
        "mkit_verify",
        "mkit_verify_attest",
        "mkit_add",
        "mkit_unstage",
        "mkit_commit",
        "mkit_create_branch",
        "mkit_checkout",
        "mkit_init",
        "mkit_keygen",
        "mkit_attest",
    ] {
        assert!(names.contains(&expected), "missing tool {expected}");
    }
    for t in tools {
        assert_eq!(t.pointer("/annotations/openWorldHint"), Some(&json!(false)));
    }
}

/// #505 PR 5/5: shared setup for the per-behavior tests below (split
/// from the former `full_workflow_init_to_log` mega-test, which chained
/// ~11 behaviors into one `#[test]` — a failure partway through gave no
/// signal about which later behavior would have passed). Establishes
/// init → keygen → add `hello.txt` → status → commit "via mcp", with the
/// same assertions the mega-test made along the way, then hands back the
/// live client plus repo path so each dependent test continues from a
/// known-good state. Returns the repo tempdir too — it must outlive the
/// client for tests that write more files into the worktree.
fn init_keygen_committed() -> (tempfile::TempDir, McpClient, String) {
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));

    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    let pubkey = ok(
        &mut client,
        "mkit_keygen",
        &json!({ "repo_path": repo, "print_pubkey": true }),
    );
    assert!(pubkey.contains("ed25519:"), "keygen output: {pubkey}");

    std::fs::write(root.path().join("hello.txt"), "hello mcp\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["hello.txt"] }),
    );

    let status = ok(&mut client, "mkit_status", &json!({ "repo_path": repo }));
    assert!(status.contains("hello.txt"), "status: {status}");

    let commit = ok(
        &mut client,
        "mkit_commit",
        &json!({ "repo_path": repo, "message": "via mcp" }),
    );
    // git-shaped summary: `[<branch> <hash>] <subject>`.
    assert!(
        commit.contains("[main ") && commit.contains("via mcp"),
        "commit: {commit}"
    );

    (root, client, repo)
}

#[test]
fn mcp_workflow_init_keygen_add_status_commit() {
    // All the assertions for this behavior live in `init_keygen_committed`
    // itself; this test exists so the setup chain (init/keygen/add/status/
    // commit) has its own localizable name distinct from the tests below
    // that build on top of it.
    let (_root, _client, _repo) = init_keygen_committed();
}

#[test]
fn mcp_workflow_log_shows_committed_message() {
    let (_root, mut client, repo) = init_keygen_committed();
    let log = ok(&mut client, "mkit_log", &json!({ "repo_path": repo }));
    assert!(log.contains("via mcp"), "log: {log}");
}

#[test]
fn mcp_workflow_verify_reports_ok() {
    let (_root, mut client, repo) = init_keygen_committed();
    let verify = ok(
        &mut client,
        "mkit_verify",
        &json!({ "repo_path": repo, "revision": "HEAD" }),
    );
    assert!(verify.contains("ok"), "verify: {verify}");
}

#[test]
fn mcp_workflow_branch_create_and_checkout_round_trip() {
    let (_root, mut client, repo) = init_keygen_committed();
    ok(
        &mut client,
        "mkit_create_branch",
        &json!({ "repo_path": repo, "branch_name": "feature" }),
    );
    ok(
        &mut client,
        "mkit_checkout",
        &json!({ "repo_path": repo, "branch_name": "feature" }),
    );
    let branches = ok(&mut client, "mkit_branch", &json!({ "repo_path": repo }));
    assert!(branches.contains("feature"), "branch: {branches}");
}

#[test]
fn mcp_workflow_unstage_clears_staged_changes() {
    let (root, mut client, repo) = init_keygen_committed();
    std::fs::write(root.path().join("two.txt"), "two\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["two.txt"] }),
    );
    ok(&mut client, "mkit_unstage", &json!({ "repo_path": repo }));
    let status = ok(&mut client, "mkit_status", &json!({ "repo_path": repo }));
    assert!(
        !status.contains("A "),
        "after unstage, nothing staged: {status}"
    );
}

#[test]
fn mcp_workflow_attest_then_show_reports_commit() {
    let (_root, mut client, repo) = init_keygen_committed();

    // Attestation: produce one, then inspect the commit object.
    // `mkit attest` prints `attested <64-hex att-id> → <path> (<n>
    // signature(s))` to stderr (surfaced as the tool text since stdout is
    // empty) — pin that shape instead of a substring-or-length guess.
    let att = ok(&mut client, "mkit_attest", &json!({ "repo_path": repo }));
    assert!(
        att.starts_with("attested ") && att.contains(" signature(s))"),
        "attest: unexpected output shape: {att}"
    );
    let att_id = att
        .strip_prefix("attested ")
        .and_then(|rest| rest.split_whitespace().next())
        .unwrap_or_default();
    assert_eq!(
        att_id.len(),
        64,
        "att-id should be a 64-char hex hash: {att}"
    );
    assert!(
        att_id.chars().all(|c| c.is_ascii_hexdigit()),
        "att-id should be hex: {att}"
    );
    let shown = ok(
        &mut client,
        "mkit_show",
        &json!({ "repo_path": repo, "revision": "HEAD" }),
    );
    assert!(shown.contains("via mcp"), "show: {shown}");
}

#[test]
fn commit_without_key_errors_with_guidance() {
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));

    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    std::fs::write(root.path().join("a.txt"), "a\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["a.txt"] }),
    );

    let text = err(
        &mut client,
        "mkit_commit",
        &json!({ "repo_path": repo, "message": "x" }),
    );
    assert!(
        text.contains("keygen"),
        "error should point at keygen: {text}"
    );
    assert!(
        text.contains("exited"),
        "error carries the exit code: {text}"
    );
}

#[test]
fn keygen_refuses_overwrite() {
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));

    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    ok(&mut client, "mkit_keygen", &json!({ "repo_path": repo }));
    // Second keygen must fail — the server never passes --force.
    err(&mut client, "mkit_keygen", &json!({ "repo_path": repo }));
}

#[test]
fn scope_confines_repo_path() {
    let allowed = tempfile::tempdir().unwrap();
    let outside = tempfile::tempdir().unwrap();
    let mut client = McpClient::spawn(Some(allowed.path()));

    let text = err(
        &mut client,
        "mkit_status",
        &json!({ "repo_path": outside.path().to_str().unwrap() }),
    );
    assert!(
        text.contains("outside the allowed repository"),
        "scope error: {text}"
    );
}

#[test]
fn flag_injection_rejected_end_to_end() {
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));
    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));

    let text = err(
        &mut client,
        "mkit_diff",
        &json!({ "repo_path": repo, "target": "-R" }),
    );
    assert!(text.contains("must not start with '-'"), "{text}");
    let text = err(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["-A"] }),
    );
    assert!(text.contains("must not start with '-'"), "{text}");
}

#[test]
fn unknown_tool_is_a_protocol_error() {
    let repo = tempfile::tempdir().unwrap();
    let mut client = McpClient::spawn(Some(repo.path()));
    let resp = client.request(
        "tools/call",
        &json!({ "name": "mkit_push", "arguments": { "repo_path": "." } }),
    );
    assert_eq!(
        resp.pointer("/error/code").and_then(Value::as_i64),
        Some(-32602)
    );
    let msg = resp
        .pointer("/error/message")
        .and_then(Value::as_str)
        .unwrap();
    assert!(msg.contains("unknown tool"), "{msg}");
}

#[test]
fn unknown_method_and_ping() {
    let repo = tempfile::tempdir().unwrap();
    let mut client = McpClient::spawn(Some(repo.path()));

    let resp = client.request("ping", &json!({}));
    assert!(resp.get("result").is_some());

    let resp = client.request("resources/list", &json!({}));
    assert_eq!(
        resp.pointer("/error/code").and_then(Value::as_i64),
        Some(-32601)
    );
}

// --- Helpers for the attestation security tests -----------------------------

/// Decode an even-length lowercase-hex string into bytes.
fn hex_decode(s: &str) -> Vec<u8> {
    (0..s.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap())
        .collect()
}

/// The `blake3:<hex>` keyid the repo-key signer reports for `default.key`,
/// derived from the public key the same way the CLI does.
fn repo_keyid(pubkey_hex: &str) -> String {
    let pk = hex_decode(pubkey_hex);
    format!(
        "blake3:{}",
        mkit_core::hash::to_hex(&mkit_core::hash::hash(&pk))
    )
}

/// Pull the `<hex>` out of a `keygen --print-pubkey` "...ed25519:<hex>..." line.
fn pubkey_hex_from(keygen_output: &str) -> String {
    let idx = keygen_output
        .find("ed25519:")
        .expect("keygen prints ed25519:<hex>");
    keygen_output[idx + "ed25519:".len()..]
        .chars()
        .take_while(char::is_ascii_hexdigit)
        .collect()
}

#[test]
fn verify_attest_succeeds_with_external_trust_roots() {
    // The most security-sensitive differentiator path, end-to-end through
    // JSON-RPC: attest a commit, then verify it against a trust-roots file
    // OUTSIDE the repo (the only kind the MCP accepts).
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));

    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    let keygen = ok(
        &mut client,
        "mkit_keygen",
        &json!({ "repo_path": repo, "print_pubkey": true }),
    );
    let pubkey_hex = pubkey_hex_from(&keygen);

    std::fs::write(root.path().join("a.txt"), "a\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["a.txt"] }),
    );
    ok(
        &mut client,
        "mkit_commit",
        &json!({ "repo_path": repo, "message": "c" }),
    );
    ok(&mut client, "mkit_attest", &json!({ "repo_path": repo }));

    // Trust-roots pinned to our repo key, written OUTSIDE the repo.
    let roots_dir = tempfile::tempdir().unwrap();
    let roots = roots_dir.path().join("trust-roots.toml");
    std::fs::write(
        &roots,
        format!(
            "[[trust_root]]\nkeyid = \"{}\"\nkind = \"ed25519\"\npubkey_hex = \"{}\"\n",
            repo_keyid(&pubkey_hex),
            pubkey_hex
        ),
    )
    .unwrap();

    // Explicit "HEAD" must work (regression for the hex-only --commit trap).
    let out = ok(
        &mut client,
        "mkit_verify_attest",
        &json!({ "repo_path": repo, "commit": "HEAD", "trust_roots": roots.to_str().unwrap() }),
    );
    assert!(
        out.to_lowercase().contains("verif") || out.contains("ok"),
        "verify-attest: {out}"
    );
}

#[test]
fn verify_attest_rejects_in_repo_trust_roots() {
    // Hostile-clone defense: a repo-local trust-roots can never be selected
    // through the MCP, even though the CLI would honor an explicit path.
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));
    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    // Plant an attacker trust-roots inside the repo.
    std::fs::write(root.path().join(".mkit/attest-trust-roots.toml"), "x").unwrap();

    let text = err(
        &mut client,
        "mkit_verify_attest",
        &json!({ "repo_path": repo, "trust_roots": ".mkit/attest-trust-roots.toml" }),
    );
    assert!(text.contains("inside the repository"), "{text}");
}

#[test]
fn verify_trusted_succeeds_with_external_trust_roots() {
    // `mkit_verify`'s `trusted`/`trust_roots` args (issue #693), end-to-end
    // through JSON-RPC: commit, then cross-check the commit's signer
    // against a trust-roots file OUTSIDE the repo.
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));

    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    let keygen = ok(
        &mut client,
        "mkit_keygen",
        &json!({ "repo_path": repo, "print_pubkey": true }),
    );
    let pubkey_hex = pubkey_hex_from(&keygen);

    std::fs::write(root.path().join("a.txt"), "a\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["a.txt"] }),
    );
    ok(
        &mut client,
        "mkit_commit",
        &json!({ "repo_path": repo, "message": "c" }),
    );

    let roots_dir = tempfile::tempdir().unwrap();
    let roots = roots_dir.path().join("trust-roots.toml");
    std::fs::write(
        &roots,
        format!(
            "[[trust_root]]\nkeyid = \"ed25519:{pubkey_hex}\"\nkind = \"ed25519\"\npubkey_hex = \"{pubkey_hex}\"\n"
        ),
    )
    .unwrap();

    let out = ok(
        &mut client,
        "mkit_verify",
        &json!({ "repo_path": repo, "revision": "HEAD", "trust_roots": roots.to_str().unwrap() }),
    );
    assert!(out.contains("trusted"), "verify: {out}");
}

#[test]
fn verify_trusted_fails_closed_for_unregistered_signer_via_mcp() {
    let (_root, mut client, repo) = init_keygen_committed();

    let roots_dir = tempfile::tempdir().unwrap();
    let roots = roots_dir.path().join("trust-roots.toml");
    let other_hex = "77".repeat(32);
    std::fs::write(
        &roots,
        format!(
            "[[trust_root]]\nkeyid = \"ed25519:{other_hex}\"\nkind = \"ed25519\"\npubkey_hex = \"{other_hex}\"\n"
        ),
    )
    .unwrap();

    let text = err(
        &mut client,
        "mkit_verify",
        &json!({ "repo_path": repo, "revision": "HEAD", "trust_roots": roots.to_str().unwrap() }),
    );
    assert!(
        text.contains("not in the trust-roots registry") || text.to_lowercase().contains("untrust"),
        "{text}"
    );
}

#[test]
fn verify_rejects_in_repo_trust_roots() {
    // Same hostile-clone defense as verify-attest: a repo-local
    // trust-roots path can never be selected through the MCP for
    // `mkit_verify` either.
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));
    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    std::fs::write(root.path().join(".mkit/trust-roots.toml"), "x").unwrap();

    let text = err(
        &mut client,
        "mkit_verify",
        &json!({ "repo_path": repo, "revision": "HEAD", "trust_roots": ".mkit/trust-roots.toml" }),
    );
    assert!(text.contains("inside the repository"), "{text}");
}

#[test]
fn attest_rejects_predicate_file_outside_repo() {
    // Scope escape: a scoped MCP must not read an outside file into a
    // signed attestation, even though --repository only confines repo_path.
    let root = tempfile::tempdir().unwrap();
    let repo = root.path().to_str().unwrap().to_string();
    let mut client = McpClient::spawn(Some(root.path()));
    ok(&mut client, "mkit_init", &json!({ "repo_path": repo }));
    ok(&mut client, "mkit_keygen", &json!({ "repo_path": repo }));
    std::fs::write(root.path().join("a.txt"), "a\n").unwrap();
    ok(
        &mut client,
        "mkit_add",
        &json!({ "repo_path": repo, "files": ["a.txt"] }),
    );
    ok(
        &mut client,
        "mkit_commit",
        &json!({ "repo_path": repo, "message": "c" }),
    );

    let outside = tempfile::tempdir().unwrap();
    let secret = outside.path().join("outside.json");
    std::fs::write(&secret, "{}").unwrap();

    let text = err(
        &mut client,
        "mkit_attest",
        &json!({ "repo_path": repo, "predicate_file": secret.to_str().unwrap() }),
    );
    assert!(text.contains("outside the repository"), "{text}");
}

#[test]
fn batch_requests_get_a_single_array_response() {
    // JSON-RPC 2.0: a batch request is answered with ONE array response;
    // a batch of only notifications is answered with nothing at all.
    let repo = tempfile::tempdir().unwrap();
    let mut child = Command::new(mkit_bin())
        .args(["mcp", "--repository", repo.path().to_str().unwrap()])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::null())
        .spawn()
        .expect("spawn mkit mcp");
    let mut stdin = child.stdin.take().unwrap();
    let mut stdout = BufReader::new(child.stdout.take().unwrap());

    // A notification-only batch first: must produce NO response line.
    writeln!(
        stdin,
        r#"[{{"jsonrpc":"2.0","method":"notifications/initialized"}}]"#
    )
    .unwrap();
    // Then a request batch: initialize + tools/list in one line.
    writeln!(
        stdin,
        r#"[{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"protocolVersion":"2025-06-18"}}}},{{"jsonrpc":"2.0","id":2,"method":"tools/list"}}]"#
    )
    .unwrap();
    stdin.flush().unwrap();

    // The first line out must be the array for the second batch (the
    // notification-only batch yields nothing).
    let mut line = String::new();
    stdout.read_line(&mut line).unwrap();
    let resp: Value = serde_json::from_str(&line).expect("batch response is JSON");
    let arr = resp
        .as_array()
        .expect("batch response must be a single JSON array");
    assert_eq!(arr.len(), 2);
    assert_eq!(
        arr[0]
            .pointer("/result/serverInfo/name")
            .and_then(Value::as_str),
        Some("mkit-repo")
    );
    assert_eq!(
        arr[1]
            .pointer("/result/tools")
            .unwrap()
            .as_array()
            .unwrap()
            .len(),
        18
    );

    drop(stdin);
    let _ = child.wait();
}