tmux-mcp 0.1.0-alpha.16

Model Context Protocol server exposing tmux through libtmux (alpha)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
use std::collections::BTreeSet;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::fmt;
use std::future::Future;
use std::sync::{Arc, OnceLock};
use std::time::Duration;

use libtmux::Server;
use rmcp::model::ErrorData;
use serde::{Deserialize, Serialize};

use crate::tail::Tails;
use crate::{CallerIdentity, TmuxTools, schema, tools};

/// The older Rust-specific safety setting, rejected rather than ignored.
pub const RETIRED_RUST_SAFETY_ENV: &str = "TMUX_MCP_SAFETY";

/// The unordered toolsets enabled for this process.
pub const TOOLSETS_ENV: &str = "LIBTMUX_TOOLSETS";

/// Individual tools added after toolset expansion.
pub const TOOLS_ENV: &str = "LIBTMUX_TOOLS";

/// Individual tools removed after every inclusion path.
pub const EXCLUDE_TOOLS_ENV: &str = "LIBTMUX_EXCLUDE_TOOLS";

/// The retired ordered-safety setting, rejected rather than ignored.
pub const RETIRED_SAFETY_ENV: &str = "LIBTMUX_SAFETY";

/// The tmux environment variables whose values tools may return.
pub const ENVIRONMENT_VALUES_ENV: &str = "LIBTMUX_ENVIRONMENT_VALUES";

/// The most names [`ENVIRONMENT_VALUES_ENV`] may allow.
const MAX_ENVIRONMENT_VALUES: usize = 32;

/// Parse the operator's allowed environment names.
///
/// Absent or empty allows none. A name is compared exactly, so `PATH` does
/// not allow `path`.
///
/// # Errors
///
/// Returns an error for an empty element, a name containing `=` or NUL, or
/// more than 32 names.
pub fn parse_environment_values(value: Option<&str>) -> Result<BTreeSet<String>, SurfaceError> {
    let names = parse_optional_names(value, ENVIRONMENT_VALUES_ENV)?;
    if let Some(name) = names.iter().find(|name| name.contains(['=', '\0'])) {
        return Err(SurfaceError::new(format!(
            "{ENVIRONMENT_VALUES_ENV} names {name:?}, which is not a variable name"
        )));
    }
    if names.len() > MAX_ENVIRONMENT_VALUES {
        return Err(SurfaceError::new(format!(
            "{ENVIRONMENT_VALUES_ENV} allows at most {MAX_ENVIRONMENT_VALUES} names"
        )));
    }
    Ok(names)
}

/// Read [`ENVIRONMENT_VALUES_ENV`] before serving MCP.
///
/// # Errors
///
/// Returns an error for invalid UTF-8 or any error
/// [`parse_environment_values`] reports.
pub fn environment_values_from_env() -> Result<BTreeSet<String>, SurfaceError> {
    parse_environment_values(unicode_env(ENVIRONMENT_VALUES_ENV)?.as_deref())
}

/// One mechanical group in the advertised MCP tool inventory.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum Toolset {
    /// Read tmux metadata, pane output, environment, or configuration.
    Inspect,
    /// Change tmux state without supplying executable input.
    Manage,
    /// Start configured processes or supply pane input and commands.
    Execute,
    /// Delete tmux state.
    Teardown,
}

impl Toolset {
    const ALL: [Self; 4] = [Self::Inspect, Self::Manage, Self::Execute, Self::Teardown];

    fn parse(name: &str) -> Option<Self> {
        match name {
            "inspect" => Some(Self::Inspect),
            "manage" => Some(Self::Manage),
            "execute" => Some(Self::Execute),
            "teardown" => Some(Self::Teardown),
            _ => None,
        }
    }

    /// The name used in environment selections and capability reports.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Inspect => "inspect",
            Self::Manage => "manage",
            Self::Execute => "execute",
            Self::Teardown => "teardown",
        }
    }
}

/// The startup-frozen request for one MCP tool surface.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Selection {
    toolsets: Vec<Toolset>,
    include: BTreeSet<String>,
    exclude: BTreeSet<String>,
}

