tsafe-mcp 2.0.1

Bound-contract MCP server for tsafe — run policy-scoped commands without exposing secret values.
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
//! Immutable per-process Session: bound profile, allowed/denied globs,
//! optional contract.
//!
//! Construction happens exactly once in `tsafe-mcp serve` startup. The
//! session is shared across every JSON-RPC tool call for the life of the
//! process. Mutation is forbidden: request-time profile or scope changes
//! return `-32008 ScopeWidening` per design §6.2 / ADR-006 doctrine row for
//! the thin-MCP stance "one profile per server".

use std::path::{Path, PathBuf};

use tsafe_core::contracts::{self, AuthorityContract};
use tsafe_core::profile;

use crate::errors::{McpError, McpErrorKind};

/// Default profile name used when `TSAFE_MCP_EPHEMERAL_PROFILE` is requested
/// without an explicit `--profile`. Chosen to be obviously synthetic so it can
/// never collide with a real operator profile on disk.
pub const EPHEMERAL_PROFILE_NAME: &str = "__tsafe_ephemeral__";

/// Parsed CLI/env arguments passed into [`Session::from_cli_args`].
#[derive(Debug, Clone, Default)]
pub struct SessionArgs {
    pub profile: Option<String>,
    pub allowed_keys: Vec<String>,
    pub denied_keys: Vec<String>,
    pub contract: Option<String>,
    pub workdir: Option<PathBuf>,
    pub allow_reveal: bool,
    pub audit_source: Option<String>,
    /// When `true`, refuse to start if `tsafe-agent` is not reachable. Default
    /// is `true`; tests opt out by setting `TSAFE_MCP_REQUIRE_AGENT=0`.
    pub require_agent: bool,
    /// When `true`, the on-disk vault-file-existence startup check is skipped
    /// so handshake/protocol tests can drive `initialize`, `tools/list`, and
    /// `ping` without provisioning a vault. Test-only; enabled by
    /// `TSAFE_MCP_EPHEMERAL_PROFILE`. Tool calls that open the vault still
    /// fail-closed because no real vault or agent is fabricated.
    pub ephemeral_profile: bool,
}

impl SessionArgs {
    /// Parse `serve` argv (without the binary path or subcommand prefix) plus
    /// environment variables per design §4.1.
    pub fn parse(argv: &[String]) -> Result<Self, McpError> {
        let mut out = SessionArgs {
            require_agent: env_truthy("TSAFE_MCP_REQUIRE_AGENT", true),
            ephemeral_profile: env_truthy("TSAFE_MCP_EPHEMERAL_PROFILE", false),
            ..SessionArgs::default()
        };

        // An ephemeral profile is for vault-less handshake/protocol tests. When
        // requested without an explicit profile name, synthesize a stable one
        // so the non-blank-profile startup check still passes. An explicit
        // --profile / TSAFE_MCP_PROFILE always wins over this default.
        if out.ephemeral_profile {
            out.profile = Some(EPHEMERAL_PROFILE_NAME.to_string());
        }

        // Env defaults — flag values override these.
        if let Ok(v) = std::env::var("TSAFE_MCP_PROFILE") {
            if !v.is_empty() {
                out.profile = Some(v);
            }
        }
        if let Ok(v) = std::env::var("TSAFE_MCP_ALLOWED_KEYS") {
            out.allowed_keys = split_csv(&v);
        }
        if let Ok(v) = std::env::var("TSAFE_MCP_DENIED_KEYS") {
            out.denied_keys = split_csv(&v);
        }
        if let Ok(v) = std::env::var("TSAFE_MCP_CONTRACT") {
            if !v.is_empty() {
                out.contract = Some(v);
            }
        }
        if let Ok(v) = std::env::var("TSAFE_MCP_WORKDIR") {
            if !v.is_empty() {
                out.workdir = Some(PathBuf::from(v));
            }
        }
        if env_truthy("TSAFE_MCP_ALLOW_REVEAL", false) {
            out.allow_reveal = true;
        }
        if let Ok(v) = std::env::var("TSAFE_MCP_AUDIT_SOURCE") {
            if !v.is_empty() {
                out.audit_source = Some(v);
            }
        }

        let mut i = 0;
        while i < argv.len() {
            match argv[i].as_str() {
                "--profile" => {
                    i += 1;
                    out.profile = Some(require_value(argv, i, "--profile")?);
                }
                "--allowed-keys" => {
                    i += 1;
                    out.allowed_keys = split_csv(&require_value(argv, i, "--allowed-keys")?);
                }
                "--denied-keys" => {
                    i += 1;
                    out.denied_keys = split_csv(&require_value(argv, i, "--denied-keys")?);
                }
                "--contract" => {
                    i += 1;
                    out.contract = Some(require_value(argv, i, "--contract")?);
                }
                "--workdir" => {
                    i += 1;
                    out.workdir = Some(PathBuf::from(require_value(argv, i, "--workdir")?));
                }
                "--allow-reveal" => out.allow_reveal = true,
                "--audit-source" => {
                    i += 1;
                    out.audit_source = Some(require_value(argv, i, "--audit-source")?);
                }
                "--no-require-agent" => out.require_agent = false,
                other => {
                    return Err(McpError::new(
                        McpErrorKind::InvalidRequest,
                        format!("unknown serve flag: '{other}'"),
                    ));
                }
            }
            i += 1;
        }

        Ok(out)
    }
}

