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
//! Where this server is running, and what it must not disrupt or destroy.
//!
//! tmux sets `TMUX` and `TMUX_PANE` in every process it starts, so an MCP
//! server launched from a pane can say which pane that is. Two things are
//! built on that: pane listings say which pane is the caller's own, pane input
//! refuses to reach it, and teardown tools refuse to destroy it.
//!
//! A pane id is only unique within one tmux server. `%1` on the socket this
//! process was started from and `%1` on the socket it was asked about are
//! different panes, so every comparison here weighs the socket as well.

use std::ffi::OsString;
use std::fmt;
use std::path::{Path, PathBuf};

use libtmux::ServerGeneration;

use serde::Serialize;

/// How a pane relates to the process answering the request.
///
/// Three values rather than a boolean, because "not the caller's pane" and
/// "there is no caller" are different answers and an agent acts differently on
/// each.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum Relation {
    /// This process is not running inside tmux, so no pane is its own.
    #[default]
    Unknown,
    /// Confirmed: the same tmux server, and the same pane.
    #[serde(rename = "self")]
    Own,
    /// Some other pane, or a pane this crate cannot prove is the caller's.
    Other,
}

/// The tmux pane hosting this process, as its environment describes it.
///
/// `TMUX` carries `socket_path,server_pid,session_number`; `TMUX_PANE` carries
/// the pane id. Either both variables form one complete identity or the
/// context is malformed; only two absent variables mean detached operation,
/// and an empty variable counts as absent.
#[derive(Clone, Eq, PartialEq)]
pub struct CallerIdentity {
    socket: Option<PathBuf>,
    server_pid: Option<u32>,
    session_id: Option<String>,
    pane_id: Option<String>,
    malformed: bool,
}

impl fmt::Debug for CallerIdentity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CallerIdentity")
            .field("socket", &self.socket.as_ref().map(|_| "<redacted>"))
            .field("server_pid", &self.server_pid)
            .field("session_id", &self.session_id)
            .field("pane_id", &self.pane_id)
            .field("malformed", &self.malformed)
            .finish()
    }
}

fn canonical_number(value: &str) -> Option<u64> {
    let parsed = value.parse::<u64>().ok()?;
    (parsed.to_string() == value).then_some(parsed)
}

fn canonical_pane_id(value: &str) -> bool {
    value
        .parse::<libtmux::PaneId>()
        .is_ok_and(|parsed| parsed.to_string() == value)
}

impl CallerIdentity {
    /// Read the identity from this process's environment.
    ///
    /// Returns `None` when neither variable is set, which is the ordinary case
    /// for a server started outside tmux.
    #[must_use]
    pub fn from_env() -> Option<Self> {
        Self::from_values(std::env::var_os("TMUX"), std::env::var_os("TMUX_PANE"))
    }

    /// Build an identity from explicit values, as the environment would give
    /// them.
    ///
    /// Separate from [`CallerIdentity::from_env`] so the parsing can be tested
    /// without a process-wide environment, which no test can hold alone.
    #[must_use]
    pub fn from_values(tmux: Option<OsString>, pane: Option<OsString>) -> Option<Self> {
        let tmux = tmux.filter(|value| !value.is_empty());
        let pane = pane.filter(|value| !value.is_empty());
        let detached = tmux.is_none() && pane.is_none();
        if detached {
            return None;
        }

        let parsed = tmux
            .and_then(|value| value.into_string().ok())
            .zip(pane.and_then(|value| value.into_string().ok()))
            .and_then(|(tmux, pane_id)| {
                let (socket, suffix) = tmux.rsplit_once(',')?;
                let (socket, server_pid) = socket.rsplit_once(',')?;
                let socket = PathBuf::from(socket);
                let server_pid = canonical_number(server_pid)
                    .and_then(|value| u32::try_from(value).ok())
                    .filter(|value| *value != 0)?;
                let session =
                    canonical_number(suffix).and_then(|value| u32::try_from(value).ok())?;
                if !socket.is_absolute()
                    || !crate::exec::route_path_is_terminal_safe(socket.as_os_str())
                    || !canonical_pane_id(&pane_id)
                {
                    return None;
                }
                Some((socket, server_pid, format!("${session}"), pane_id))
            });

        Some(match parsed {
            Some((socket, server_pid, session_id, pane_id)) => Self {
                socket: Some(socket),
                server_pid: Some(server_pid),
                session_id: Some(session_id),
                pane_id: Some(pane_id),
                malformed: false,
            },
            None => Self {
                socket: None,
                server_pid: None,
                session_id: None,
                pane_id: None,
                malformed: true,
            },
        })
    }