impl Selection {
    /// Parse the three list settings before any tmux connection is opened.
    ///
    /// # Errors
    ///
    /// Returns an error for empty tokens or unknown tool and toolset names.
    pub fn parse(
        toolsets: Option<&str>,
        include: Option<&str>,
        exclude: Option<&str>,
    ) -> Result<Self, SurfaceError> {
        Self::parse_for_socket(toolsets, include, exclude, false)
    }

    /// Parse a selection while applying the selected socket's provenance.
    ///
    /// # Errors
    ///
    /// Returns an error for empty tokens or unknown tool and toolset names.
    pub fn parse_for_socket(
        toolsets: Option<&str>,
        include: Option<&str>,
        exclude: Option<&str>,
        default_teardown: bool,
    ) -> Result<Self, SurfaceError> {
        let toolsets = match toolsets {
            None if default_teardown => Toolset::ALL.to_vec(),
            None => vec![Toolset::Inspect, Toolset::Manage, Toolset::Execute],
            Some("") => Vec::new(),
            Some(value) => parse_names(value, "LIBTMUX_TOOLSETS")?
                .into_iter()
                .map(|name| {
                    Toolset::parse(&name).ok_or_else(|| {
                        SurfaceError::new(format!(
                            "unknown toolset {name:?}; expected inspect, manage, execute, or teardown"
                        ))
                    })
                })
                .collect::<Result<BTreeSet<_>, _>>()?
                .into_iter()
                .collect(),
        };
        Ok(Self {
            toolsets,
            include: parse_optional_names(include, "LIBTMUX_TOOLS")?,
            exclude: parse_optional_names(exclude, "LIBTMUX_EXCLUDE_TOOLS")?,
        })
    }

    /// Read and validate the process-wide selection before serving MCP.
    ///
    /// # Errors
    ///
    /// Returns an error for invalid UTF-8, malformed selections, or retired settings.
    pub fn from_env(default_teardown: bool) -> Result<Self, SurfaceError> {
        for retired in [RETIRED_SAFETY_ENV, RETIRED_RUST_SAFETY_ENV] {
            if std::env::var_os(retired).is_some() {
                return Err(SurfaceError::new(format!(
                    "{retired} has been removed; use {TOOLSETS_ENV}"
                )));
            }
        }
        let toolsets = unicode_env(TOOLSETS_ENV)?;
        let include = unicode_env(TOOLS_ENV)?;
        let exclude = unicode_env(EXCLUDE_TOOLS_ENV)?;
        Self::parse_for_socket(
            toolsets.as_deref(),
            include.as_deref(),
            exclude.as_deref(),
            default_teardown,
        )
    }

    /// The startup-frozen toolsets in deterministic order.
    #[must_use]
    pub fn toolsets(&self) -> &[Toolset] {
        &self.toolsets
    }

    pub(super) fn includes(&self, name: &str) -> bool {
        self.include.contains(name)
    }

    pub(super) fn excludes(&self, name: &str) -> bool {
        self.exclude.contains(name)
    }

    pub(super) fn included_names(&self) -> &BTreeSet<String> {
        &self.include
    }

    pub(super) fn excluded_names(&self) -> &BTreeSet<String> {
        &self.exclude
    }
}

fn unicode_env(name: &'static str) -> Result<Option<String>, SurfaceError> {
    match std::env::var(name) {
        Ok(value) => Ok(Some(value)),
        Err(std::env::VarError::NotPresent) => Ok(None),
        Err(std::env::VarError::NotUnicode(value)) => Err(non_unicode(name, value)),
    }
}

fn non_unicode(name: &'static str, _value: OsString) -> SurfaceError {
    SurfaceError::new(format!("{name} must be valid UTF-8"))
}

fn parse_optional_names(
    value: Option<&str>,
    variable: &'static str,
) -> Result<BTreeSet<String>, SurfaceError> {
    match value {
        None | Some("") => Ok(BTreeSet::new()),
        Some(value) => Ok(parse_names(value, variable)?.into_iter().collect()),
    }
}