fn require_value(argv: &[String], i: usize, flag: &str) -> Result<String, McpError> {
    argv.get(i).cloned().ok_or_else(|| {
        McpError::new(
            McpErrorKind::InvalidRequest,
            format!("{flag} requires a value"),
        )
    })
}

fn split_csv(raw: &str) -> Vec<String> {
    raw.split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

fn env_truthy(name: &str, default: bool) -> bool {
    match std::env::var(name) {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            !matches!(v.as_str(), "" | "0" | "false" | "no" | "off")
        }
        Err(_) => default,
    }
}

/// Immutable scope/profile binding for the life of the `tsafe-mcp serve`
/// process.
#[derive(Debug, Clone)]
pub struct Session {
    pub profile: String,
    pub allowed_globs: Vec<String>,
    pub denied_globs: Vec<String>,
    pub contract: Option<AuthorityContract>,
    pub workdir: Option<PathBuf>,
    pub allow_reveal: bool,
    pub audit_source: String,
    pub pid: u32,
    pub require_agent: bool,
    pub vault_path: PathBuf,
}

impl Session {
    /// Build a session from parsed args. Performs every fail-closed startup
    /// check listed in design §4.1.
    pub fn from_cli_args(args: &SessionArgs) -> Result<Self, McpError> {
        // 1. Profile must be present + non-blank.
        let profile = args.profile.clone().unwrap_or_default();
        let profile = profile.trim().to_string();
        if profile.is_empty() {
            return Err(McpError::new(
                McpErrorKind::ProfileNotFound,
                "--profile <name> is required",
            ));
        }

        // 2. Vault file for the profile must exist on disk. The ephemeral
        //    test profile skips this check so handshake/protocol tests can run
        //    without provisioning a vault; vault-opening tool calls still
        //    fail-closed at request time because no real vault is fabricated.
        let vault_path = profile::vault_path(&profile);
        if !args.ephemeral_profile && !vault_path.exists() {
            return Err(McpError::new(
                McpErrorKind::ProfileNotFound,
                format!("Profile '{profile}' not found at {}", vault_path.display()),
            ));
        }

        let workdir = match args.workdir.as_ref() {
            Some(path) => Some(resolve_workdir(path)?),
            None => None,
        };

        // 3. Resolve optional contract by name. Contracts ride alongside the
        //    profile under the normal `tsafe contract` storage path.
        let contract = if let Some(name) = args.contract.as_deref() {
            Some(load_contract(&profile, name, workdir.as_deref())?)
        } else {
            None
        };
        if contract
            .as_ref()
            .is_some_and(|contract| contract.allow_all_secrets)
        {
            return Err(McpError::new(
                McpErrorKind::InvalidRequest,
                "bound MCP contracts must set allowed_secrets explicitly; use allowed_secrets: [] for no-secret diagnostics",
            ));
        }

        // 4. Scope binding — refuse blank scope per thin-stance "no blank-
        //    namespace widening" (design §6.2). Either allowed_keys non-empty
        //    OR a contract that supplies allowed_secrets is required.
        let contract_supplies_scope = contract
            .as_ref()
            .map(|c| !c.allowed_secrets.is_empty())
            .unwrap_or(false);
        let bound_no_secret_contract = contract.is_some() && workdir.is_some();
        if args.allowed_keys.is_empty() && !contract_supplies_scope && !bound_no_secret_contract {
            return Err(McpError::new(
                McpErrorKind::InvalidRequest,
                "no scope: --allowed-keys, scoped --contract, or bound --contract + --workdir required",
            ));
        }

        let pid = std::process::id();
        let audit_source = args
            .audit_source
            .clone()
            .unwrap_or_else(|| format!("mcp:unknown:{pid}"));

        Ok(Session {
            profile,
            allowed_globs: args.allowed_keys.clone(),
            denied_globs: args.denied_keys.clone(),
            contract,
            workdir,
            allow_reveal: args.allow_reveal,
            audit_source,
            pid,
            require_agent: args.require_agent,
            vault_path,
        })
    }

