tailscale-mcp 1.2.1

MCP server for Tailscale: the local node through the CLI, the tailnet through the control-plane API
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
//! Running a local command and reading its failure.
//!
//! The interesting part is the reading. `tailscale` reports everything through
//! a non-zero exit code and a line of English on standard error, so this is
//! where that line becomes one of the error codes an agent can act on. Getting
//! it wrong is not cosmetic: `needs_operator` tells the caller to run one
//! command and try again, while `unsupported_version` tells it to stop asking.

use std::collections::HashMap;
use std::net::IpAddr;

use tailscale_cli::{ExecError, Invocation, Output};

use crate::context::{SelfIdentity, ToolContext};
use crate::error::{ToolError, ToolResult};
use crate::meta::ToolMeta;
use crate::version::{Version, satisfies};

/// Run a command, and turn anything other than a clean exit into a tool error.
pub async fn run(ctx: &ToolContext, meta: &ToolMeta, invocation: Invocation) -> ToolResult<Output> {
    let display = displayed(ctx, &invocation);
    let output = ctx
        .local
        .run(invocation)
        .await
        .map_err(|e| exec_error(ctx, &display, e))?;
    if output.success() {
        return Ok(output);
    }
    Err(command_failure(ctx, meta, &display, &output))
}

/// Run a command whose refusal may be an ordinary answer.
///
/// Several `tailscale` commands report an unremarkable fact about the tailnet
/// through a non-zero exit: `exit-node list` when there are no exit nodes,
/// `routecheck` when no report has been produced yet, `wait` when the timeout
/// passed, `status` when the backend is not running. Reporting those as tool
/// failures would tell a caller that its call went wrong when what it learnt is
/// exactly what it asked for.
///
/// What stays a failure is everything that is not an answer about the tailnet:
/// a binary that is not there, a subcommand it does not know, a refusal to talk
/// to us at all. The caller reads [`Output::success`] for the rest.
pub async fn run_tolerant(
    ctx: &ToolContext,
    meta: &ToolMeta,
    invocation: Invocation,
) -> ToolResult<Output> {
    let display = displayed(ctx, &invocation);
    let output = ctx
        .local
        .run(invocation)
        .await
        .map_err(|e| exec_error(ctx, &display, e))?;
    if output.success() {
        return Ok(output);
    }
    let stderr = ctx.redactor.apply(&output.stderr);
    if is_unrecognised(&stderr) {
        return Err(version_error(ctx, meta));
    }
    if needs_operator(&stderr) {
        return Err(ToolError::needs_operator(&stderr));
    }
    // Deliberately not `is_not_found`: "no exit nodes found" is the answer
    // these commands exist to give.
    Ok(output)
}

/// Run a command and hand back its standard output as text, failures aside.
pub async fn run_text(
    ctx: &ToolContext,
    meta: &ToolMeta,
    invocation: Invocation,
) -> ToolResult<String> {
    let output = run(ctx, meta, invocation).await?;
    Ok(output.stdout_str().into_owned())
}

/// The command line as it may be shown: what ran, with any secret in it gone.
///
/// [`Invocation::display`] is the argument list verbatim, which every typed
/// tool could show as it stands, because the server assembled those arguments
/// itself and knows an auth key only ever reaches the CLI through a file. The
/// passthrough has no such assurance: its arguments are the caller's, so a
/// command line that turns into an error message, a log line or a report goes
/// through here first. It is `pub(crate)` for the last of those: the
/// passthrough puts the command in what it answers with, and a second spelling
/// of this expression is a second place to forget it.
pub(crate) fn displayed(ctx: &ToolContext, invocation: &Invocation) -> String {
    ctx.redactor.apply(&invocation.display()).into_owned()
}

/// Something went wrong before the command produced a result.
///
/// Every message here goes through the session's redactor, not just the
/// shape-based pass [`ToolError::new`] applies for itself. `ExecError::Io`
/// names the command it was talking to, and since the passthrough that command
/// line is the caller's; the rest are redacted too so that the next variant
/// added does not have to be judged for whether it carries one.
fn exec_error(ctx: &ToolContext, display: &str, error: ExecError) -> ToolError {
    let told = |error: &ExecError| ctx.redactor.apply(&error.to_string()).into_owned();
    match error {
        ExecError::BinaryNotFound { .. }
        | ExecError::BinaryNotExecutable { .. }
        | ExecError::Spawn { .. } => {
            ToolError::backend_unavailable("the local surface", &told(&error))
        }
        ExecError::Timeout {
            timeout, printed, ..
        } => ToolError::timeout(display, timeout.as_secs(), &ctx.redactor.apply(&printed)),
        ExecError::Io { .. } | ExecError::SecretFile(_) => {
            ToolError::new(crate::error::ErrorCode::CliFailed, told(&error))
        }
    }
}