fn parse_names(value: &str, variable: &'static str) -> Result<Vec<String>, SurfaceError> {
    value
        .split(',')
        .map(|raw| {
            let name = raw.trim();
            if name.is_empty() {
                Err(SurfaceError::new(format!(
                    "{variable} contains an empty name"
                )))
            } else {
                Ok(name.to_owned())
            }
        })
        .collect()
}

/// A startup configuration or manifest error.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SurfaceError(String);

impl SurfaceError {
    pub(crate) fn new(message: impl Into<String>) -> Self {
        Self(message.into())
    }
}

impl fmt::Display for SurfaceError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl std::error::Error for SurfaceError {}

/// What startup can honestly claim about the selected tmux daemon.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum SocketProvenance {
    /// A product socket this process can create with minimal configuration.
    DedicatedMinimal,
    /// The product socket already existed, so its configuration is unknown.
    DedicatedExisting,
    /// The operator selected a socket, whose daemon configuration is unknown.
    OperatorSelected,
    /// The operator selected a socket where no daemon answered at startup.
    OperatorSelectedAbsent,
    /// The operator selected an explicit tmux configuration for an absent daemon.
    UserConfigured,
    /// A daemon already answered, so an explicit config was not its provenance.
    UserConfiguredExisting,
    /// A programmatic builder did not provide provenance.
    #[default]
    Unknown,
}

impl SocketProvenance {
    /// Whether absent toolset configuration may include teardown.
    #[must_use]
    pub const fn defaults_to_teardown(self) -> bool {
        matches!(self, Self::DedicatedMinimal)
    }

    fn report(self, server: &Server) -> crate::manifest::SocketReport {
        let selector = server.socket_name().map_or_else(
            || format!("path:{}", server.socket_path().display()),
            |name| format!("name:{}", name.to_string_lossy()),
        );
        let (selection_provenance, server_state, configuration_provenance) = match self {
            Self::DedicatedMinimal => ("default-dedicated", "created", "minimal"),
            Self::DedicatedExisting => ("default-dedicated", "existing", "unknown"),
            Self::OperatorSelected | Self::UserConfiguredExisting => {
                ("operator-current", "existing", "unknown")
            }
            Self::OperatorSelectedAbsent => ("operator-current", "absent", "unknown"),
            Self::UserConfigured => ("operator-current", "absent", "user-configured"),
            Self::Unknown => ("unknown", "unknown", "unknown"),
        };
        crate::manifest::SocketReport {
            selector,
            selection_provenance,
            server_state,
            configuration_provenance,
            namespace_boundary: "tmux-objects-only",
        }
    }
}

fn shell_quote(value: &OsStr) -> String {
    let value = value.to_string_lossy();
    format!("'{}'", value.replace('\'', "'\"'\"'"))
}

fn connection_report(
    socket: &crate::manifest::SocketReport,
    server: &Server,
) -> crate::manifest::ConnectionReport {
    let path = server.socket_path().as_os_str();
    crate::manifest::ConnectionReport {
        socket_selector: socket.selector.clone(),
        socket_provenance: socket.selection_provenance,
        resolved_socket_path: server.socket_path().to_string_lossy().into_owned(),
        server_state: socket.server_state,
        configuration_provenance: socket.configuration_provenance,
        attach_command: format!(
            "{} -N -S {} attach",
            shell_quote(server.tmux_executable()),
            shell_quote(path),
        ),
    }
}

/// Assembles a [`TmuxTools`] with the parts the environment usually supplies.
#[derive(Debug)]
pub struct Builder {
    server: Server,
    caller: Option<CallerIdentity>,
    selection: Selection,
    socket_provenance: SocketProvenance,
    environment_values: BTreeSet<String>,
}

impl Builder {
    /// Allow tools to return the values of these tmux environment variables.
    ///
    /// None are allowed by default: `show_environment` reports names and
    /// state, and `get_tmux_variables` refuses a name the environment holds.
    /// A tmux server inherits the environment of the shell that started it,
    /// so its values are the user's tokens and keys.
    #[must_use]
    pub fn environment_values(mut self, names: BTreeSet<String>) -> Self {
        self.environment_values = names;
        self
    }

    /// Say where this process is running, rather than reading the environment.
    #[must_use]
    pub fn caller(mut self, caller: Option<CallerIdentity>) -> Self {
        self.caller = caller;
        self
    }