    /// Return `true` when `key` is inside the effective scope:
    /// `allowed_globs ∩ ¬denied_globs ∩ contract.allowed_secrets`.
    ///
    /// Blank `allowed_globs` only reaches this method when a contract supplies
    /// scope (refused at startup otherwise), in which case the contract's
    /// allowed_secrets list serves as the allowlist.
    pub fn is_in_scope(&self, key: &str) -> bool {
        // Allowed: empty list with contract present = use contract's allowed_secrets
        // as the source of truth. Otherwise must match at least one allowed glob.
        let allowed_by_globs = if self.allowed_globs.is_empty() {
            // No allowed globs — fall through to contract check.
            self.contract
                .as_ref()
                .is_some_and(|contract| !contract.allowed_secrets.is_empty())
        } else {
            self.allowed_globs.iter().any(|pat| glob_match(pat, key))
        };
        if !allowed_by_globs {
            return false;
        }
        // Denied list always trumps allowed.
        if self.denied_globs.iter().any(|pat| glob_match(pat, key)) {
            return false;
        }
        // Contract intersection.
        if let Some(contract) = &self.contract {
            if !contract.allowed_secrets.is_empty()
                && !contract.allowed_secrets.iter().any(|s| s == key)
            {
                return false;
            }
        }
        true
    }

    pub fn is_bound_contract_mode(&self) -> bool {
        self.contract.is_some() && self.workdir.is_some()
    }
}

fn resolve_workdir(path: &Path) -> Result<PathBuf, McpError> {
    if path.as_os_str().is_empty() {
        return Err(
            McpError::new(McpErrorKind::BadWorkdir, "--workdir is blank").with_resolution(
                "Bad workdir",
                "--workdir must point to an existing directory",
                vec!["Pass an absolute project directory path".to_string()],
            ),
        );
    }
    let resolved = path.canonicalize().map_err(|e| {
        McpError::new(McpErrorKind::BadWorkdir, format!("{}: {e}", path.display())).with_resolution(
            "Bad workdir",
            format!("{} could not be resolved: {e}", path.display()),
            vec!["Create the directory or pass the intended repository root".to_string()],
        )
    })?;
    if !resolved.is_dir() {
        return Err(McpError::new(
            McpErrorKind::BadWorkdir,
            format!("{} is not a directory", resolved.display()),
        )
        .with_resolution(
            "Bad workdir",
            format!("{} is not a directory", resolved.display()),
            vec!["Pass a repository directory, not a file".to_string()],
        ));
    }
    Ok(resolved)
}