/// The command ran and refused. Work out what kind of refusal it was.
pub fn command_failure(
    ctx: &ToolContext,
    meta: &ToolMeta,
    display: &str,
    output: &Output,
) -> ToolError {
    let stderr = ctx.redactor.apply(&output.stderr);
    if is_unrecognised(&stderr) {
        return version_error(ctx, meta);
    }
    if needs_operator(&stderr) {
        return ToolError::needs_operator(&stderr);
    }
    if is_not_found(&stderr) {
        return ToolError::not_found(stderr.trim());
    }
    ToolError::cli_failed(display, output.exit_code, &stderr)
}

/// The binary does not know this subcommand or flag.
///
/// Matched on Go's `flag` package wording and the CLI's own dispatch, both of
/// which are stable across the releases this server supports.
fn is_unrecognised(stderr: &str) -> bool {
    const MARKERS: &[&str] = &[
        "flag provided but not defined",
        "unknown flag",
        "unknown subcommand",
        "unknown command",
        "is not a tailscale command",
        "unrecognized command",
    ];
    let lowered = stderr.to_ascii_lowercase();
    MARKERS.iter().any(|m| lowered.contains(m))
}

/// The command exists but this user may not run it.
fn needs_operator(stderr: &str) -> bool {
    const MARKERS: &[&str] = &[
        "access denied",
        "operator",
        "must be run as root",
        "permission denied",
        "you must be root",
    ];
    let lowered = stderr.to_ascii_lowercase();
    MARKERS.iter().any(|m| lowered.contains(m))
}

/// The command ran but its target is not there.
fn is_not_found(stderr: &str) -> bool {
    const MARKERS: &[&str] = &["no such", "not found", "does not exist", "unknown peer"];
    let lowered = stderr.to_ascii_lowercase();
    MARKERS.iter().any(|m| lowered.contains(m))
}

/// Report an unrecognised command as a version problem.
///
/// The minimum comes from the tool's own row when it has one. When it does not
/// — the command predates our floor and should have been there — the floor is
/// the honest answer: something older than anything we model is running.
fn version_error(ctx: &ToolContext, meta: &ToolMeta) -> ToolError {
    let needs = meta
        .min_version
        .map(str::to_owned)
        .unwrap_or_else(|| crate::version::SUPPORTED_FLOOR.to_string());
    let found = ctx
        .cli_version
        .map_or_else(|| "unknown".to_owned(), |v| v.to_string());
    ToolError::unsupported_version(meta.name, &needs, &found)
}

/// Whether a tool's stated minimum is met by the CLI we found.
///
/// Checked before spawning, so that a tool with a known minimum reports the
/// version code with its own number rather than whatever the binary says.
pub fn version_permits(ctx: &ToolContext, meta: &ToolMeta) -> ToolResult<()> {
    if satisfies(ctx.cli_version, meta.min_version) {
        Ok(())
    } else {
        Err(version_error(ctx, meta))
    }
}

/// Read the version out of `tailscale version`.
///
/// A failure here is not an error: the probe runs at startup, and a server that
/// refused to start because it could not read a version string would be worse
/// than one that runs without knowing it.
pub async fn probe_version(backend: &dyn tailscale_cli::LocalBackend) -> Option<Version> {
    let output = backend
        .run(Invocation::read(["version"]))
        .await
        .ok()
        .filter(Output::success)?;
    Version::parse_cli_output(&output.stdout_str())
}

/// Read who this node is from `tailscale status --json`.
///
/// Only the handful of fields that name this node, because the point is to
/// recognise a control-plane operation aimed at ourselves (ticket 21) rather
/// than to model the status document — ticket 08 does that properly.
///
/// A failure gives an identity that matches nothing, which is the safe way
/// round: an operation we cannot prove is aimed at ourselves is treated as an
/// ordinary one, and the operator sees the same confirmation rules as anyone
/// managing another node.
pub async fn probe_identity(backend: &dyn tailscale_cli::LocalBackend) -> SelfIdentity {
    status_document(backend)
        .await
        .as_ref()
        .map(identity_in)
        .unwrap_or_default()
}

/// Who this node is and what it calls its peers, from one reading of status.
///
/// Both at once because both come out of the same document, and running
/// `tailscale status` twice at startup to parse the same JSON two ways is work
/// nobody asked for.
pub async fn probe_node(
    backend: &dyn tailscale_cli::LocalBackend,
) -> (SelfIdentity, HashMap<IpAddr, String>) {
    let Some(document) = status_document(backend).await else {
        return (SelfIdentity::default(), HashMap::new());
    };
    (identity_in(&document), peer_names_in(&document))
}