    /// Choose the startup-frozen unordered tool surface.
    #[must_use]
    pub fn selection(mut self, selection: Selection) -> Self {
        self.selection = selection;
        self
    }

    /// Record only the socket/configuration provenance startup established.
    #[must_use]
    pub const fn socket_provenance(mut self, provenance: SocketProvenance) -> Self {
        self.socket_provenance = provenance;
        self
    }

    /// Build the server with its startup-frozen tool selection.
    ///
    /// # Panics
    ///
    /// Panics if native tool metadata violates the capability contract.
    #[must_use]
    #[allow(
        clippy::expect_used,
        reason = "build preserves the existing infallible constructor contract"
    )]
    pub fn build(self) -> TmuxTools {
        self.try_build()
            .expect("native tool routes and the requested surface are valid")
    }

    /// Build the server after validating every named tool against the manifest.
    ///
    /// # Errors
    ///
    /// Returns an error if the native routes or requested selection are invalid.
    pub fn try_build(self) -> Result<TmuxTools, SurfaceError> {
        let identity = Arc::new(crate::identity::InstanceIdentity::new());
        let mut router = tools::router();
        for route in router.map.values_mut() {
            schema::strip_unknown_formats(Arc::make_mut(&mut route.attr.input_schema));
            if let Some(schema) = route.attr.output_schema.as_mut() {
                schema::strip_unknown_formats(Arc::make_mut(schema));
            }
        }
        let mut resolved = crate::manifest::resolve(router, &self.selection)?;
        let socket = self.socket_provenance.report(&self.server);
        resolved.report.connection = connection_report(&socket, &self.server);
        resolved.report.socket = socket;
        let router = resolved.router;
        Ok(TmuxTools {
            server: Arc::new(self.server),
            caller: self.caller.map(Arc::new),
            capability_report: Arc::new(resolved.report),
            socket: Arc::new(OnceLock::new()),
            tails: Arc::new(Tails::new(identity)),
            echoes: Arc::new(crate::echo::PaneEchoes::new()),
            tool_router: router,
            nested_tool_router: resolved.nested_router,
            environment_values: Arc::new(self.environment_values),
        })
    }
}

/// Reports how a long call is getting on, when the client asked to be told.
///
/// MCP sends progress only to a request that carried a `progressToken`, so a
/// client that did not ask pays nothing: there is no token, and the notifier
/// does not exist. Without this a sixty-second wait is indistinguishable from
/// a server that has stopped answering.
#[derive(Clone, Debug)]
struct Progress {
    peer: rmcp::service::Peer<rmcp::RoleServer>,
    token: rmcp::model::ProgressToken,
}

/// Whoever asked to be told how a long call is getting on.
///
/// Extracted from the request rather than passed, so a tool declares that it
/// reports progress by taking one. It is empty unless the client sent a
/// progress token, and an empty one can be built directly -- which is what
/// lets these tools be driven without a live client.
#[derive(Clone, Debug, Default)]
pub struct Reporter(Option<Progress>);

impl Reporter {
    /// A reporter with nobody to report to.
    #[must_use]
    pub const fn none() -> Self {
        Self(None)
    }
}

impl<C> rmcp::handler::server::common::FromContextPart<C> for Reporter
where
    C: rmcp::handler::server::common::AsRequestContext,
{
    fn from_context_part(context: &mut C) -> Result<Self, ErrorData> {
        let context = context.as_request_context();
        Ok(Self(context.meta.get_progress_token().map(|token| {
            Progress {
                peer: context.peer.clone(),
                token,
            }
        })))
    }
}

impl Progress {
    /// Say what is happening now.
    ///
    /// `so_far` is seconds elapsed, because the protocol asks for a number
    /// that rises every time and a wait has no other measure of its own
    /// progress: it does not know how long it will take.
    ///
    /// Best-effort: a client that has gone away is the caller's problem to
    /// notice through its own request, not this notification's to report.
    async fn say(&self, so_far: f64, message: impl Into<String>) {
        let mut param = rmcp::model::ProgressNotificationParam::new(self.token.clone(), so_far);
        param.message = Some(message.into());
        let _ = self.peer.notify_progress(param).await;
    }
}