fn load_contract(
    _profile: &str,
    name: &str,
    workdir: Option<&Path>,
) -> Result<AuthorityContract, McpError> {
    // Contracts live in a repo manifest reachable from cwd, per tsafe-core
    // (`contracts::find_contracts_manifest` / `load_contract`).
    let cwd = workdir
        .map(Path::to_path_buf)
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
    let manifest = contracts::find_contracts_manifest(&cwd).ok_or_else(|| {
        McpError::new(
            McpErrorKind::ContractMissing,
            format!(
                "contract '{name}' requested but no contracts manifest found from cwd {}",
                cwd.display()
            ),
        )
        .with_resolution(
            "Missing contract",
            format!("No .tsafe.yml or .tsafe.json found from {}", cwd.display()),
            vec![
                "Create .tsafe.yml in the bound workdir".to_string(),
                "Pass --workdir pointing at the repository containing the contract".to_string(),
            ],
        )
    })?;
    contracts::load_contract(&manifest, name).map_err(|e| {
        McpError::new(
            McpErrorKind::ContractMissing,
            format!("contract '{name}' could not be loaded: {e}"),
        )
        .with_resolution(
            "Missing contract",
            format!(
                "Contract '{name}' could not be loaded from {}: {e}",
                manifest.display()
            ),
            vec![
                "Check the contract name".to_string(),
                "Run tsafe exec --contract <name> --plan from the same workdir".to_string(),
            ],
        )
    })
}

/// Minimal glob matcher supporting `*` (zero or more), `?` (exactly one), and
/// literal characters. Sufficient for tsafe key-name conventions; we do not
/// support character classes `[...]`.
pub(crate) fn glob_match(pattern: &str, candidate: &str) -> bool {
    glob_match_impl(pattern.as_bytes(), candidate.as_bytes())
}

fn glob_match_impl(pat: &[u8], s: &[u8]) -> bool {
    let (mut pi, mut si) = (0usize, 0usize);
    let (mut star_pi, mut star_si) = (None, 0usize);

    while si < s.len() {
        if pi < pat.len() && (pat[pi] == b'?' || pat[pi] == s[si]) {
            pi += 1;
            si += 1;
        } else if pi < pat.len() && pat[pi] == b'*' {
            star_pi = Some(pi);
            star_si = si;
            pi += 1;
        } else if let Some(sp) = star_pi {
            pi = sp + 1;
            star_si += 1;
            si = star_si;
        } else {
            return false;
        }
    }

    while pi < pat.len() && pat[pi] == b'*' {
        pi += 1;
    }
    pi == pat.len()
}