    /// Whether the variables were set but do not describe one tmux pane.
    ///
    /// Pane-input and teardown tools refuse every call while this holds,
    /// because they cannot rule out reaching the caller's own pane.
    #[must_use]
    pub const fn is_malformed(&self) -> bool {
        self.malformed
    }

    /// The pane this process runs in, when tmux named one.
    #[must_use]
    pub fn pane_id(&self) -> Option<&str> {
        self.pane_id.as_deref()
    }

    /// The socket path this process was started from, when tmux named one.
    #[must_use]
    pub fn socket(&self) -> Option<&Path> {
        self.socket.as_deref()
    }

    pub(crate) fn resolve_on<'a>(
        &'a self,
        server_socket: &Path,
        generation: ServerGeneration,
        panes: &[libtmux::Pane],
    ) -> Result<Option<&'a str>, &'static str> {
        if self.malformed {
            return Err("malformed");
        }
        let (Some(socket), Some(server_pid), Some(session_id), Some(pane_id)) = (
            self.socket.as_deref(),
            self.server_pid,
            self.session_id.as_deref(),
            self.pane_id.as_deref(),
        ) else {
            return Err("incomplete");
        };
        if !same_path(socket, server_socket) {
            return Ok(None);
        }
        if server_pid != generation.pid() {
            return Err("stale server process");
        }
        if !panes.iter().any(|pane| {
            pane.id().to_string() == pane_id && pane.session_id().to_string() == session_id
        }) {
            return Err("unresolved pane and session");
        }
        Ok(Some(pane_id))
    }

    /// Whether a pane on the given server is provably this process's own.
    ///
    /// Positive only on a confirmed socket match, because this drives an
    /// annotation an agent reads as fact. Anything less is [`Relation::Other`]:
    /// a bare pane-id match across two sockets is the false positive this
    /// whole module exists to avoid.
    #[must_use]
    pub fn relation_to(&self, pane_id: &str, server_socket: Option<&Path>) -> Relation {
        if self.malformed {
            return Relation::Other;
        }
        if self.pane_id.as_deref() != Some(pane_id) {
            return Relation::Other;
        }
        if same_socket(self.socket.as_deref(), server_socket) {
            Relation::Own
        } else {
            Relation::Other
        }
    }

    /// Whether this process might be running on the given server.
    ///
    /// Malformed context and an unreadable target socket remain protected.
    /// Complete identities on a different physical socket are foreign; a
    /// socket basename alone never authenticates a caller.
    #[must_use]
    pub fn may_be_on(&self, server_socket: Option<&Path>, _socket_name: Option<&str>) -> bool {
        if self.malformed {
            return true;
        }
        let Some(caller) = self.socket.as_deref() else {
            // No socket to compare. If tmux named a pane, assume it is here.
            return self.pane_id.is_some();
        };
        let Some(target) = server_socket else {
            return true;
        };
        if same_path(caller, target) {
            return true;
        }
        false
    }
}

/// Whether two socket paths name the same socket, when both are known.
fn same_socket(caller: Option<&Path>, target: Option<&Path>) -> bool {
    match (caller, target) {
        (Some(caller), Some(target)) => same_path(caller, target),
        _ => false,
    }
}