/// Report progress every so often while a future runs.
///
/// Wraps rather than threads a reporter through each primitive: the useful
/// thing to say about a wait is that it is still waiting, and how long for,
/// which needs nothing from inside it.
pub(super) async fn reporting<T>(
    reporter: Reporter,
    what: &str,
    work: impl Future<Output = T>,
) -> T {
    let Some(progress) = reporter.0 else {
        return work.await;
    };

    let began = tokio::time::Instant::now();
    let ticker = async {
        let mut every = tokio::time::interval(PROGRESS_EVERY);
        // The first tick is immediate, and "0 seconds in" says nothing.
        every.tick().await;
        loop {
            every.tick().await;
            let elapsed = began.elapsed().as_secs();
            progress
                .say(
                    f64::from(u32::try_from(elapsed).unwrap_or(u32::MAX)),
                    format!("{what}, {elapsed}s so far"),
                )
                .await;
        }
    };

    tokio::select! {
        outcome = work => outcome,
        () = ticker => unreachable!("the ticker loops forever"),
    }
}

/// How often a long call says it is still going.
const PROGRESS_EVERY: Duration = Duration::from_secs(5);

impl TmuxTools {
    /// Expose one tmux server, locating this process within it.
    #[must_use]
    pub fn new(server: Server) -> Self {
        Self::builder(server).build()
    }