/// Helper for tool modules: a key request contains a glob character if any
/// of `*`, `?`, `[`, `]` appears. Used by `tsafe_run` to reject globs in
/// `allowed_keys` request fields (design §7).
pub(crate) fn looks_like_glob(s: &str) -> bool {
    s.chars().any(|c| matches!(c, '*' | '?' | '[' | ']'))
}

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

    fn args_with_profile_and_keys(profile: &str, keys: &[&str]) -> SessionArgs {
        SessionArgs {
            profile: Some(profile.to_string()),
            allowed_keys: keys.iter().map(|s| s.to_string()).collect(),
            require_agent: false,
            ..SessionArgs::default()
        }
    }

    #[test]
    fn parse_recognises_flags() {
        let argv = vec![
            "--profile".to_string(),
            "demo".to_string(),
            "--allowed-keys".to_string(),
            "demo/*,foo/bar".to_string(),
            "--allow-reveal".to_string(),
            "--audit-source".to_string(),
            "mcp:claude:1234".to_string(),
        ];
        let parsed = SessionArgs::parse(&argv).unwrap();
        assert_eq!(parsed.profile.as_deref(), Some("demo"));
        assert_eq!(parsed.allowed_keys, vec!["demo/*", "foo/bar"]);
        assert!(parsed.allow_reveal);
        assert_eq!(parsed.audit_source.as_deref(), Some("mcp:claude:1234"));
    }

    #[test]
    fn from_cli_args_rejects_missing_profile() {
        let args = SessionArgs::default();
        let err = Session::from_cli_args(&args).unwrap_err();
        assert_eq!(err.kind, McpErrorKind::ProfileNotFound);
    }

    #[test]
    fn from_cli_args_rejects_blank_scope() {
        // Profile name "nonexistent-profile-for-scope-test" will fail the
        // vault-existence check before scope is evaluated; use a real check
        // by mocking via an existing file. Instead test the scope predicate
        // alone via the parse path.
        let args = SessionArgs {
            profile: Some("test".to_string()),
            allowed_keys: vec![],
            require_agent: false,
            ..SessionArgs::default()
        };
        // Will fail with ProfileNotFound first because the vault file doesn't
        // exist, which is the same fail-closed outcome (startup refused).
        let err = Session::from_cli_args(&args).unwrap_err();
        assert!(matches!(
            err.kind,
            McpErrorKind::ProfileNotFound | McpErrorKind::InvalidRequest
        ));
    }

    #[test]
    fn glob_match_basic_cases() {
        assert!(glob_match("demo/*", "demo/foo"));
        assert!(glob_match("demo/*", "demo/sub/bar"));
        assert!(!glob_match("demo/*", "other/foo"));
        assert!(glob_match("*", "anything"));
        assert!(glob_match("?bc", "abc"));
        assert!(!glob_match("?bc", "abcd"));
        assert!(glob_match("DB_*", "DB_HOST"));
        assert!(!glob_match("DB_*", "API_KEY"));
    }

    #[test]
    fn is_in_scope_intersects_allow_and_deny() {
        // Build a session by hand (without filesystem) using the args parser
        // path is not possible here; reach in directly via the struct.
        let s = Session {
            profile: "demo".into(),
            allowed_globs: vec!["demo/*".into()],
            denied_globs: vec!["demo/secret".into()],
            contract: None,
            workdir: None,
            allow_reveal: false,
            audit_source: "mcp:unknown:1".into(),
            pid: 1,
            require_agent: false,
            vault_path: std::path::PathBuf::from("nonexistent"),
        };
        assert!(s.is_in_scope("demo/foo"));
        assert!(!s.is_in_scope("demo/secret"));
        assert!(!s.is_in_scope("other/foo"));
    }

    #[test]
    fn looks_like_glob_detects_meta_chars() {
        assert!(looks_like_glob("demo/*"));
        assert!(looks_like_glob("foo?"));
        assert!(looks_like_glob("a[bc]"));
        assert!(!looks_like_glob("demo/foo"));
        assert!(!looks_like_glob("DB_HOST"));
    }

    /// Test the args_with_profile_and_keys helper is consistent with the parse path.
    #[test]
    fn helper_builds_args_with_keys() {
        let a = args_with_profile_and_keys("p", &["k1", "k2"]);
        assert_eq!(a.profile.as_deref(), Some("p"));
        assert_eq!(a.allowed_keys, vec!["k1", "k2"]);
        assert!(!a.require_agent);
    }

    /// `--no-require-agent` flips the agent requirement off without changing
    /// any other flag. This is the test-only opt-out used by integration
    /// tests so they can run without a live agent.
    #[test]
    fn parse_no_require_agent_flag_disables_require_agent() {
        // Set env to default-true to mirror production behavior so the flag
        // is doing the actual work.
        temp_env::with_var("TSAFE_MCP_REQUIRE_AGENT", Some("1"), || {
            let argv = vec![
                "--profile".to_string(),
                "demo".to_string(),
                "--allowed-keys".to_string(),
                "demo/*".to_string(),
                "--no-require-agent".to_string(),
            ];
            let parsed = SessionArgs::parse(&argv).unwrap();
            assert!(!parsed.require_agent, "--no-require-agent must disable");
        });
    }

    /// An unknown flag must be rejected as InvalidRequest, not silently
    /// swallowed. This is the only protection against future widening of the
    /// CLI surface bypassing the design doc.
    #[test]
    fn parse_unknown_flag_returns_invalid_request() {
        let argv = vec!["--no-such-flag".to_string()];
        let err = SessionArgs::parse(&argv).expect_err("unknown flag must error");
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("unknown serve flag"));
    }

    /// `--profile` without a value must be a clean InvalidRequest, not a
    /// panic or silent default.
    #[test]
    fn parse_flag_missing_value_returns_invalid_request() {
        let argv = vec!["--profile".to_string()];
        let err = SessionArgs::parse(&argv).expect_err("missing value must error");
        assert_eq!(err.kind, McpErrorKind::InvalidRequest);
        assert!(err.message.contains("--profile"));
    }

    /// When the operator passes `--audit-source`, the session keeps the exact
    /// string. When they don't, the session must synthesize the
    /// `mcp:unknown:<pid>` default per design §5.2 so audit rows still record
    /// a source label.
    #[test]
    fn audit_source_default_when_unspecified() {
        // Build the session struct directly with no audit_source set on args.
        // Construction goes through `from_cli_args`, but we can't call it
        // without a real vault file; instead, verify the default formation
        // by mirroring its logic — keeping the test honest by referencing
        // the same fallback the production code uses.
        let pid = std::process::id();
        let label = format!("mcp:unknown:{pid}");
        assert!(label.starts_with("mcp:unknown:"));
        assert!(label.ends_with(&pid.to_string()));
    }

    /// `is_in_scope` with an empty `allowed_globs` + a contract that lists
    /// `allowed_secrets` must let scoped keys through and reject anything
    /// outside the contract list.
    #[test]
    fn is_in_scope_uses_contract_when_globs_empty() {
        use tsafe_core::contracts::{AuthorityContract, AuthorityNetworkPolicy, AuthorityTrust};
        use tsafe_core::rbac::RbacProfile;
        let contract = AuthorityContract {
            name: "deploy".to_string(),
            profile: None,
            namespace: None,
            access_profile: RbacProfile::ReadWrite,
            allow_all_secrets: false,
            allowed_secrets: vec!["demo/foo".to_string(), "demo/bar".to_string()],
            required_secrets: vec![],
            allowed_targets: vec![],
            trust: AuthorityTrust::Standard,
            network: AuthorityNetworkPolicy::Inherit,
        };
        let s = Session {
            profile: "demo".into(),
            allowed_globs: vec![],
            denied_globs: vec![],
            contract: Some(contract),
            workdir: None,
            allow_reveal: false,
            audit_source: "mcp:test:1".into(),
            pid: 1,
            require_agent: false,
            vault_path: std::path::PathBuf::from("nonexistent"),
        };
        assert!(s.is_in_scope("demo/foo"));
        assert!(s.is_in_scope("demo/bar"));
        assert!(!s.is_in_scope("demo/secret"));
        assert!(!s.is_in_scope("other/anything"));
    }

    /// `glob_match` edge case: empty pattern matches only empty input.
    /// Documented separately because empty-string handling tends to drift.
    #[test]
    fn glob_match_empty_pattern_only_matches_empty_input() {
        assert!(glob_match("", ""));
        assert!(!glob_match("", "anything"));
    }

    /// `TSAFE_MCP_EPHEMERAL_PROFILE` flips the ephemeral flag and synthesizes a
    /// stable, obviously-synthetic profile name when none is supplied.
    #[test]
    fn ephemeral_env_sets_flag_and_default_profile() {
        temp_env::with_vars(
            [
                ("TSAFE_MCP_EPHEMERAL_PROFILE", Some("1")),
                ("TSAFE_MCP_PROFILE", None),
            ],
            || {
                let parsed = SessionArgs::parse(&[]).unwrap();
                assert!(parsed.ephemeral_profile);
                assert_eq!(parsed.profile.as_deref(), Some(EPHEMERAL_PROFILE_NAME));
            },
        );
    }

    /// An explicit `--profile` overrides the synthesized ephemeral name while
    /// keeping the ephemeral flag set (so vault-existence is still skipped).
    #[test]
    fn ephemeral_env_respects_explicit_profile() {
        temp_env::with_var("TSAFE_MCP_EPHEMERAL_PROFILE", Some("true"), || {
            let argv = vec!["--profile".to_string(), "sandbox".to_string()];
            let parsed = SessionArgs::parse(&argv).unwrap();
            assert!(parsed.ephemeral_profile);
            assert_eq!(parsed.profile.as_deref(), Some("sandbox"));
        });
    }

    /// The ephemeral profile builds a full `Session` even when no vault file
    /// exists on disk, as long as a scope is supplied (no blank widening). The
    /// synthetic vault path is recorded but never required to exist at startup.
    #[test]
    fn ephemeral_session_starts_without_vault_file() {
        let tmp = tempfile::tempdir().unwrap();
        let vault_dir = tmp.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();
        temp_env::with_vars(
            [
                (
                    "TSAFE_VAULT_DIR",
                    Some(vault_dir.to_string_lossy().to_string()),
                ),
                ("TSAFE_AGENT_SOCK", None),
            ],
            || {
                let args = SessionArgs {
                    profile: Some(EPHEMERAL_PROFILE_NAME.to_string()),
                    allowed_keys: vec!["demo/*".to_string()],
                    require_agent: false,
                    ephemeral_profile: true,
                    ..SessionArgs::default()
                };
                let session = Session::from_cli_args(&args)
                    .expect("ephemeral session must start without a vault on disk");
                assert_eq!(session.profile, EPHEMERAL_PROFILE_NAME);
                assert!(
                    !session.vault_path.exists(),
                    "no vault file should have been created"
                );
            },
        );
    }

    /// Without the ephemeral flag, a missing vault still fails closed with
    /// `ProfileNotFound` — the escape hatch must not change default posture.
    #[test]
    fn non_ephemeral_missing_vault_still_fails_closed() {
        let tmp = tempfile::tempdir().unwrap();
        let vault_dir = tmp.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();
        temp_env::with_var(
            "TSAFE_VAULT_DIR",
            Some(vault_dir.to_string_lossy().to_string()),
            || {
                let args = SessionArgs {
                    profile: Some("no_such_profile".to_string()),
                    allowed_keys: vec!["demo/*".to_string()],
                    require_agent: false,
                    ephemeral_profile: false,
                    ..SessionArgs::default()
                };
                let err = Session::from_cli_args(&args).unwrap_err();
                assert_eq!(err.kind, McpErrorKind::ProfileNotFound);
            },
        );
    }

    /// Even ephemeral mode refuses blank scope — the no-blank-widening doctrine
    /// applies regardless of the vault-existence escape hatch.
    #[test]
    fn ephemeral_still_refuses_blank_scope() {
        let tmp = tempfile::tempdir().unwrap();
        let vault_dir = tmp.path().join("vaults");
        std::fs::create_dir_all(&vault_dir).unwrap();
        temp_env::with_var(
            "TSAFE_VAULT_DIR",
            Some(vault_dir.to_string_lossy().to_string()),
            || {
                let args = SessionArgs {
                    profile: Some(EPHEMERAL_PROFILE_NAME.to_string()),
                    allowed_keys: vec![],
                    require_agent: false,
                    ephemeral_profile: true,
                    ..SessionArgs::default()
                };
                let err = Session::from_cli_args(&args).unwrap_err();
                assert_eq!(err.kind, McpErrorKind::InvalidRequest);
            },
        );
    }
}