tailscale-mcp 2.0.3

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
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
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
//! The tailnet surface, as a session actually gets it.
//!
//! What is checked here is not any one tool's behaviour — the contract table
//! covers that — but the things every tailnet tool inherits and none of them
//! implements: that a call carries the credential, means the tailnet the
//! environment named, is held to the session's result cap, and says something
//! useful when there is no credential or the control plane cannot be reached.
//!
//! This replaces `tests/control_plane.rs`, which asserted the same properties
//! by reaching into the session's context and driving the client directly.
//! That was a provisional third seam, kept because ticket 15 built a transport
//! with no tool above it (Q59) and re-aimed at this ticket when ticket 16 also
//! landed none (Q63). Every assertion below is now an ordinary tool call, so
//! nothing here knows how the server is wired.
#![allow(clippy::expect_used, clippy::unwrap_used)]

mod harness;

use serde_json::json;
use tailscale_mcp::config::API_BASE_URL_ENV;
use tailscale_rest::credentials::TAILNET_ENV;
use tailscale_rest::fake::{FakeControlPlane, Response};

use harness::{Setup, TEST_API_KEY};

const DEVICES: &str = "/api/v2/tailnet/-/devices";

#[tokio::test]
async fn a_tool_call_reaches_the_control_plane_with_the_session_credential() {
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .api_answers("GET", DEVICES, Response::json(json!({"devices": []})))
        .await
        .start()
        .await;

    let answer = harness.call_ok("tailnet_device_list", json!({})).await;
    assert_eq!(answer["devices"], json!([]));

    let request = harness.control_plane().only_request();
    assert_eq!(request.path, DEVICES);
    assert_eq!(
        request.authorization(),
        Some(format!("Bearer {TEST_API_KEY}").as_str()),
        "the credential the session was built with should be the one on the wire"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_tailnet_a_tool_acts_on_is_the_one_the_environment_named() {
    let path = "/api/v2/tailnet/example.com/devices";
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .env(TAILNET_ENV, "example.com")
        .api_answers("GET", path, Response::json(json!({"devices": []})))
        .await
        .start()
        .await;

    harness.call_ok("tailnet_device_list", json!({})).await;

    assert_eq!(harness.control_plane().only_request().path, path);

    harness.shutdown().await;
}

#[tokio::test]
async fn an_answer_over_the_session_cap_is_refused_rather_than_truncated() {
    // The same ceiling a tool result is held to. A control-plane answer that
    // could not be returned anyway is better refused before it is parsed.
    let big = json!({
        "devices": (0..50)
            .map(|n| json!({"name": format!("example-node-{n}")}))
            .collect::<Vec<_>>(),
    });
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .env("TAILSCALE_MCP_MAX_RESULT_BYTES", "128")
        .api_answers("GET", DEVICES, Response::json(&big))
        .await
        .start()
        .await;

    let error = harness.call_err("tailnet_device_list", json!({})).await;
    assert_eq!(error["code"], json!("result_too_large"));
    // The session's cap refuses an oversized *result* with the same code, so
    // the code alone would not say which check fired. The message does: the
    // transport's names the request and the ceiling it was held to, while the
    // result cap's states an exact size, which the transport never learns
    // because it stops reading.
    let message = error["message"].as_str().expect("a message");
    assert!(
        message.contains(DEVICES) && message.contains("more than 128 bytes"),
        "the refusal should be the transport's, before the body was parsed: {error:#?}"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_control_plane_that_cannot_be_reached_is_the_surface_being_unavailable() {
    // The one arm of the mapping that cannot be built by hand: a transport
    // failure carries a `reqwest::Error`, which only a real failed request
    // produces. So one is produced — the fake is started and then dropped, so
    // its port is a place nothing is listening.
    let address = {
        let fake = FakeControlPlane::start().await.expect("a loopback socket");
        fake.base_url().to_owned()
    };

    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .env(API_BASE_URL_ENV, &address)
        .start()
        .await;

    let error = harness.call_err("tailnet_device_list", json!({})).await;
    assert_eq!(error["code"], json!("backend_unavailable"));
    assert!(
        error["message"]
            .as_str()
            .is_some_and(|m| m.contains("the control plane is unavailable")),
        "the refusal should say which backend: {error:#?}"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn without_a_credential_the_tailnet_tools_are_absent_and_the_session_is_told_why() {
    // `control_plane.rs` asserted this through the context, where the missing
    // client carries a sentence naming `TAILSCALE_API_KEY`. Through a session
    // that sentence is unreachable: a surface with no credential is switched
    // off at startup, so its tools are never offered and no call can arrive to
    // be refused. What a caller can see is the absence and the instructions,
    // so that is what is checked. The sentence still exists, for the one case
    // that can reach it — a credential that stops working mid-session — and
    // `context.rs`'s
    // `a_context_with_no_credential_names_the_variables_that_would_give_it_one`
    // is where it is asserted.
    let harness = Setup::new()
        .toolsets("local-status,tailnet-devices")
        .without_credentials()
        .start()
        .await;

    let offered = harness.tool_names().await;
    assert!(
        offered.iter().any(|name| name.starts_with("tailscale_")),
        "the local tools are unaffected: {offered:?}"
    );
    assert!(
        !offered.iter().any(|name| name.starts_with("tailnet_")),
        "no tailnet tool should be offered: {offered:?}"
    );
    assert!(
        harness
            .instructions()
            .contains("tailnet surface is not available"),
        "a session that cannot reach the control plane should be told so"
    );

    harness.shutdown().await;
}

// ---------------------------------------------------------------------------
// What the surface adds on top of the transport
// ---------------------------------------------------------------------------

#[tokio::test]
async fn both_device_identifier_forms_reach_the_device_they_name() {
    // The API takes either the node id or the numeric one, and a tool that
    // preferred one would be a tool that could not address half the tailnet.
    for id in ["n1111111CNTRL", "123456789"] {
        let path = format!("/api/v2/device/{id}");
        let harness = Setup::new()
            .toolsets("tailnet-devices")
            .api_answers("GET", &path, Response::json(json!({"nodeId": id})))
            .await
            .start()
            .await;

        let answer = harness
            .call_ok("tailnet_device_get", json!({"device_id": id}))
            .await;

        assert_eq!(answer["nodeId"], json!(id));
        assert_eq!(harness.control_plane().only_request().path, path);
        harness.shutdown().await;
    }
}

#[tokio::test]
async fn field_selection_and_filters_travel_as_the_api_spells_them() {
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .api_answers("GET", DEVICES, Response::json(json!({"devices": []})))
        .await
        .start()
        .await;

    harness
        .call_ok(
            "tailnet_device_list",
            json!({"fields": "all", "filters": {"isEphemeral": "true", "tags": "tag:example"}}),
        )
        .await;

    let query = harness.control_plane().only_request().query.clone();
    assert_eq!(
        query.get("fields").map(String::as_str),
        Some("all"),
        "{query:?}"
    );
    assert_eq!(
        query.get("isEphemeral").map(String::as_str),
        Some("true"),
        "a filter travels as its own query parameter: {query:?}"
    );
    assert_eq!(
        query.get("tags").map(String::as_str),
        Some("tag:example"),
        "{query:?}"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_window_slices_the_listing_without_changing_its_shape() {
    let devices: Vec<_> = (0..5)
        .map(|n| json!({"nodeId": format!("n111111{n}CNTRL")}))
        .collect();
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .api_answers("GET", DEVICES, Response::json(json!({"devices": devices})))
        .await
        .start()
        .await;

    let answer = harness
        .call_ok("tailnet_device_list", json!({"offset": 1, "limit": 2}))
        .await;

    let listed = answer["devices"].as_array().expect("still a device list");
    assert_eq!(listed.len(), 2, "{answer:#?}");
    assert_eq!(listed[0]["nodeId"], json!("n1111111CNTRL"));
    assert_eq!(
        answer["window"],
        json!({"total": 5, "returned": 2, "offset": 1, "limit": 2}),
        "a windowed answer says how much it left out, and what was asked for"
    );

    // The window is this server's, not the API's: the request is unchanged.
    let query = harness.control_plane().only_request().query.clone();
    assert!(!query.contains_key("limit"), "{query:?}");
    assert!(!query.contains_key("offset"), "{query:?}");

    harness.shutdown().await;
}

#[tokio::test]
async fn an_unwindowed_listing_is_the_api_answer_and_nothing_else() {
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .api_answers(
            "GET",
            DEVICES,
            Response::json(json!({"devices": [{"nodeId": "n1111111CNTRL"}]})),
        )
        .await
        .start()
        .await;

    let answer = harness.call_ok("tailnet_device_list", json!({})).await;

    assert_eq!(answer, json!({"devices": [{"nodeId": "n1111111CNTRL"}]}));

    harness.shutdown().await;
}

#[tokio::test]
async fn a_posture_attribute_round_trips_through_the_control_plane() {
    let device = "n1111111CNTRL";
    let attribute = format!("/api/v2/device/{device}/attributes/custom:example");
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers("POST", &attribute, Response::empty())
        .await
        .api_answers(
            "GET",
            &format!("/api/v2/device/{device}/attributes"),
            Response::json(json!({
                "attributes": {"custom:example": 80},
                "expiries": {"custom:example": "2027-01-01T00:00:00Z"},
            })),
        )
        .await
        .api_answers("DELETE", &attribute, Response::empty())
        .await
        .start()
        .await;

    harness
        .call_ok(
            "tailnet_device_attribute_set",
            json!({"device_id": device, "attribute_key": "custom:example", "value": 80,
                   "expiry": "2027-01-01T00:00:00Z"}),
        )
        .await;

    let read = harness
        .call_ok(
            "tailnet_device_attributes_get",
            json!({"device_id": device}),
        )
        .await;
    assert_eq!(read["attributes"]["custom:example"], json!(80));

    let deleted = harness
        .call_ok(
            "tailnet_device_attribute_delete",
            json!({"device_id": device, "attribute_key": "custom:example"}),
        )
        .await;
    assert_eq!(deleted["done"], json!("attribute deleted"));

    let sent = harness.control_plane().recorded();
    assert_eq!(sent.len(), 3, "one call each: {sent:#?}");
    assert_eq!(
        sent[0].json(),
        json!({"value": 80, "expiry": "2027-01-01T00:00:00Z"}),
        "the body is Tailscale's own shape, and carries only what was given"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_batched_attribute_update_refuses_a_key_the_api_would_reject() {
    // Refused here rather than by the control plane, because the batch is
    // all-or-nothing: one bad key in a hundred devices would fail the whole
    // call after it had been sent, and the refusal names the device.
    // An answer is arranged that the call must not reach: if the check were
    // missing, the tool would send the batch and answer with this instead.
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers(
            "PATCH",
            "/api/v2/tailnet/-/device-attributes",
            Response::empty(),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_device_attributes_update",
            json!({"nodes": {"n1111111CNTRL": {"node:os": "linux"}}}),
        )
        .await;

    assert_eq!(error["code"], json!("invalid_args"));
    assert!(
        error["message"]
            .as_str()
            .is_some_and(|m| m.contains("custom:") && m.contains("n1111111CNTRL")),
        "the refusal should name the key and the device: {error:#?}"
    );
    assert_eq!(
        harness.control_plane().request_count(),
        0,
        "nothing should have been sent"
    );

    harness.shutdown().await;
}

// ---------------------------------------------------------------------------
// DNS and policy
// ---------------------------------------------------------------------------

#[tokio::test]
async fn the_split_dns_update_and_replace_forms_are_different_calls() {
    // The API's own distinction, and the one this toolset's naming exists to
    // keep visible: `PATCH` merges, `PUT` overwrites. A tool that sent one
    // where the caller meant the other would silently drop every domain it was
    // not told about.
    let path = "/api/v2/tailnet/-/dns/split-dns";
    let domains = json!({"domains": {"example.com": ["10.0.0.1"]}});
    let harness = Setup::new()
        .toolsets("tailnet-dns")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers(
            "PATCH",
            path,
            Response::json(json!({"example.com": ["10.0.0.1"]})),
        )
        .await
        .api_answers(
            "PUT",
            path,
            Response::json(json!({"example.com": ["10.0.0.1"]})),
        )
        .await
        .start()
        .await;

    harness
        .call_ok("tailnet_dns_split_update", domains.clone())
        .await;
    harness.call_ok("tailnet_dns_split_replace", domains).await;

    let sent = harness.control_plane().recorded();
    assert_eq!(
        sent.iter().map(|r| r.method.as_str()).collect::<Vec<_>>(),
        ["PATCH", "PUT"],
        "the merge and the replace reach different verbs: {sent:#?}"
    );
    // Both send the map itself, not a wrapper: `domains` is this server's
    // parameter name and the body is Tailscale's shape (ADR-0004).
    for request in &sent {
        assert_eq!(request.json(), json!({"example.com": ["10.0.0.1"]}));
    }

    harness.shutdown().await;
}

#[tokio::test]
async fn reading_the_policy_answers_with_its_version_and_the_document_as_written() {
    // `spec.md`'s one documented exception to answering with the body alone:
    // the version is a header, so it cannot travel in a body that has no room
    // for one.
    let hujson = "{\n  // a comment, which JSON does not have\n  \"acls\": [],\n}";
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .api_answers(
            "GET",
            "/api/v2/tailnet/-/acl",
            Response::text("application/hujson", hujson).with_header("etag", "\"e0b2816b418\""),
        )
        .await
        .start()
        .await;

    let answer = harness.call_ok("tailnet_policy_get", json!({})).await;

    assert_eq!(answer["format"], json!("hujson"));
    assert_eq!(answer["etag"], json!("\"e0b2816b418\""));
    assert_eq!(
        answer["policy"],
        json!(hujson),
        "the comments are the part a person wrote, so the document comes back as written"
    );
    assert_eq!(
        harness.control_plane().only_request().header("accept"),
        Some("application/hujson"),
        "and that is what was asked for"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_json_spelling_is_asked_for_and_comes_back_parsed() {
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .api_answers(
            "GET",
            "/api/v2/tailnet/-/acl",
            Response::text("application/json", "{\"acls\": [{\"action\": \"accept\"}]}"),
        )
        .await
        .start()
        .await;

    let answer = harness
        .call_ok("tailnet_policy_get", json!({"format": "json"}))
        .await;

    assert_eq!(answer["format"], json!("json"));
    assert_eq!(
        answer["policy"],
        json!({"acls": [{"action": "accept"}]}),
        "asked for as JSON, so handed back parsed rather than as a string"
    );
    assert_eq!(
        harness.control_plane().only_request().header("accept"),
        Some("application/json")
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_detailed_report_is_asked_for_without_an_accept_and_is_its_own_shape() {
    // Two rules in one call. The description: "If using this, do not supply an
    // `Accept` parameter in the header." And the report is not the policy, so
    // it does not arrive under `policy` — a `format` of `"details"` would be a
    // value `format` does not accept back.
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .api_answers(
            "GET",
            "/api/v2/tailnet/-/acl",
            Response::json(json!({
                "acl": "eyJhY2xzIjogW119",
                "warnings": ["a group is not syncing"],
                "errors": [],
            })),
        )
        .await
        .start()
        .await;

    let answer = harness
        .call_ok("tailnet_policy_get", json!({"details": true}))
        .await;

    assert_eq!(
        answer["details"]["warnings"][0],
        json!("a group is not syncing")
    );
    assert_eq!(answer["details"]["acl"], json!("eyJhY2xzIjogW119"));
    assert!(answer.get("policy").is_none(), "{answer:#?}");
    assert!(answer.get("format").is_none(), "{answer:#?}");

    let request = harness.control_plane().only_request();
    assert_eq!(
        request.query.get("details").map(String::as_str),
        Some("true")
    );
    // "If using this, do not supply an `Accept` parameter in the header."
    // What reaches the wire is the HTTP client's own `*/*`, which every client
    // sends and which asks for nothing in particular. What matters is that
    // this server named neither format: `application/hujson` alongside
    // `details` is the combination the description warns about.
    assert_eq!(
        request.header("accept"),
        Some("*/*"),
        "no format should have been asked for: {:?}",
        request.headers
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn asking_for_a_format_and_the_report_at_once_is_refused() {
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .api_answers(
            "GET",
            "/api/v2/tailnet/-/acl",
            Response::json(json!({"acl": "", "warnings": [], "errors": []})),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_policy_get",
            json!({"details": true, "format": "json"}),
        )
        .await;
    assert_eq!(error["code"], json!("invalid_args"));
    assert_eq!(harness.control_plane().request_count(), 0);

    harness.shutdown().await;
}

#[tokio::test]
async fn a_policy_write_without_a_guard_never_reaches_the_control_plane() {
    // An answer is arranged that the call must not reach: without the check
    // the write would land, and a write with no `If-Match` overwrites whatever
    // is there — including a change the caller never saw.
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers(
            "POST",
            "/api/v2/tailnet/-/acl",
            Response::text("application/hujson", "{}"),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err("tailnet_policy_set", json!({"policy": "{\"acls\": []}"}))
        .await;
    assert_eq!(error["code"], json!("invalid_args"));
    assert_eq!(
        harness.control_plane().request_count(),
        0,
        "nothing should have been sent"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_stale_version_is_a_conflict_that_says_to_read_it_again() {
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers(
            "POST",
            "/api/v2/tailnet/-/acl",
            Response::status(
                412,
                json!({"message": "precondition failed, invalid old hash"}),
            ),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_policy_set",
            json!({"policy": "{\"acls\": []}", "etag": "\"stale\""}),
        )
        .await;

    assert_eq!(error["code"], json!("conflict"));
    assert_eq!(error["status"], json!(412));
    assert!(
        error["hint"]
            .as_str()
            .is_some_and(|h| h.contains("tailnet_policy_get")),
        "the remedy is to read it again: {error:#?}"
    );
    assert_eq!(
        harness.control_plane().only_request().header("if-match"),
        Some("\"stale\""),
        "and the version the caller gave is what was on the wire"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn writing_over_the_default_is_the_other_way_to_pass_the_guard() {
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers(
            "POST",
            "/api/v2/tailnet/-/acl",
            Response::text("application/hujson", "{}"),
        )
        .await
        .start()
        .await;

    harness
        .call_ok(
            "tailnet_policy_set",
            json!({"policy": "{\n  // written by hand\n  \"acls\": [],\n}",
                   "over_default": true}),
        )
        .await;

    let request = harness.control_plane().only_request();
    assert_eq!(request.header("if-match"), Some("\"ts-default\""));
    assert_eq!(
        request.header("content-type"),
        Some("application/hujson"),
        "a document given as a string is sent as HuJSON, comments and all"
    );
    assert!(
        request.body.contains("// written by hand"),
        "and unescaped: {:?}",
        request.body
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_two_validation_modes_are_told_apart_by_what_was_given() {
    // One endpoint, two meanings: an array of tests runs against the policy in
    // force, an object is a hypothetical document. The API reads the body's
    // own JSON type, so sending the wrong one runs the wrong check.
    let path = "/api/v2/tailnet/-/acl/validate";
    let harness = Setup::new()
        .toolsets("tailnet-policy")
        .api_answers("POST", path, Response::empty())
        .await
        .api_answers("POST", path, Response::empty())
        .await
        .start()
        .await;

    let tests = json!([{"src": "someone@example.com", "accept": ["10.0.0.1:80"]}]);
    let passed = harness
        .call_ok("tailnet_policy_validate", json!({"tests": tests}))
        .await;
    assert_eq!(
        passed["passed"],
        json!(true),
        "an empty answer is a pass, and says so rather than answering nothing"
    );

    harness
        .call_ok("tailnet_policy_validate", json!({"policy": {"acls": []}}))
        .await;

    let sent = harness.control_plane().recorded();
    assert!(
        sent[0].json().is_array(),
        "the tests go as an array: {sent:#?}"
    );
    assert!(
        sent[1].json().is_object(),
        "the policy goes as an object: {sent:#?}"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_posture_integration_secret_reaches_the_control_plane_as_client_secret() {
    let harness = Setup::new()
        .toolsets("tailnet-posture")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers(
            "POST",
            "/api/v2/tailnet/-/posture/integrations",
            // The tool passes this answer on unchanged, so a secret echoed in
            // it would reach the caller. Only the request is checked here.
            Response::json(json!({"id": "pi-example", "provider": "falcon"})),
        )
        .await
        .start()
        .await;

    let answer = harness
        .call_ok(
            "tailnet_posture_integration_create",
            json!({"provider": "falcon", "client_secret": "example-secret-value"}),
        )
        .await;

    assert_eq!(answer["id"], json!("pi-example"));
    assert_eq!(
        harness.control_plane().only_request().json()["clientSecret"],
        json!("example-secret-value"),
        "the secret should have reached the control plane as `clientSecret`"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_posture_integration_update_that_changes_nothing_is_refused_before_it_is_sent() {
    // An answer is arranged that the call must not reach: without the check
    // the empty `PATCH` would be sent and answered as if something changed.
    let harness = Setup::new()
        .toolsets("tailnet-posture")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers(
            "PATCH",
            "/api/v2/posture/integrations/pi-example",
            Response::json(json!({"id": "pi-example", "provider": "falcon"})),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_posture_integration_update",
            json!({"integration_id": "pi-example"}),
        )
        .await;

    assert_eq!(error["code"], json!("invalid_args"));
    assert_eq!(
        harness.control_plane().request_count(),
        0,
        "nothing should have been sent"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn a_key_listing_states_its_scope_on_the_wire_whether_or_not_it_was_asked_to() {
    // Q74: the parameter is never absent, because the description marks it
    // required and calls it optional in the same breath, and an absent one
    // would leave which listing came back up to whichever reading the control
    // plane took.
    let path = "/api/v2/tailnet/-/keys";
    let harness = Setup::new()
        .toolsets("tailnet-keys")
        .api_answers("GET", path, Response::json(json!({"keys": []})))
        .await
        .api_answers("GET", path, Response::json(json!({"keys": []})))
        .await
        .start()
        .await;

    harness.call_ok("tailnet_key_list", json!({})).await;
    harness
        .call_ok("tailnet_key_list", json!({"all": false}))
        .await;

    let asked = harness.control_plane().recorded();
    assert_eq!(
        asked[0].query.get("all").map(String::as_str),
        Some("true"),
        "an unasked listing should still say which listing it wants"
    );
    assert_eq!(
        asked[1].query.get("all").map(String::as_str),
        Some("false"),
        "and the narrower question stays available"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn an_invitation_refused_for_the_credential_says_which_credential_it_needs() {
    // Ticket 19's criterion: the six endpoints that act as a person carry the
    // requirement in the failure, since this server cannot tell what kind of
    // credential it holds until the control plane answers (Q76).
    let path = "/api/v2/tailnet/-/user-invites";
    let harness = Setup::new()
        .toolsets("tailnet-invites")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers(
            "POST",
            path,
            Response::status(403, json!({"message": "calling user not found"})),
        )
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_user_invite_create",
            json!({"invites": [{"role": "member", "email": "someone@example.com"}]}),
        )
        .await;

    let hint = error["hint"].as_str().expect("a hint");
    assert!(
        hint.contains("owned by a user") && hint.contains("OAuth client"),
        "the refusal should name the requirement, not just repeat the status: {hint}"
    );
    assert_eq!(error["status"], 403, "and still report what came back");

    harness.shutdown().await;
}

#[tokio::test]
async fn a_service_call_asks_the_other_spelling_when_the_documented_one_is_not_there() {
    // The criterion: service naming follows the path the live API serves, not
    // only the published description. Neither source can be checked from here,
    // so the tool asks (Q81).
    let documented = "/api/v2/tailnet/-/services/svc:example";
    let go_client = "/api/v2/tailnet/-/vip-services/svc:example";
    let harness = Setup::new()
        .toolsets("tailnet-services")
        .api_answers(
            "GET",
            documented,
            Response::status(404, json!({"message": "not found"})),
        )
        .await
        .api_answers(
            "GET",
            go_client,
            Response::json(json!({"name": "svc:example", "addrs": ["100.64.0.1"]})),
        )
        .await
        .start()
        .await;

    let answer = harness
        .call_ok(
            "tailnet_service_get",
            json!({"service_name": "svc:example"}),
        )
        .await;
    assert_eq!(
        answer["name"],
        json!("svc:example"),
        "the second path's answer"
    );

    let asked = harness.control_plane().recorded();
    assert_eq!(
        asked.iter().map(|r| r.path.as_str()).collect::<Vec<_>>(),
        vec![documented, go_client],
        "the documented spelling should be tried first, and only then the other"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn withdrawing_a_host_needs_the_destructive_tier_and_approving_does_not() {
    // Same shape as `tailnet_device_authorize` (Q70): the row's tier is a
    // floor, and the argument decides.
    let path = "/api/v2/tailnet/-/services/svc:example/device/n1111111CNTRL/approved";
    let harness = Setup::new()
        .toolsets("tailnet-services")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers("POST", path, Response::json(json!({"approved": true})))
        .await
        .start()
        .await;

    harness
        .call_ok(
            "tailnet_service_approval_set",
            json!({"service_name": "svc:example", "device_id": "n1111111CNTRL", "approved": true}),
        )
        .await;

    let error = harness
        .call_err(
            "tailnet_service_approval_set",
            json!({"service_name": "svc:example", "device_id": "n1111111CNTRL", "approved": false}),
        )
        .await;
    assert_eq!(error["code"], "not_permitted");
    assert_eq!(
        harness.control_plane().request_count(),
        1,
        "the refusal should happen here, not at the control plane"
    );

    harness.shutdown().await;
}

#[tokio::test]
async fn the_one_paginated_listing_follows_its_cursor_to_the_end() {
    // The criterion, and the reason `tailnet_device_list` needed a window of
    // this server's own while this one does not (Q82).
    let path = "/api/v2/organizations/example.com/tailnets";
    let harness = Setup::new()
        .toolsets("tailnet-org")
        .api_answers_once(
            "GET",
            path,
            Response::json(json!({
                "tailnets": [{"id": "T111111CNTRL"}],
                "cursor": "page-two",
                "totalCount": 2
            })),
        )
        .await
        .api_answers_once(
            "GET",
            path,
            Response::json(json!({"tailnets": [{"id": "T222222CNTRL"}], "totalCount": 2})),
        )
        .await
        .start()
        .await;

    let answer = harness
        .call_ok(
            "tailnet_organization_tailnet_list",
            json!({"organization": "example.com"}),
        )
        .await;
    assert_eq!(
        answer["tailnets"],
        json!([{"id": "T111111CNTRL"}, {"id": "T222222CNTRL"}]),
        "both pages, in order"
    );
    assert_eq!(answer["totalCount"], json!(2));
    assert_eq!(
        answer.get("cursor"),
        None,
        "a walk that finished has nothing left to hand back"
    );

    let asked = harness.control_plane().recorded();
    assert_eq!(asked.len(), 2);
    assert_eq!(
        asked[0].query.get("limit").map(String::as_str),
        Some("100"),
        "the API's maximum page size, and its default"
    );
    assert_eq!(asked[0].query.get("cursor"), None);
    assert_eq!(
        asked[1].query.get("cursor").map(String::as_str),
        Some("page-two"),
        "the second page should be asked for with what the first answered"
    );

    harness.shutdown().await;
}

/// `-` is the one tailnet this tool will not delete.
///
/// Everywhere else in the API `-` means the tailnet the credential belongs to,
/// and the control plane would read it that way here too — so a model that had
/// picked up the convention could delete the tailnet it is working in while
/// believing it had named one. The confirmation does not help: a caller who
/// meant to delete *a* tailnet would confirm. So the refusal is on the name,
/// before anything else, in the same spirit as refusing a device name that
/// matches two devices rather than guessing between them.
#[tokio::test]
async fn a_tailnet_cannot_be_deleted_by_the_dash_that_means_our_own() {
    let harness = Setup::new()
        .toolsets("tailnet-org")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers("DELETE", "/api/v2/tailnet/-", Response::empty())
        .await
        .start()
        .await;

    // Even with the confirmation, which is the case that matters: the guard
    // has to sit in front of a caller who has already said it meant it.
    for given in ["-", " - "] {
        let error = harness
            .call_err(
                "tailnet_organization_tailnet_delete",
                json!({"tailnet": given, "confirm": true}),
            )
            .await;
        assert_eq!(error["code"], "invalid_args", "for {given:?}: {error}");
        assert!(
            error["message"]
                .as_str()
                .is_some_and(|m| m.contains("Name the one you mean")),
            "the refusal should say what to do instead: {error}"
        );
    }
    assert_eq!(
        harness.control_plane().request_count(),
        0,
        "and nothing should have reached the control plane"
    );

    // A tailnet named outright still goes through, so this refuses one thing
    // rather than breaking the tool.
    let harness2 = Setup::new()
        .toolsets("tailnet-org")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers("DELETE", "/api/v2/tailnet/T111111CNTRL", Response::empty())
        .await
        .start()
        .await;
    let answer = harness2
        .call_ok(
            "tailnet_organization_tailnet_delete",
            json!({"tailnet": "T111111CNTRL", "confirm": true}),
        )
        .await;
    assert_eq!(answer["done"], json!("tailnet deleted"));

    harness.shutdown().await;
    harness2.shutdown().await;
}

#[tokio::test]
async fn deleting_this_nodes_own_device_needs_the_call_to_say_so() {
    // The fake `tailscale status` names `n1111111CNTRL` as this node, so the
    // identity read at startup matches it (Q83).
    let ours = "/api/v2/device/n1111111CNTRL";
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers("DELETE", ours, Response::empty())
        .await
        .start()
        .await;

    let error = harness
        .call_err(
            "tailnet_device_delete",
            json!({"device_id": "n1111111CNTRL"}),
        )
        .await;
    assert_eq!(error["code"], "confirmation_required");
    assert_eq!(
        harness.control_plane().request_count(),
        0,
        "the refusal happens here; nothing should reach the control plane"
    );

    let answer = harness
        .call_ok(
            "tailnet_device_delete",
            json!({"device_id": "n1111111CNTRL", "confirm": true}),
        )
        .await;
    assert_eq!(answer["done"], json!("deleted"));

    harness.shutdown().await;
}

#[tokio::test]
async fn the_same_call_against_another_device_is_an_ordinary_one() {
    let theirs = "/api/v2/device/n2222222CNTRL";
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .api_answers("DELETE", theirs, Response::empty())
        .await
        .start()
        .await;

    let answer = harness
        .call_ok(
            "tailnet_device_delete",
            json!({"device_id": "n2222222CNTRL"}),
        )
        .await;
    assert_eq!(answer["done"], json!("deleted"));
    assert_eq!(harness.control_plane().request_count(), 1);

    harness.shutdown().await;
}

/// The numeric id is the other name the control plane accepts, and status
/// never mentions it.
///
/// So a caller naming this node the other way round has to be recognised the
/// other way round, or the confirmation is a rule with a hole exactly where a
/// caller would fall through it. The id is asked of the control plane, once,
/// and only when the target is all digits — which is why the ordinary call
/// above still costs one request and not two (Q87).
#[tokio::test]
async fn this_node_is_recognised_by_its_numeric_id_too() {
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        // What the control plane says when asked who `n1111111CNTRL` is.
        .api_answers(
            "GET",
            "/api/v2/device/n1111111CNTRL",
            Response::json(json!({"nodeId": "n1111111CNTRL", "id": "92960230385"})),
        )
        .await
        .api_answers("DELETE", "/api/v2/device/92960230385", Response::empty())
        .await
        .start()
        .await;

    let error = harness
        .call_err("tailnet_device_delete", json!({"device_id": "92960230385"}))
        .await;
    assert_eq!(
        error["code"], "confirmation_required",
        "the numeric id names this node just as the node id does"
    );

    // Asked once, then remembered: the second refusal costs no further lookup.
    let before = harness.control_plane().request_count();
    let error = harness
        .call_err("tailnet_device_delete", json!({"device_id": "92960230385"}))
        .await;
    assert_eq!(error["code"], "confirmation_required");
    assert_eq!(
        harness.control_plane().request_count(),
        before,
        "the numeric id does not change while the node id stays the same"
    );

    let answer = harness
        .call_ok(
            "tailnet_device_delete",
            json!({"device_id": "92960230385", "confirm": true}),
        )
        .await;
    assert_eq!(answer["done"], json!("deleted"));

    harness.shutdown().await;
}

#[tokio::test]
async fn this_node_is_recognised_by_any_name_the_api_accepts() {
    // `matches` is generous on purpose: a caller may name the node by its
    // address or its MagicDNS name, and a missed match is the expensive
    // direction. The fake status carries all three.
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .start()
        .await;

    for name in [
        "n1111111CNTRL",
        "100.64.0.1",
        "workstation.example-tailnet.ts.net",
    ] {
        let error = harness
            .call_err("tailnet_device_expire", json!({"device_id": name}))
            .await;
        assert_eq!(
            error["code"], "confirmation_required",
            "`{name}` should be recognised as this node: {error:#?}"
        );
    }
    assert_eq!(harness.control_plane().request_count(), 0);

    harness.shutdown().await;
}

#[tokio::test]
async fn with_no_local_surface_there_is_no_identity_and_the_call_is_ordinary() {
    // Documented behaviour, not an accident: a session with no local surface
    // has nothing to match against, and refusing every device operation on a
    // suspicion it cannot check would make the tailnet surface unusable on its
    // own (Q83).
    let ours = "/api/v2/device/n1111111CNTRL";
    let harness = Setup::new()
        .toolsets("tailnet-devices")
        .tier(tailscale_mcp::meta::Tier::Destructive)
        .without_cli()
        .api_answers("DELETE", ours, Response::empty())
        .await
        .start()
        .await;

    let answer = harness
        .call_ok(
            "tailnet_device_delete",
            json!({"device_id": "n1111111CNTRL"}),
        )
        .await;
    assert_eq!(answer["done"], json!("deleted"));

    harness.shutdown().await;
}

/// A misspelled argument is refused, at any depth, rather than dropped.
///
/// Dropped, `multi_use` made a single-use invite that the call reported as
/// made; the arguments are snake_case and Tailscale's bodies camelCase, so the
/// slip is an easy one to make (Q172).
#[tokio::test]
async fn an_argument_the_tool_does_not_take_is_refused_by_name() {
    let harness = Setup::new()
        .toolsets("tailnet-invites")
        .tier(tailscale_mcp::meta::Tier::Write)
        .start()
        .await;

    for (args, (named, accepted)) in [
        (
            json!({"device_id": "n2222222CNTRL", "invites": [{"multiUse": true}], "emails": []}),
            ("`emails`", "`invites`"),
        ),
        (
            json!({"device_id": "n2222222CNTRL", "invites": [{"email": "a@example.com"}, {"multi_use": true}]}),
            ("`invites[1].multi_use`", "`multiUse`"),
        ),
    ] {
        let error = harness.call_err("tailnet_device_invite_create", args).await;
        assert_eq!(error["code"], "invalid_args", "{error:#?}");
        let message = error["message"].as_str().unwrap_or_default();
        assert!(message.contains(named), "{message}");
        assert!(
            message.contains(accepted),
            "the accepted names help the retry: {message}"
        );
    }
    assert_eq!(harness.control_plane().request_count(), 0);

    harness.shutdown().await;
}

/// A document in Tailscale's own shape is the control plane's to judge.
#[tokio::test]
async fn a_free_form_document_still_carries_whatever_it_carries() {
    let harness = Setup::new()
        .toolsets("tailnet-settings")
        .tier(tailscale_mcp::meta::Tier::Write)
        .api_answers("PATCH", "/api/v2/tailnet/-/settings", Response::empty())
        .await
        .start()
        .await;

    let settings = json!({"routeSelection": "regional-routing", "aSettingFromNextYear": 1});
    harness
        .call_ok("tailnet_settings_update", json!({"settings": settings}))
        .await;
    assert_eq!(harness.control_plane().only_request().json(), settings);

    harness.shutdown().await;
}