    /// Expose one tmux server, saying explicitly where this process is and how
    /// much of the surface it may use.
    ///
    /// The environment is process-wide, so a test that needs a caller or a
    /// selection cannot set one without disturbing every other test. This is how it
    /// says so instead.
    #[must_use]
    pub fn builder(server: Server) -> Builder {
        Builder {
            server,
            caller: CallerIdentity::from_env(),
            selection: Selection {
                toolsets: vec![Toolset::Inspect, Toolset::Manage, Toolset::Execute],
                include: BTreeSet::new(),
                exclude: BTreeSet::new(),
            },
            socket_provenance: SocketProvenance::Unknown,
            environment_values: BTreeSet::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Selection, Toolset};
    use crate::manifest::{OutputClass, ProcessReach, TmuxEffect};
    use std::collections::BTreeSet;

    #[test]
    fn toolset_selection_distinguishes_empty_from_empty_tokens() {
        let empty = Selection::parse(Some(""), None, None).expect("empty surface");
        assert!(empty.toolsets().is_empty());

        let inspect = Selection::parse(Some("inspect"), None, None).expect("one toolset");
        assert_eq!(inspect.toolsets(), &[Toolset::Inspect]);

        for malformed in [",inspect", "inspect,", "inspect,,manage"] {
            let error = Selection::parse(Some(malformed), None, None).expect_err("empty token");
            assert!(error.to_string().contains("empty"), "{malformed}: {error}");
        }
    }

    #[test]
    fn registered_routes_are_the_capability_manifest() {
        let selection =
            Selection::parse_for_socket(None, None, None, true).expect("dedicated minimal surface");
        let resolved = crate::manifest::resolve(crate::tools::router(), &selection)
            .expect("complete manifest");
        let listed = resolved.router.list_all();
        let reported: Vec<_> = resolved
            .report
            .tools
            .iter()
            .map(|tool| tool.name.as_str())
            .collect();
        let names: Vec<_> = listed.iter().map(|tool| tool.name.as_ref()).collect();

        assert_eq!(names, reported);
        assert!(listed.iter().all(|tool| {
            let description = tool.description.as_deref().expect("description");
            resolved
                .report
                .tools
                .iter()
                .any(|row| row.name == tool.name && description.ends_with(row.controlled_opener()))
        }));
    }

    /// A caller that reads only up to a tool's first sentence -- a common
    /// truncation or summary strategy -- must still be able to tell tools
    /// apart.
    ///
    /// `finish_route` used to prepend the coarse, capability-keyed safety
    /// sentence before a tool's own description; several tools sharing a
    /// `(toolset, process_reach, output_classes)` bucket then shared the
    /// byte-identical opener.
    #[test]
    fn every_tools_first_sentence_is_distinct() {
        let selection =
            Selection::parse_for_socket(None, None, None, true).expect("dedicated minimal surface");
        let resolved = crate::manifest::resolve(crate::tools::router(), &selection)
            .expect("complete manifest");

        let listed = resolved.router.list_all();
        let mut by_first_sentence: std::collections::HashMap<&str, Vec<&str>> =
            std::collections::HashMap::new();
        for tool in &listed {
            let description = tool.description.as_deref().expect("description");
            let first_sentence = description.split(". ").next().unwrap_or(description);
            by_first_sentence
                .entry(first_sentence)
                .or_default()
                .push(tool.name.as_ref());
        }
        let collisions: Vec<_> = by_first_sentence
            .into_iter()
            .filter(|(_, names)| names.len() > 1)
            .collect();
        assert!(
            collisions.is_empty(),
            "tools sharing a first sentence, indistinguishable by a caller that reads only that \
             far: {collisions:?}",
        );
    }

    /// The generated safety sentence follows a tool's own text, so a summary
    /// with no closing period ran into it: "List every tmux session on the
    /// server Inspect tmux metadata; ...".
    #[test]
    fn every_tools_own_description_ends_its_sentence() {
        let unfinished: Vec<_> = crate::tools::router()
            .list_all()
            .into_iter()
            .filter(|tool| {
                !tool
                    .description
                    .as_deref()
                    .unwrap_or_default()
                    .trim_end()
                    .ends_with(['.', '!', '?'])
            })
            .map(|tool| tool.name.into_owned())
            .collect();

        assert!(unfinished.is_empty(), "no closing period: {unfinished:?}");
    }

    /// Clients auto-approve or prompt from these hints, so a tool that
    /// changes tmux must never claim to be read-only.
    #[test]
    fn annotations_follow_each_tools_capability_row() {
        let selection = Selection::parse(Some("inspect,manage,execute,teardown"), None, None)
            .expect("selection");
        let resolved = crate::manifest::resolve(crate::tools::router(), &selection)
            .expect("complete manifest");
        let mut distinct = BTreeSet::new();
        let mut destructive_tools = BTreeSet::new();

        for tool in resolved.router.list_all() {
            let row = &resolved
                .report
                .tools
                .iter()
                .find(|row| row.name == tool.name)
                .expect("report row")
                .capability;
            let hints = tool.annotations.as_ref().expect("annotations");
            let read_only = hints.read_only_hint.expect("readOnlyHint");
            let destructive = hints.destructive_hint.expect("destructiveHint");
            let changes_tmux = row.toolset != Toolset::Inspect
                || row.process_reach != ProcessReach::None
                || row
                    .tmux_effects
                    .iter()
                    .any(|effect| *effect != TmuxEffect::Observe);
            let can_destroy = row.tmux_effects.contains(&TmuxEffect::Delete)
                || matches!(
                    row.process_reach,
                    ProcessReach::PaneInput | ProcessReach::PaneCommand
                );

            assert_eq!(read_only, !changes_tmux, "{} readOnlyHint", tool.name);
            assert_eq!(destructive, can_destroy, "{} destructiveHint", tool.name);
            if destructive {
                destructive_tools.insert(tool.name.to_string());
            }
            distinct.insert((
                read_only,
                destructive,
                hints.idempotent_hint.expect("idempotentHint"),
                hints.open_world_hint.expect("openWorldHint"),
            ));
        }
        assert!(distinct.len() > 3, "hints barely vary: {distinct:?}");
        // tmux 3.7 applies a lowered history limit to existing panes,
        // discarding their scrollback.
        assert!(destructive_tools.contains("set_history_limit"));
    }

    #[test]
    fn configured_value_reads_disclose_configured_command_output() {
        let selection = Selection::parse(Some("inspect"), None, None).expect("selection");
        let resolved = crate::manifest::resolve(crate::tools::router(), &selection)
            .expect("complete manifest");

        for name in ["get_tmux_variables", "show_option"] {
            let tool = resolved
                .report
                .tools
                .iter()
                .find(|tool| tool.name == name)
                .expect("tool row");
            assert_eq!(
                tool.capability.output_classes,
                [OutputClass::TmuxMetadata, OutputClass::ConfiguredCommand]
                    .into_iter()
                    .collect(),
                "{name}",
            );
            assert!(
                tool.controlled_opener()
                    .starts_with("Read configured tmux commands;")
            );
        }
    }

    #[test]
    fn synchronize_panes_is_the_only_declared_input_amplifier() {
        let selection = Selection::parse(Some("inspect,manage,execute,teardown"), None, None)
            .expect("selection");
        let resolved = crate::manifest::resolve(crate::tools::router(), &selection)
            .expect("complete manifest");
        let report = serde_json::to_value(resolved.report).expect("report serializes");
        let tools = report["tools"].as_array().expect("tool rows");

        assert!(
            tools
                .iter()
                .all(|tool| tool["amplifiesFutureInput"].is_boolean()),
            "every manifest row carries the amplification fact"
        );
        let amplified: Vec<_> = tools
            .iter()
            .filter(|tool| tool["amplifiesFutureInput"] == true)
            .map(|tool| tool["name"].as_str().expect("tool name"))
            .collect();
        assert_eq!(amplified, ["set_synchronize_panes"]);
        let synchronize = resolved
            .router
            .list_all()
            .into_iter()
            .find(|tool| tool.name == "set_synchronize_panes")
            .expect("synchronize route");
        let description = synchronize.description.as_deref().expect("description");
        for claim in ["window default", "Individual pane overrides", "can amplify"] {
            assert!(description.contains(claim), "missing {claim:?}");
        }
    }

    #[test]
    fn unknown_provenance_defaults_without_teardown() {
        let selection = Selection::parse(None, None, None).expect("conservative default");
        assert_eq!(
            selection.toolsets(),
            &[Toolset::Inspect, Toolset::Manage, Toolset::Execute]
        );
    }

    #[test]
    fn spawn_routes_accept_no_command_or_environment_payload() {
        let router = crate::tools::router();
        for name in [
            "create_session",
            "create_window",
            "split_window",
            "respawn_pane",
        ] {
            let schema = &router.get(name).expect("spawn route").input_schema;
            let keys: BTreeSet<_> = schema
                .get("properties")
                .and_then(serde_json::Value::as_object)
                .expect("object schema")
                .keys()
                .map(String::as_str)
                .collect();
            assert!(!keys.contains("command"), "{name}");
            assert!(!keys.contains("environment"), "{name}");
            assert!(!keys.contains("env"), "{name}");
        }
    }

    #[test]
    fn exclusion_removes_aggregate_nested_authority() {
        let selection =
            Selection::parse(Some("inspect"), None, Some("capture_pane")).expect("selection");
        let resolved =
            crate::manifest::resolve(crate::tools::router(), &selection).expect("resolved surface");
        let batch = resolved
            .report
            .tools
            .iter()
            .find(|tool| tool.name == "call_read_tools_batch")
            .expect("batch route");

        assert!(!batch.capability.nested_authority.contains("capture_pane"));
    }

    #[test]
    fn read_batch_covers_every_non_self_bounded_inspect_route() {
        let selection = Selection::parse(Some("inspect"), None, None).expect("selection");
        let resolved =
            crate::manifest::resolve(crate::tools::router(), &selection).expect("resolved surface");
        let expected: BTreeSet<_> = resolved
            .report
            .tools
            .iter()
            .filter(|tool| {
                tool.capability.toolset == Toolset::Inspect
                    && tool.name != "call_read_tools_batch"
                    && tool.name != "wait_for_text"
            })
            .map(|tool| tool.name.clone())
            .collect();
        let batch = resolved
            .report
            .tools
            .iter()
            .find(|tool| tool.name == "call_read_tools_batch")
            .expect("batch route");

        assert_eq!(batch.capability.nested_authority, expected);
        let description = resolved
            .router
            .list_all()
            .into_iter()
            .find(|tool| tool.name == "call_read_tools_batch")
            .and_then(|tool| tool.description.map(std::borrow::Cow::into_owned))
            .expect("batch description");
        assert!(
            description.contains("inner tools do not receive separate client approval"),
            "{description}"
        );
    }
}