/// Compare physical endpoints, with exact paths as the unavailable fallback.
fn same_path(left: &Path, right: &Path) -> bool {
    crate::run_request::same_endpoint(left, right)
}

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::os::unix::ffi::OsStringExt as _;

    #[test]
    fn any_nonempty_caller_variable_is_not_detached() {
        for (tmux, pane) in [
            (Some(OsString::from("/tmp/socket,1,0")), None),
            (None, Some(OsString::from("%0"))),
            (Some(OsString::new()), Some(OsString::from("%0"))),
            (
                Some(OsString::from("/tmp/socket,not-a-pid,0")),
                Some(OsString::from("%0")),
            ),
        ] {
            let caller = CallerIdentity::from_values(tmux, pane)
                .expect("only two absent variables represent a detached caller");
            assert!(caller.malformed);
            assert!(caller.is_malformed());
        }
    }

    /// `TMUX= TMUX_PANE=` is how a shell un-nests tmux, and means the same as
    /// unsetting both.
    #[test]
    fn empty_caller_variables_are_detached() {
        for (tmux, pane) in [
            (Some(OsString::new()), Some(OsString::new())),
            (Some(OsString::new()), None),
            (None, Some(OsString::new())),
        ] {
            assert_eq!(CallerIdentity::from_values(tmux, pane), None);
        }
    }

    #[test]
    fn a_pane_without_a_socket_is_malformed() {
        let caller = CallerIdentity::from_values(None, Some(OsString::from("%3")))
            .expect("a present variable is not detached");
        assert!(caller.malformed);
        assert_eq!(caller.pane_id(), None);
    }

    use super::*;

    fn identity(tmux: &str, pane: &str) -> CallerIdentity {
        let caller = CallerIdentity::from_values(Some(tmux.into()), Some(pane.into()))
            .unwrap_or_else(|| unreachable!("both values are present"));
        assert!(!caller.malformed, "fixture identity is complete");
        caller
    }

    #[test]
    fn an_absent_environment_is_no_identity() {
        assert_eq!(CallerIdentity::from_values(None, None), None);
    }

    #[test]
    fn a_pane_without_tmux_is_not_usable_identity() {
        let caller = CallerIdentity::from_values(None, Some("%3".into()));
        let caller = caller.unwrap_or_else(|| unreachable!("a pane is present"));

        assert!(caller.malformed);
        assert_eq!(caller.pane_id(), None);
        assert_eq!(caller.socket(), None);
    }

    #[test]
    fn tmux_carries_socket_pid_and_session() {
        let caller = identity("/tmp/tmux-1000/a,comma,48188,10", "%3");

        assert_eq!(caller.socket(), Some(Path::new("/tmp/tmux-1000/a,comma")));
        assert_eq!(caller.server_pid, Some(48188));
        assert_eq!(caller.session_id.as_deref(), Some("$10"));
        assert_eq!(caller.pane_id(), Some("%3"));
    }

    #[test]
    fn caller_fields_require_the_exact_tmux_encoding() {
        for (tmux, pane) in [
            ("/tmp/socket,0,0", "%0"),
            ("/tmp/socket,01,0", "%0"),
            ("/tmp/socket,1,00", "%0"),
            ("/tmp/socket,1,$0", "%0"),
            ("/tmp/socket,1,4294967296", "%0"),
            ("/tmp/socket,1,0", "%00"),
            ("relative/socket,1,0", "%0"),
            ("/tmp/socket,1,0,extra", "%0"),
        ] {
            let caller = CallerIdentity::from_values(Some(tmux.into()), Some(pane.into()))
                .expect("present context");
            assert!(caller.malformed, "{tmux} {pane}");
        }
    }

    #[test]
    fn caller_socket_rejects_ascii_terminal_controls() {
        for byte in (0..=0x1f).chain([0x7f]) {
            let mut tmux = b"/tmp/socket-".to_vec();
            tmux.push(byte);
            tmux.extend_from_slice(b",1,0");
            let caller = CallerIdentity::from_values(
                Some(OsString::from_vec(tmux)),
                Some(OsString::from("%0")),
            )
            .expect("present context");
            assert!(caller.malformed, "byte {byte:#04x} was accepted");
        }
    }

    #[tokio::test]
    async fn caller_socket_hard_link_resolves_on_the_same_daemon() {
        let guard = libtmux::test::TestServer::builder()
            .start()
            .await
            .expect("tmux starts");
        let server = guard.server();
        let session = server
            .new_session("caller-hard-link")
            .await
            .expect("session starts");
        let pane = session.panes().await.expect("panes list").remove(0);
        let generation = server.generation().await.expect("server generation");
        let alias = server.socket_path().with_file_name("caller-hard-link.sock");
        std::fs::hard_link(server.socket_path(), &alias).expect("socket hard link is created");
        let caller = CallerIdentity::from_values(
            Some(
                format!(
                    "{},{},{}",
                    alias.display(),
                    generation.pid(),
                    session.id().as_ref().trim_start_matches('$')
                )
                .into(),
            ),
            Some(pane.id().as_ref().into()),
        )
        .expect("caller context is present");
        let panes = server.panes().await.expect("pane snapshot");

        assert_eq!(
            caller
                .resolve_on(server.socket_path(), generation, &panes)
                .expect("physical alias is authenticated"),
            Some(pane.id().as_ref())
        );
        std::fs::remove_file(&alias).expect("socket hard link is removed");
        guard.shutdown().await.expect("tmux fixture shuts down");
    }

    #[test]
    fn debug_surfaces_redact_the_socket_path() {
        let path = "/tmp/libtmux-rs-test/caller-debug.sock";
        let caller = identity(&format!("{path},48188,10"), "%3");
        let builder = crate::TmuxTools::builder(
            libtmux::Server::builder()
                .socket_path("/tmp/libtmux-rs-test/caller-target.sock")
                .build()
                .expect("an inert server builds"),
        )
        .caller(Some(caller.clone()));
        let surfaces = [
            format!("{caller:?}"),
            format!("{builder:?}"),
            format!("{:?}", builder.build()),
        ];

        for surface in surfaces {
            assert!(surface.contains("CallerIdentity"), "{surface}");
            assert!(!surface.contains(path), "{surface}");
        }
    }

    #[test]
    fn a_truncated_tmux_value_is_malformed() {
        let caller = CallerIdentity::from_values(Some("/tmp/sock".into()), Some("%1".into()))
            .expect("present context");

        assert!(caller.malformed);
        assert_eq!(caller.socket(), None);
    }

    #[test]
    fn extra_fields_make_the_context_malformed() {
        let caller =
            CallerIdentity::from_values(Some("/tmp/sock,1,1,extra".into()), Some("%1".into()))
                .expect("present context");

        assert!(caller.malformed);
        assert_eq!(caller.socket(), None);
    }

    #[test]
    fn the_same_pane_on_the_same_socket_is_the_callers_own() {
        let caller = identity("/tmp/sock,1,0", "%1");

        assert_eq!(
            caller.relation_to("%1", Some(Path::new("/tmp/sock"))),
            Relation::Own
        );
    }

    #[test]
    fn the_same_pane_id_on_another_socket_is_not() {
        let caller = identity("/tmp/sock-a,1,0", "%1");

        assert_eq!(
            caller.relation_to("%1", Some(Path::new("/tmp/sock-b"))),
            Relation::Other,
            "a pane id is only unique within one server"
        );
    }

    #[test]
    fn an_unprovable_socket_annotates_as_other() {
        let caller = CallerIdentity::from_values(None, Some("%1".into()));
        let caller = caller.unwrap_or_else(|| unreachable!("a pane is present"));

        assert_eq!(
            caller.relation_to("%1", Some(Path::new("/tmp/sock"))),
            Relation::Other,
            "the annotation states fact, so it declines what it cannot prove"
        );
    }

    #[test]
    fn a_different_pane_is_other() {
        let caller = identity("/tmp/sock,1,0", "%1");

        assert_eq!(
            caller.relation_to("%2", Some(Path::new("/tmp/sock"))),
            Relation::Other
        );
    }

    #[test]
    fn a_mangled_socket_is_no_evidence_rather_than_contrary_evidence() {
        // tmux writes an absolute path. Anything else reached this process
        // through something that damaged it, and reading it as "a different
        // server" would clear the way to killing the caller's own pane.
        for mangled in ["garbage-with-no-commas", "relative/path,1,0", "..,1,0"] {
            let caller = CallerIdentity::from_values(Some(mangled.into()), Some("%1".into()))
                .expect("present context");

            assert!(caller.malformed);
            assert_eq!(
                caller.socket(),
                None,
                "{mangled} should not parse as a socket"
            );
            assert!(
                caller.may_be_on(Some(Path::new("/tmp/tmux-1000/default")), Some("default")),
                "{mangled} must leave the guard cautious"
            );
            assert_eq!(
                caller.relation_to("%1", Some(Path::new("/tmp/tmux-1000/default"))),
                Relation::Other,
                "{mangled} proves nothing, so the annotation declines"
            );
        }
    }

    #[test]
    fn the_guard_blocks_what_the_annotation_declines() {
        let caller = CallerIdentity::from_values(None, Some("%1".into()));
        let caller = caller.unwrap_or_else(|| unreachable!("a pane is present"));

        assert!(
            caller.may_be_on(Some(Path::new("/tmp/sock")), Some("default")),
            "with no socket to compare, a kill must assume the worst"
        );
    }

    #[test]
    fn the_guard_blocks_when_the_target_socket_is_unreadable() {
        let caller = identity("/tmp/sock,1,0", "%1");

        assert!(caller.may_be_on(None, None));
    }

    #[test]
    fn the_guard_does_not_authenticate_a_basename_match() {
        let caller = identity("/private/tmp/tmux-1000/work,1,0", "%1");

        assert!(!caller.may_be_on(Some(Path::new("/tmp/tmux-1000/work")), Some("work")));
    }

    #[test]
    fn the_guard_clears_an_unrelated_server() {
        let caller = identity("/tmp/tmux-1000/default,1,0", "%1");

        assert!(
            !caller.may_be_on(Some(Path::new("/tmp/tmux-1000/other")), Some("other")),
            "a different socket by both path and name is a different server"
        );
    }
}