/// `tailscale status --json`, parsed, or nothing if it could not be had.
pub(crate) async fn status_document(
    backend: &dyn tailscale_cli::LocalBackend,
) -> Option<serde_json::Value> {
    let output = backend
        .run(Invocation::read(["status", "--json"]))
        .await
        .ok()
        .filter(Output::success)?;
    serde_json::from_str(&output.stdout_str()).ok()
}

fn identity_in(document: &serde_json::Value) -> SelfIdentity {
    let node = &document["Self"];
    SelfIdentity {
        node_id: node["ID"].as_str().map(str::to_owned),
        // Status cannot supply this: the numeric id is the control plane's own
        // name for the device and is never sent to the node. Filled in from
        // the control plane by `ToolContext::names_us`.
        numeric_id: None,
        addresses: node["TailscaleIPs"]
            .as_array()
            .map(|ips| {
                ips.iter()
                    .filter_map(|ip| ip.as_str().map(str::to_owned))
                    .collect()
            })
            .unwrap_or_default(),
        dns_name: node["DNSName"].as_str().map(str::to_owned),
    }
}

/// Every node this node can name, by address.
///
/// For the HTTP transport's log line: a request arriving from `100.64.0.2` is
/// more useful in a log as the node it came from, and the local node already
/// knows the mapping. An address this node has never heard of stays an
/// address (ticket 23).
fn peer_names_in(document: &serde_json::Value) -> HashMap<IpAddr, String> {
    let mut named = HashMap::new();
    let peers = document["Peer"]
        .as_object()
        .into_iter()
        .flat_map(|by_key| by_key.values());
    for node in std::iter::once(&document["Self"]).chain(peers) {
        let Some(name) = node["DNSName"].as_str() else {
            continue;
        };
        let name = name.trim_end_matches('.');
        for address in node["TailscaleIPs"].as_array().into_iter().flatten() {
            if let Some(address) = address.as_str().and_then(|a| a.parse().ok()) {
                named.insert(address, name.to_owned());
            }
        }
    }
    named
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use super::*;
    use crate::context::{Identity, PathPolicy};
    use crate::error::{ErrorCode, Redactor};
    use crate::meta::{Tier, ToolMeta, Toolset};
    use crate::testing::StubBackend;

    fn meta(min_version: Option<&'static str>) -> ToolMeta {
        ToolMeta {
            name: "tailscale_service_list",
            toolset: Toolset::LocalStatus,
            tier: Tier::Read,
            summary: "",
            self_severing: false,
            severs_local_node: false,
            requires_confirmation: false,
            idempotent: true,
            varying_tier: false,
            min_version,
            platforms: None,
        }
    }

    fn context(backend: StubBackend, cli_version: Option<Version>) -> ToolContext {
        ToolContext {
            local: Arc::new(backend),
            tailnet: None,
            redactor: Redactor::default(),
            max_result_bytes: 1 << 20,
            identity: Identity::default(),
            cli_version,
            paths: PathPolicy::default(),
            devices: Default::default(),
            max_tier: crate::meta::Tier::Destructive,
        }
    }

    #[tokio::test]
    async fn a_clean_exit_is_not_an_error() {
        let ctx = context(StubBackend::ok("1.102.2\n"), None);
        let text = run_text(&ctx, &meta(None), Invocation::read(["version"]))
            .await
            .expect("should succeed");
        assert_eq!(text.trim(), "1.102.2");
    }

    #[tokio::test]
    async fn an_unknown_subcommand_reports_the_minimum_version() {
        let ctx = context(
            StubBackend::failure(1, "tailscale service: unknown subcommand \"list\"\n"),
            Some(Version::new(1, 78, 0)),
        );
        let err = run(
            &ctx,
            &meta(Some("1.94")),
            Invocation::read(["service", "list"]),
        )
        .await
        .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::UnsupportedVersion);
        assert!(err.message.contains("1.94"), "{}", err.message);
        assert!(err.message.contains("1.78.0"), "{}", err.message);
    }

    #[tokio::test]
    async fn an_unknown_flag_reports_the_minimum_version() {
        let ctx = context(
            StubBackend::failure(1, "flag provided but not defined: -report-posture\n"),
            None,
        );
        let err = run(&ctx, &meta(Some("1.58")), Invocation::read(["set"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::UnsupportedVersion);
        assert!(err.message.contains("1.58"), "{}", err.message);
    }

    #[tokio::test]
    async fn a_tool_without_a_minimum_falls_back_to_the_floor() {
        let ctx = context(StubBackend::failure(1, "unknown subcommand\n"), None);
        let err = run(&ctx, &meta(None), Invocation::read(["nonsense"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::UnsupportedVersion);
        assert!(
            err.message
                .contains(&crate::version::SUPPORTED_FLOOR.to_string()),
            "{}",
            err.message
        );
    }

    #[tokio::test]
    async fn a_known_minimum_is_checked_before_the_command_runs() {
        let ctx = context(StubBackend::ok(""), Some(Version::new(1, 78, 0)));
        let err = version_permits(&ctx, &meta(Some("1.94"))).expect_err("should refuse");
        assert_eq!(err.code, ErrorCode::UnsupportedVersion);
        version_permits(&ctx, &meta(Some("1.72"))).expect("older requirement is met");
        version_permits(&ctx, &meta(None)).expect("no requirement is always met");
    }

    #[tokio::test]
    async fn a_permission_refusal_is_reported_as_needing_an_operator() {
        let ctx = context(
            StubBackend::failure(
                1,
                "Access denied: this operation requires the operator to be set\n",
            ),
            None,
        );
        let err = run(&ctx, &meta(None), Invocation::read(["up"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::NeedsOperator);
        assert!(
            err.hint.is_some(),
            "an operator error should say what to do"
        );
    }

    #[tokio::test]
    async fn a_missing_target_is_reported_as_not_found() {
        let ctx = context(StubBackend::failure(1, "no such peer: laptop\n"), None);
        let err = run(&ctx, &meta(None), Invocation::read(["ping", "laptop"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::NotFound);
    }

    #[tokio::test]
    async fn anything_else_is_a_plain_command_failure() {
        let ctx = context(StubBackend::failure(2, "something went wrong\n"), None);
        let err = run(&ctx, &meta(None), Invocation::read(["status"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::CliFailed);
        assert_eq!(err.exit_code, Some(2));
        assert_eq!(err.stderr.as_deref(), Some("something went wrong"));
    }

    #[tokio::test]
    async fn a_missing_binary_disables_the_surface_rather_than_failing_the_command() {
        let ctx = context(StubBackend::missing(), None);
        let err = run(&ctx, &meta(None), Invocation::read(["status"]))
            .await
            .expect_err("should fail");
        assert_eq!(err.code, ErrorCode::BackendUnavailable);
    }

    #[tokio::test]
    async fn a_secret_in_the_error_stream_does_not_reach_the_caller() {
        let ctx = context(
            StubBackend::failure(1, "bad key tskey-auth-example1CNTRL-secretpart\n"),
            None,
        );
        let err = run(&ctx, &meta(None), Invocation::read(["up"]))
            .await
            .expect_err("should fail");
        assert!(
            !err.stderr
                .as_deref()
                .unwrap_or_default()
                .contains("secretpart"),
            "{err:?}"
        );
    }

    #[tokio::test]
    async fn the_version_probe_reads_the_first_line() {
        let backend = StubBackend::ok("1.102.2\n  go version: go1.24.1\n");
        assert_eq!(probe_version(&backend).await, Some(Version::new(1, 102, 2)));
    }

    #[tokio::test]
    async fn the_version_probe_gives_up_quietly() {
        assert_eq!(probe_version(&StubBackend::missing()).await, None);
        assert_eq!(probe_version(&StubBackend::failure(1, "no")).await, None);
        assert_eq!(probe_version(&StubBackend::ok("not a version")).await, None);
    }

    /// One reading of status, two answers out of it.
    #[tokio::test]
    async fn the_status_probe_names_this_node_and_its_peers() {
        let backend = StubBackend::missing().on(
            ["status", "--json"],
            tailscale_cli::stub::Reply::ok(
                serde_json::json!({
                    "Self": {
                        "ID": "n1111111CNTRL",
                        "DNSName": "workstation.example-tailnet.ts.net.",
                        "TailscaleIPs": ["100.64.0.1", "fd7a:115c:a1e0::1"],
                    },
                    "Peer": {
                        "nodekey:2222": {
                            "DNSName": "laptop.example-tailnet.ts.net.",
                            "TailscaleIPs": ["100.64.0.2"],
                        },
                        // No addresses, so nothing to key it by.
                        "nodekey:3333": {"DNSName": "ghost.example-tailnet.ts.net."},
                    },
                })
                .to_string(),
            ),
        );

        let (identity, peers) = probe_node(&backend).await;
        assert!(identity.matches("n1111111CNTRL"));
        assert!(identity.matches("workstation"));
        assert_eq!(
            peers.get(&"100.64.0.2".parse::<IpAddr>().expect("an address")),
            Some(&"laptop.example-tailnet.ts.net".to_owned()),
            "a peer is named by the address a request would arrive from"
        );
        assert_eq!(
            peers.get(&"100.64.0.1".parse::<IpAddr>().expect("an address")),
            Some(&"workstation.example-tailnet.ts.net".to_owned()),
            "and so is this node, which can reach its own HTTP transport"
        );
        assert_eq!(
            peers.len(),
            3,
            "the trailing dot is dropped, the ghost has no address"
        );

        assert_eq!(
            backend.calls().len(),
            1,
            "one reading of status, not one per answer wanted"
        );
    }
}