atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
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
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
//! The `upload_blob` and `download_blob` tools.
//!
//! # Why download defaults to a file
//!
//! A tool result reaches the model as text. A 16 MiB blob is roughly 21.8 MB
//! of base64, which at three to four characters per token is hundreds of
//! thousands of tokens. So the default is to write the bytes to disk and hand
//! back a path plus a `resource_link`; inline is opt-in and capped. Images
//! under the cap are returned as image content instead, which hosts tokenise
//! as an image rather than as a wall of text.
//!
//! # Why download writes only where atpmcp chooses
//!
//! The file is always atpmcp's own: an entry in the blob cache named for the
//! CID, or, with no cache to write to, one too small for the blob or one that
//! cannot store it, a scratch file in the system temp directory under a name
//! unique to the call. The
//! caller cannot name the destination. It could, through an `output_path`
//! argument, until 0.15.0.
//!
//! That argument made `download_blob` a write to any path the user can write,
//! of bytes the caller chose -- the CID check proves only that the bytes are
//! the ones asked for, and anyone can upload any bytes to their own PDS and
//! ask for that CID. A prompt injection could create `~/.zshenv` or a launch
//! agent. The tool is annotated `readOnlyHint: true`, which is what hosts read
//! to decide that a call needs no confirmation, so the write came without a
//! prompt. Removing the argument keeps that annotation true. A host's own
//! file tools, which ask first, can move the file anywhere the user wants it.
//!
//! A call that still passes `output_path` is refused rather than having the
//! argument ignored, because ignoring it would let the caller believe the file
//! was written where it asked.
//!
//! # Why upload has no endpoint override
//!
//! An upload carries a credential. A tool that would send it to a host chosen
//! by the model is a credential-forwarding gadget, so the target is always the
//! account's own PDS.

use std::path::PathBuf;
use std::sync::Arc;

use atproto_client::client::{AppPasswordAuth, Auth};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use serde_json::Value;

use crate::blob::{BlobUri, Locator, is_supported_did, validate_blob_cid};
use crate::context::ServerContext;
use crate::errors::ToolError;
use crate::mime;
use crate::proto::serve::RequestCtx;
use crate::tools::{optional_whole_number, tool_error, tool_structured};
use atpxrpc::accounts;

/// Execute the `upload_blob` tool.
pub async fn upload_blob(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Value {
    match upload(ctx, rctx, arguments).await {
        Ok(value) => value,
        Err(error) => {
            tracing::error!(error = %error, "Blob upload failed.");
            tool_error(&error.to_string())
        }
    }
}

/// The size ceiling for one transfer: the caller's, but never above the
/// operator's.
///
/// A `max_bytes` argument narrows the configured limit and cannot widen it.
/// This was `unwrap_or`, which let the argument replace the limit outright --
/// so the limit bounded only callers who did not ask for more.
fn effective_limit(requested: Option<u64>, configured: u64) -> u64 {
    match requested {
        Some(requested) => requested.min(configured),
        None => configured,
    }
}

/// The caller's `max_bytes`: `None` when absent or `null`, else a whole
/// number of at least 1, as the schema declares.
///
/// Read through [`optional_whole_number`], as `generate_tid` reads its
/// arguments. It was `and_then(Value::as_u64)`, which read `"1024"`, `1024.0`
/// and `-1` as absent, so a caller that asked for at most 1024 bytes was
/// served up to the whole configured ceiling, as a success. Zero is refused
/// too: it can only refuse every blob.
///
/// # Errors
///
/// A message naming the argument.
fn requested_max_bytes(arguments: &Value) -> Result<Option<u64>, String> {
    match optional_whole_number(arguments, "max_bytes") {
        Ok(Some(0)) | Err(_) => {
            Err("the 'max_bytes' argument must be a whole number of at least 1".to_string())
        }
        Ok(requested) => Ok(requested),
    }
}

async fn upload(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Result<Value, ToolError> {
    let Some(auth_handle) = arguments.get("auth_handle").and_then(Value::as_str) else {
        return Err(ToolError::BlobUploadFailed {
            reason: "the 'auth_handle' argument must be a string naming a stored account"
                .to_string(),
        });
    };

    // The configured limit is a ceiling, not a default. It used to be
    // `unwrap_or`, so the argument *replaced* it: a caller passing
    // `max_bytes` larger than the operator's limit had the limit removed.
    // Nothing stopped a multi-gigabyte `path` being read into memory, and
    // the read happens before the account is looked up, so no stored
    // account was needed to do it.
    let requested =
        requested_max_bytes(&arguments).map_err(|reason| ToolError::BlobUploadFailed { reason })?;
    let max_bytes = effective_limit(requested, ctx.limits.blob_max_upload_bytes);

    let path = arguments.get("path").and_then(Value::as_str);
    let data_base64 = arguments.get("data_base64").and_then(Value::as_str);

    let data = match (path, data_base64) {
        (Some(path), None) => read_local_file(path, max_bytes).await?,
        (None, Some(encoded)) => {
            let data = BASE64
                .decode(encoded)
                .map_err(|error| ToolError::BlobUploadFailed {
                    reason: format!("data_base64 is not valid base64: {error}"),
                })?;
            check_size(data.len() as u64, max_bytes)?;
            data
        }
        (Some(_), Some(_)) => {
            return Err(ToolError::BlobUploadFailed {
                reason: "provide exactly one of 'path' or 'data_base64', not both".to_string(),
            });
        }
        (None, None) => {
            return Err(ToolError::BlobUploadFailed {
                reason: "provide exactly one of 'path' or 'data_base64'".to_string(),
            });
        }
    };

    if data.is_empty() {
        return Err(ToolError::BlobUploadFailed {
            reason: "refusing to upload an empty blob".to_string(),
        });
    }

    let declared = arguments.get("content_type").and_then(Value::as_str);
    let content_type = mime::decide(declared, &data)?;

    let mut account =
        accounts::load_account(auth_handle).map_err(|error| ToolError::BlobUploadFailed {
            reason: error.to_string(),
        })?;

    let size = data.len() as u64;
    let Uploaded {
        blob: blob_value,
        cid,
        returned_cid,
        computed,
        verified,
        uri,
    } = put_blob(ctx, rctx, &mut account, data, &content_type.value).await?;

    let mut summary = format!(
        "Uploaded {size} bytes as {} to {}. Blob CID {cid}.",
        content_type.value, account.handle
    );
    if let Some(disagreement) = &content_type.disagreement {
        summary.push_str(&format!(" Note: {disagreement}."));
    }
    if !verified {
        summary.push_str(&format!(
            " Warning: the PDS returned CID {returned_cid} but the bytes hash to {computed}."
        ));
    }

    let structured = serde_json::json!({
        "blob": blob_value,
        "uri": uri,
        "cid": cid,
        "size": size,
        "mimeType": content_type.value,
        "verified": verified,
    });

    Ok(tool_structured(
        &summary,
        structured,
        vec![serde_json::json!({
            "type": "resource_link",
            "uri": uri,
            "name": cid,
            "description": "The uploaded blob, readable as a resource.",
            "mimeType": content_type.value,
        })],
    ))
}

/// A blob [`put_blob`] uploaded.
pub(crate) struct Uploaded {
    /// The blob envelope the PDS answered with, to embed in a record as is.
    pub blob: Value,
    /// The blob's CID: the PDS's, or the one computed from the bytes when it
    /// answered with none.
    pub cid: String,
    /// The CID the PDS answered with, empty when it gave none.
    pub returned_cid: String,
    /// The CID of the bytes sent.
    pub computed: String,
    /// Whether the two agree.
    pub verified: bool,
    /// The blob's `atpmcp://` resource URI.
    pub uri: String,
}

/// Upload `data` to `account`'s own PDS as `mime_type`, refreshing the
/// session once if it has expired, and seed the cache with it when the PDS's
/// CID matches the bytes.
///
/// The one upload path, shared by `upload_blob` and `generate_bsky_post`'s
/// thumbnail, so the second cannot drift from the first on where a
/// credential goes or how an answer is checked.
///
/// # Errors
///
/// [`ToolError::BlobUploadFailed`] when the call is cancelled, the PDS
/// refuses it, or its blob reference cannot be read.
pub(crate) async fn put_blob(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    account: &mut accounts::Account,
    data: Vec<u8>,
    mime_type: &str,
) -> Result<Uploaded, ToolError> {
    let size = data.len() as u64;
    rctx.set_progress_total(Some(size));
    rctx.report_progress(
        0,
        &format!("Uploading {size} bytes to {}", account.pds_endpoint),
    );

    let endpoint = account.pds_endpoint.clone();
    let http = ctx.blob_client.clone();
    let mime_value = mime_type.to_string();
    let computed = atproto_dasl::compute_raw_cid(&data).to_string();

    let response = tokio::select! {
        biased;
        () = rctx.cancel.cancelled() => {
            return Err(ToolError::BlobUploadFailed { reason: "cancelled".to_string() });
        }
        result = accounts::with_refresh(
            &ctx.blob_client,
            account,
            |auth: AppPasswordAuth| {
                let http = http.clone();
                let endpoint = endpoint.clone();
                let mime_value = mime_value.clone();
                let data = data.clone();
                async move {
                    atproto_client::com::atproto::repo::upload_blob(
                        &http,
                        &Auth::AppPassword(auth),
                        &endpoint,
                        &mime_value,
                        data,
                    )
                    .await
                }
            },
            |outcome| match outcome {
                Err(error) => accounts::is_expired_token_error(&error.to_string()),
                Ok(_) => false,
            },
        ) => result.map_err(|error| ToolError::BlobUploadFailed {
            // `{:#}`, not `to_string()`: atproto-client's transport errors
            // carry their cause as a source, so the top line alone says a
            // request failed and not why.
            reason: format!("{error:#}"),
        })?,
    };

    rctx.finish_progress(size, "Upload complete");

    let blob =
        serde_json::to_value(&response.blob).map_err(|error| ToolError::BlobUploadFailed {
            reason: format!("could not serialize the blob reference: {error}"),
        })?;

    let returned_cid = blob
        .get("ref")
        .and_then(|reference| reference.get("$link"))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();

    // A few microseconds of hashing, and it catches a server that stored
    // something other than what we sent.
    let verified = !returned_cid.is_empty() && returned_cid == computed;
    if !verified {
        tracing::warn!(
            returned = %returned_cid,
            computed = %computed,
            "The PDS returned a blob CID that does not match the bytes uploaded."
        );
    }

    let cid = if returned_cid.is_empty() {
        computed.clone()
    } else {
        returned_cid.clone()
    };

    // Seed the cache so an immediate resources/read of the returned URI is
    // free and offline. Only when the CID is the one we can prove.
    if verified {
        let _ = ctx.cache.put(&cid, &data, Some(mime_type)).await;
    }

    let uri = BlobUri::new(account.did.clone(), &cid).to_uri();

    Ok(Uploaded {
        blob,
        cid,
        returned_cid,
        computed,
        verified,
        uri,
    })
}

/// Execute the `download_blob` tool.
pub async fn download_blob(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Value {
    match download(ctx, rctx, arguments).await {
        Ok(value) => value,
        Err(error) => {
            tracing::error!(error = %error, "Blob download failed.");
            tool_error(&error.to_string())
        }
    }
}

async fn download(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    arguments: Value,
) -> Result<Value, ToolError> {
    // Refused before anything connects. See the module docs.
    if arguments.get("output_path").is_some() {
        return Err(ToolError::BlobDownloadFailed {
            reason: "'output_path' is no longer accepted. The blob is saved to atpmcp's own cache \
                     and its path is returned; move it with a file tool if you need it elsewhere"
                .to_string(),
        });
    }

    let requested = requested_max_bytes(&arguments)
        .map_err(|reason| ToolError::BlobDownloadFailed { reason })?;
    let max_bytes = effective_limit(requested, ctx.limits.blob_max_download_bytes);
    let expected = expected_from_reference(&arguments)
        .map_err(|reason| ToolError::BlobDownloadFailed { reason })?;
    let inline = arguments
        .get("inline")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let endpoint = arguments
        .get("endpoint")
        .and_then(Value::as_str)
        .map(str::to_string);
    // A caller-named host, checked before anything connects to it.
    if let Some(endpoint) = endpoint.as_deref() {
        crate::host_policy::check_endpoint(&ctx.limits, endpoint)?;
    }

    let (did, cid) = if let Some(uri) = arguments.get("uri").and_then(Value::as_str) {
        let parsed = BlobUri::parse(uri).map_err(|error| ToolError::BlobDownloadFailed {
            reason: error.to_string(),
        })?;
        (parsed.did, parsed.cid)
    } else {
        let Some(identity) = arguments.get("identity").and_then(Value::as_str) else {
            return Err(ToolError::BlobDownloadFailed {
                reason: "provide either 'uri', or 'identity' together with 'cid'".to_string(),
            });
        };
        let Some(cid) = arguments.get("cid").and_then(Value::as_str) else {
            return Err(ToolError::BlobDownloadFailed {
                reason: "the 'cid' argument must be a string when 'identity' is given".to_string(),
            });
        };
        validate_blob_cid(cid).map_err(|reason| ToolError::BlobDownloadFailed { reason })?;

        // A handle is accepted for convenience and immediately canonicalised;
        // the URI this tool hands back always names a DID.
        let did = if is_supported_did(identity) {
            identity.to_string()
        } else {
            ctx.resolver
                .resolve(identity)
                .await
                .map_err(|error| ToolError::BlobDownloadFailed {
                    reason: format!("failed to resolve {identity}: {error:#}"),
                })?
                .id
        };
        (did, cid.to_string())
    };

    let locator = Locator {
        did: did.clone(),
        cid: cid.clone(),
        endpoint,
    };

    let mut blob = crate::blob::fetch(ctx, rctx, &locator, &expected, max_bytes).await?;
    let size = blob.size;
    let uri = BlobUri::new(&did, &cid).to_uri();
    let mime_type = blob.mime_type.clone();
    let mime_disagreement = blob.mime_disagreement.clone();

    // The verified file's own location, always. With no persistent cache, a
    // budget of zero, or a blob larger than the budget, it is a scratch file
    // that would be deleted when `blob` drops; `keep` lets it outlive the
    // call, since this path is the only way left to reach a blob too large to
    // return inline. A cache entry is not evicted by the commit that wrote
    // it, so either way the path exists when this answers.
    let in_cache = ctx
        .cache
        .path_for(&cid)
        .is_some_and(|entry| entry == blob.path);
    let path = blob.keep().display().to_string();

    let mut content = vec![serde_json::json!({
        "type": "resource_link",
        "uri": uri,
        "name": cid,
        "description": "The downloaded blob, readable as a resource.",
        "mimeType": mime_type,
    })];

    let mut summary = format!(
        "Downloaded {size} bytes ({mime_type}) for {cid} from {did}{}.",
        if blob.cached {
            ", served from cache"
        } else {
            ""
        }
    );
    if let Some(disagreement) = &mime_disagreement {
        summary.push_str(&format!(" Note: {disagreement}."));
    }

    if inline {
        if size > ctx.limits.blob_max_inline_bytes {
            // Its own error, not `BlobTooLarge`. The blob is downloaded by
            // this point and the file is on disk -- the resource link above
            // already names it -- so reporting the same failure as a transfer
            // that never happened tells the caller to do the wrong thing. The
            // remedies are opposite: raise the transfer ceiling, or stop
            // asking for the bytes inline and take the path.
            return Err(ToolError::BlobTooLargeToInline {
                size,
                limit: ctx.limits.blob_max_inline_bytes,
            });
        }
        // At most `size` bytes, just checked against the inline ceiling, and
        // read through the handle they were verified through and hashed
        // again, so they are the verified bytes or an error. Not a second
        // read of `blob.path`, which an eviction or a rename could have
        // changed since.
        let data = blob.bytes().await?;
        let encoded = BASE64.encode(&data);
        if mime::is_image(&mime_type) {
            content.push(serde_json::json!({
                "type": "image",
                "data": encoded,
                "mimeType": mime_type,
            }));
        } else {
            content.push(serde_json::json!({
                "type": "resource",
                "resource": { "uri": uri, "mimeType": mime_type, "blob": encoded },
            }));
        }
    } else if in_cache {
        summary.push_str(&format!(" Saved to {path}."));
    } else {
        summary.push_str(&format!(
            " Saved to {path}, a scratch file outside the blob cache."
        ));
    }

    let mut structured = serde_json::json!({
        "uri": uri,
        "cid": cid,
        "did": did,
        "mimeType": mime_type,
        "size": size,
        "path": path,
        "cached": blob.cached,
        "verified": true,
    });
    if let Some(disagreement) = mime_disagreement {
        structured["mimeTypeDisagreement"] = Value::String(disagreement);
    }

    Ok(tool_structured(&summary, structured, content))
}

/// The `size` and `mime_type` arguments, which a caller copies from the blob
/// reference it is following.
///
/// -04 §11.7 has a client verify a fetched blob's "content hash and size" and
/// "the media type declared in the blob metadata". The CID is checked whatever
/// is passed; these let the rest be. `size` is a whole number of at least 1,
/// as §9.1 has it "non-zero and positive", and `mime_type` a content type.
///
/// # Errors
///
/// A message naming the argument.
fn expected_from_reference(arguments: &Value) -> Result<crate::blob::Expected, String> {
    let size = match optional_whole_number(arguments, "size") {
        Ok(Some(0)) | Err(_) => {
            return Err(
                "the 'size' argument must be a whole number of at least 1, the blob reference's \
                 size"
                    .to_string(),
            );
        }
        Ok(size) => size,
    };
    let mime_type = match arguments.get("mime_type") {
        None | Some(Value::Null) => None,
        Some(Value::String(value)) => {
            mime::check_declared(value)?;
            Some(value.clone())
        }
        Some(other) => {
            return Err(format!(
                "the 'mime_type' argument must be a string, the blob reference's mimeType; got \
                 {other}"
            ));
        }
    };
    Ok(crate::blob::Expected { size, mime_type })
}

/// Read a local file, refusing anything over the ceiling before loading it.
pub(crate) async fn read_local_file(path: &str, max_bytes: u64) -> Result<Vec<u8>, ToolError> {
    let path_buf = PathBuf::from(path);
    if !path_buf.is_absolute() {
        return Err(ToolError::LocalFileFailed {
            path: path.to_string(),
            reason: "the path must be absolute".to_string(),
        });
    }

    // Checked from the metadata first, so a four-gigabyte file is refused
    // without being read into memory.
    let metadata =
        tokio::fs::metadata(&path_buf)
            .await
            .map_err(|error| ToolError::LocalFileFailed {
                path: path.to_string(),
                reason: error.to_string(),
            })?;

    if !metadata.is_file() {
        return Err(ToolError::LocalFileFailed {
            path: path.to_string(),
            reason: "not a regular file".to_string(),
        });
    }
    check_size(metadata.len(), max_bytes)?;

    let data = tokio::fs::read(&path_buf)
        .await
        .map_err(|error| ToolError::LocalFileFailed {
            path: path.to_string(),
            reason: error.to_string(),
        })?;

    // Re-checked after the read: the file could have grown in between.
    check_size(data.len() as u64, max_bytes)?;
    Ok(data)
}

fn check_size(size: u64, limit: u64) -> Result<(), ToolError> {
    if size > limit {
        Err(ToolError::BlobTooLarge { size, limit })
    } else {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::test_support::{test_context, test_request};

    /// The configured limit is a ceiling, not a default.
    ///
    /// It was `unwrap_or`, so an argument above the operator's limit replaced
    /// it outright. With a 1 KiB ceiling configured, a 5 MiB file was read
    /// whole into memory when `max_bytes` asked for 100 MB -- and the read
    /// happens before the account is looked up, so no stored account was
    /// needed to do it.
    #[test]
    fn an_argument_above_the_configured_limit_is_capped() {
        assert_eq!(effective_limit(Some(100_000_000), 1024), 1024);
        assert_eq!(effective_limit(Some(u64::MAX), 16_777_216), 16_777_216);
    }

    /// An argument below the limit still narrows it: the caller may ask for
    /// less, just not more.
    #[test]
    fn an_argument_below_the_configured_limit_narrows_it() {
        assert_eq!(effective_limit(Some(512), 1024), 512);
        assert_eq!(effective_limit(Some(0), 1024), 0);
    }

    /// No argument means the configured limit.
    #[test]
    fn no_argument_uses_the_configured_limit() {
        assert_eq!(effective_limit(None, 1024), 1024);
    }

    /// Upload and download are bounded separately.
    ///
    /// They shared one field, set by a variable named `..._DOWNLOAD_BYTES`, so
    /// an operator bounding uploads was doing it by accident.
    #[test]
    fn upload_and_download_have_their_own_ceilings() {
        let limits = crate::context::Limits {
            blob_max_upload_bytes: 10,
            blob_max_download_bytes: 20,
            ..crate::context::Limits::default()
        };
        assert_eq!(
            effective_limit(Some(1_000), limits.blob_max_upload_bytes),
            10
        );
        assert_eq!(
            effective_limit(Some(1_000), limits.blob_max_download_bytes),
            20
        );
    }

    #[tokio::test]
    async fn upload_requires_an_auth_handle() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let result = upload_blob(&ctx, &mut rctx, serde_json::json!({})).await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("auth_handle")
        );
    }

    #[tokio::test]
    async fn upload_requires_exactly_one_source() {
        let (ctx, mut rctx) = (test_context(), test_request());

        let neither = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({ "auth_handle": "alice.example.com" }),
        )
        .await;
        assert_eq!(neither["isError"], true);

        let both = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "auth_handle": "alice.example.com",
                "path": "/tmp/x",
                "data_base64": "aGk=",
            }),
        )
        .await;
        assert_eq!(both["isError"], true);
        assert!(
            both["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("not both")
        );
    }

    #[tokio::test]
    async fn upload_rejects_invalid_base64() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let result = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "auth_handle": "alice.example.com",
                "data_base64": "not base64!!!",
            }),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("error-atpmcp-tool-10")
        );
    }

    #[tokio::test]
    async fn upload_refuses_an_undeterminable_content_type() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let result = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "auth_handle": "alice.example.com",
                // "plain text" has no magic bytes and no declared type.
                "data_base64": BASE64.encode("plain text"),
            }),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("error-atpmcp-tool-14")
        );
    }

    #[tokio::test]
    async fn upload_enforces_the_size_ceiling() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let oversize = vec![0u8; 4096];
        let result = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "auth_handle": "alice.example.com",
                "data_base64": BASE64.encode(&oversize),
                "content_type": "application/octet-stream",
                "max_bytes": 1024,
            }),
        )
        .await;
        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("error-atpmcp-tool-13"), "{message}");
        // An upload's size is known, and is given exactly.
        assert!(
            message.contains("4096 bytes exceeds limit 1024"),
            "{message}"
        );
        assert!(!message.contains("at least"), "{message}");
    }

    /// The finding: `max_bytes` was read with `as_u64`, so `"1024"`, `-1` and
    /// the rest were taken as absent and the whole configured ceiling applied,
    /// as a success. Each is refused now, naming the argument, before the
    /// download connects anywhere -- the endpoint is unroutable, so reaching
    /// it would fail differently -- and before the upload reads anything.
    #[tokio::test]
    async fn a_max_bytes_that_is_not_a_whole_number_of_at_least_one_is_refused() {
        let (ctx, mut rctx) = (test_context(), test_request());
        for max_bytes in [
            serde_json::json!("1024"),
            serde_json::json!(-1),
            serde_json::json!(0),
            serde_json::json!(1024.5),
            serde_json::json!(true),
        ] {
            let download = download_blob(
                &ctx,
                &mut rctx,
                serde_json::json!({
                    "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                    "cid": atproto_dasl::compute_raw_cid(b"any blob").to_string(),
                    "endpoint": "https://127.0.0.1:1/",
                    "max_bytes": max_bytes,
                }),
            )
            .await;
            assert_eq!(download["isError"], true, "{max_bytes}: {download}");
            let message = download["content"][0]["text"].as_str().unwrap();
            assert!(
                message.starts_with("error-atpmcp-tool-11 ") && message.contains("'max_bytes'"),
                "{max_bytes}: {message}"
            );

            let upload = upload_blob(
                &ctx,
                &mut rctx,
                serde_json::json!({
                    "auth_handle": "alice.example.com",
                    "data_base64": BASE64.encode([0u8; 16]),
                    "content_type": "application/octet-stream",
                    "max_bytes": max_bytes,
                }),
            )
            .await;
            assert_eq!(upload["isError"], true, "{max_bytes}: {upload}");
            let message = upload["content"][0]["text"].as_str().unwrap();
            assert!(
                message.starts_with("error-atpmcp-tool-10 ") && message.contains("'max_bytes'"),
                "{max_bytes}: {message}"
            );
        }
    }

    /// JSON Schema's `integer` includes `1024.0`, so it is 1024: not a
    /// refusal, and not absent. As absent, a 4096-byte blob was served and
    /// uploaded under the whole configured ceiling.
    #[tokio::test]
    async fn a_max_bytes_written_with_a_fraction_is_that_number() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let data = vec![3u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, None).await.unwrap();

        let download = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
                "max_bytes": 1024.0,
            }),
        )
        .await;
        assert_eq!(download["isError"], true, "{download}");
        let message = download["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("error-atpmcp-tool-13"), "{message}");
        assert!(message.contains("limit 1024"), "{message}");

        let upload = upload_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "auth_handle": "alice.example.com",
                "data_base64": BASE64.encode(&data),
                "content_type": "application/octet-stream",
                "max_bytes": 1024.0,
            }),
        )
        .await;
        assert_eq!(upload["isError"], true, "{upload}");
        let message = upload["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("error-atpmcp-tool-13"), "{message}");
        assert!(message.contains("limit 1024"), "{message}");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// `null` is how many clients spell an argument they are not setting.
    #[test]
    fn a_null_max_bytes_is_absent() {
        assert_eq!(
            requested_max_bytes(&serde_json::json!({ "max_bytes": null })),
            Ok(None)
        );
        assert_eq!(requested_max_bytes(&serde_json::json!({})), Ok(None));
        assert_eq!(
            requested_max_bytes(&serde_json::json!({ "max_bytes": 1 })),
            Ok(Some(1))
        );
    }

    #[tokio::test]
    async fn download_requires_a_target() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let result = download_blob(&ctx, &mut rctx, serde_json::json!({})).await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("identity")
        );
    }

    #[tokio::test]
    async fn download_rejects_a_record_cid() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let record_cid = atproto_dasl::compute_cid_for(&serde_json::json!({ "a": 1 }))
            .unwrap()
            .to_string();
        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": record_cid,
            }),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("raw codec")
        );
    }

    #[tokio::test]
    async fn download_rejects_a_malformed_uri() {
        let (ctx, mut rctx) = (test_context(), test_request());
        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({ "uri": "atproto://public/blob/did:plc:abc/bafkrei" }),
        )
        .await;
        assert_eq!(result["isError"], true);
    }

    #[tokio::test]
    async fn a_cache_hit_is_served_without_a_network_call() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let data = {
            let mut png = vec![
                0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
                0x44, 0x52,
            ];
            png.extend_from_slice(&[0u8; 32]);
            png
        };
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, Some("image/png")).await.unwrap();

        // The endpoint is unroutable: reaching the network at all would fail.
        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
            }),
        )
        .await;

        assert_eq!(result["isError"], false, "{result}");
        assert_eq!(result["structuredContent"]["cached"], true);
        assert_eq!(result["structuredContent"]["verified"], true);
        assert_eq!(result["structuredContent"]["mimeType"], "image/png");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// A cached blob is held to the caller's `max_bytes`. It was served
    /// whole: the argument was consulted only on a miss.
    #[tokio::test]
    async fn a_cache_hit_over_max_bytes_is_refused() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let data = vec![5u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, None).await.unwrap();

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
                "max_bytes": 1024,
            }),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("error-atpmcp-tool-13"), "{message}");
        // A cached copy's size is known, so it is given exactly, unlike a
        // download stopped at the limit.
        assert!(
            message.contains("Blob too large: 4096 bytes exceeds limit 1024"),
            "{message}"
        );
        assert!(!message.contains("at least"), "{message}");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// A download stopped at the limit gives what arrived as a lower bound,
    /// `tool-20`. It was `tool-13`, which gives an exact size, so a caller
    /// could retry with `max_bytes` set to that figure and be refused again.
    #[tokio::test]
    async fn a_download_stopped_at_max_bytes_gives_a_lower_bound() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let data = vec![5u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        // No `Content-Length`, so it is the running count that stops the read.
        let endpoint = crate::tools::test_support::one_shot_server(200, data, false).await;

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "max_bytes": 1024,
            }),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.starts_with("error-atpmcp-tool-20 "), "{message}");
        assert!(message.contains("at least"), "{message}");
        assert!(message.contains("limit 1024"), "{message}");
        assert!(!message.contains("error-atpmcp-tool-13"), "{message}");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// And to the operator's download ceiling, with no argument at all. An
    /// entry larger than that ceiling needs no one to have lowered anything:
    /// `upload_blob` seeds the cache under the separate upload ceiling.
    #[tokio::test]
    async fn a_cache_hit_over_the_download_ceiling_is_refused() {
        let ctx = crate::tools::test_support::test_context_with_cache_and_limits(
            crate::context::Limits {
                blob_max_download_bytes: 1024,
                allow_insecure_endpoints: true,
                ..crate::context::Limits::default()
            },
        );
        let mut rctx = test_request();
        let data = vec![6u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        // As `upload_blob` seeds it, under the upload ceiling.
        ctx.cache.put(&cid, &data, None).await.unwrap();

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
            }),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("error-atpmcp-tool-13"), "{message}");
        assert!(message.contains("limit 1024"), "{message}");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// A repository answering `400 {"error":"BlobNotFound"}` is reported as
    /// that answer. It was hashed like a blob and reported as `tool-12`, a CID
    /// mismatch, the alarm for a repository serving the wrong bytes.
    #[tokio::test]
    async fn a_blob_the_repository_does_not_have_is_reported_as_its_answer() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let endpoint = crate::tools::test_support::one_shot_server(
            400,
            br#"{"error":"BlobNotFound","message":"Blob not found"}"#.to_vec(),
            true,
        )
        .await;

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": atproto_dasl::compute_raw_cid(b"not on this PDS").to_string(),
                "endpoint": endpoint,
            }),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.starts_with("error-atpmcp-tool-19 "), "{message}");
        assert!(message.contains("HTTP 400"), "{message}");
        assert!(message.contains("BlobNotFound"), "{message}");
        assert!(!message.contains("error-atpmcp-tool-12"), "{message}");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    #[tokio::test]
    async fn inline_is_refused_above_the_ceiling() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let data = vec![7u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache
            .put(&cid, &data, Some("application/octet-stream"))
            .await
            .unwrap();

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
                "inline": true,
            }),
        )
        .await;

        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        // Its own code, not the transfer-limit one. The blob downloaded; only
        // the request to paste it inline was refused, and the remedies differ.
        assert!(
            message.contains("error-atpmcp-tool-17"),
            "expected the inline-specific refusal, got {message}"
        );
        assert!(
            !message.contains("error-atpmcp-tool-13"),
            "the transfer-limit code says the download failed, which it did not: {message}"
        );
        assert!(
            message.contains("drop 'inline' to take the path"),
            "the refusal should say how to get the bytes: {message}"
        );
        assert!(
            !message.contains("output_path"),
            "and must not point at the removed argument: {message}"
        );

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// A cache small enough to evict a blob as soon as it was written -- an
    /// `ATPMCP_BLOB_CACHE_MAX_BYTES` of 0 did it to every one -- removed the
    /// verified file before the inline read opened it again, so a fetch that
    /// had succeeded was reported as `tool-11`. The read goes through the
    /// verified handle now, which outlives an unlink; `blob.rs`'s
    /// `a_file_removed_after_verification_still_reads_back` covers that. And
    /// a commit no longer evicts what it has just written, while a budget of
    /// 0 caches nothing, so the inline read of such a blob is a scratch file's.
    #[tokio::test]
    async fn an_inline_download_with_a_zero_cache_budget_returns_its_bytes() {
        let ctx = crate::tools::test_support::test_context_with_cache_budget(
            crate::tools::test_support::test_limits(),
            0,
        );
        let mut rctx = test_request();
        let data = b"fetched and verified for a cache that keeps nothing".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        let endpoint = crate::tools::test_support::one_shot_server(200, data.clone(), true).await;

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "inline": true,
            }),
        )
        .await;

        assert_eq!(result["isError"], false, "{result}");
        assert!(!ctx.cache.is_enabled(), "a zero budget caches nothing");
        let inlined = result["content"]
            .as_array()
            .unwrap()
            .iter()
            .find(|block| block["type"] == "resource")
            .expect("the bytes, inline");
        assert_eq!(
            BASE64
                .decode(inlined["resource"]["blob"].as_str().unwrap())
                .unwrap(),
            data
        );

        if let Some(path) = result["structuredContent"]["path"].as_str() {
            let _ = std::fs::remove_file(path);
        }
    }

    /// Download `data` from a one-shot server into a cache with a budget of
    /// `cache_max_bytes`, and return the `path` the tool answered with.
    async fn downloaded_path(
        cache_max_bytes: u64,
        data: &[u8],
        declare_length: bool,
    ) -> (Arc<ServerContext>, std::path::PathBuf) {
        let ctx = crate::tools::test_support::test_context_with_cache_budget(
            crate::tools::test_support::test_limits(),
            cache_max_bytes,
        );
        let result = download_through(&ctx, data, declare_length).await;
        let path = result["structuredContent"]["path"]
            .as_str()
            .expect("a path")
            .into();
        (ctx, path)
    }

    /// Download `data` from a one-shot server through `ctx`, check that it
    /// succeeded, and return the tool's result.
    async fn download_through(
        ctx: &Arc<ServerContext>,
        data: &[u8],
        declare_length: bool,
    ) -> Value {
        let mut rctx = test_request();
        let cid = atproto_dasl::compute_raw_cid(data).to_string();
        let endpoint =
            crate::tools::test_support::one_shot_server(200, data.to_vec(), declare_length).await;

        let result = download_blob(
            ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
            }),
        )
        .await;

        assert_eq!(result["isError"], false, "{result}");
        result
    }

    /// The finding: `commit_write` renamed the blob into the cache and then
    /// pruned it back under budget, and with a budget of 0 that evicted the
    /// entry it had just written. Every download answered with a path that no
    /// longer existed. A budget of 0 now caches nothing, so the path is a
    /// scratch file, as with no cache at all.
    #[tokio::test]
    async fn a_download_path_survives_a_cache_budget_of_zero() {
        let data = b"a blob for a cache that keeps nothing".to_vec();
        let (ctx, path) = downloaded_path(0, &data, true).await;

        assert_eq!(
            std::fs::read(&path).expect("the path the tool returned exists"),
            data
        );
        assert!(!ctx.cache.is_enabled(), "a zero budget caches nothing");
        let _ = std::fs::remove_file(&path);
    }

    /// The same for a blob larger than a budget that is not zero: it cannot
    /// fit, so it is never put in the cache to be evicted from it.
    #[tokio::test]
    async fn a_download_path_survives_a_blob_larger_than_the_cache() {
        let data = b"a blob longer than the sixteen-byte cache it is fetched into".to_vec();
        let (ctx, path) = downloaded_path(16, &data, true).await;

        assert_eq!(
            std::fs::read(&path).expect("the path the tool returned exists"),
            data
        );
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        assert!(
            !ctx.cache.path_for(&cid).unwrap().exists(),
            "a blob larger than the cache is not written into it"
        );
        let _ = std::fs::remove_file(&path);
        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// The finding: without a `Content-Length` the size is known only once
    /// the blob is written, and it was committed into the cache whatever it
    /// turned out to be. The commit's prune may not evict the entry it has
    /// just written, so it evicted every other one trying to get back under a
    /// budget the new entry alone exceeded. The written size is checked now,
    /// and a blob over budget moves out to a scratch file, as a declared one
    /// streams to one.
    #[tokio::test]
    async fn an_undeclared_blob_larger_than_the_cache_leaves_the_other_entries() {
        let ctx = crate::tools::test_support::test_context_with_cache_budget(
            crate::tools::test_support::test_limits(),
            64,
        );
        let dir = ctx.cache.dir().expect("a cache").to_path_buf();
        let resident: Vec<String> = (0..3u8)
            .map(|index| vec![index; 16])
            .map(|data| {
                let cid = atproto_dasl::compute_raw_cid(&data).to_string();
                (cid, data)
            })
            .map(|(cid, data)| {
                std::fs::create_dir_all(&dir).unwrap();
                std::fs::write(dir.join(&cid), data).unwrap();
                cid
            })
            .collect();

        let data = vec![9u8; 100];
        let result = download_through(&ctx, &data, false).await;
        let path = std::path::PathBuf::from(
            result["structuredContent"]["path"]
                .as_str()
                .expect("a path"),
        );

        for cid in &resident {
            assert!(
                ctx.cache.get(cid).await.is_some(),
                "the entries already cached are still there: {cid}"
            );
        }
        assert_eq!(
            std::fs::read(&path).expect("the path the tool returned exists"),
            data
        );
        assert!(
            !path.starts_with(&dir),
            "a blob over budget is a scratch file outside the cache: {}",
            path.display()
        );
        assert!(
            result["content"][0]["text"]
                .as_str()
                .is_some_and(|text| text.contains("a scratch file outside the blob cache")),
            "{result}"
        );
        let mut left: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        left.sort();
        let mut expected = resident.clone();
        expected.sort();
        assert_eq!(
            left, expected,
            "nothing is added to the cache, not even a partial file"
        );

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir_all(dir);
    }

    /// The finding: a blob whose commit failed was used in place, which is
    /// its `.partial` temp file in the cache directory, and `download_blob`
    /// kept it there, a file the cache neither counts nor evicts. It moves out
    /// to a scratch file now. A directory where the entry belongs makes the
    /// commit's rename fail.
    #[tokio::test]
    async fn a_blob_whose_commit_fails_is_handed_out_from_outside_the_cache() {
        let ctx = test_context_with_cache();
        let dir = ctx.cache.dir().expect("a cache").to_path_buf();
        let data = b"a blob the cache cannot take".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        std::fs::create_dir_all(dir.join(&cid)).unwrap();

        let result = download_through(&ctx, &data, true).await;
        let path = std::path::PathBuf::from(
            result["structuredContent"]["path"]
                .as_str()
                .expect("a path"),
        );

        assert!(
            !path.starts_with(&dir),
            "the path is outside the cache: {}",
            path.display()
        );
        assert_eq!(
            std::fs::read(&path).expect("the path the tool returned exists"),
            data
        );
        let left: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(left, vec![cid], "no partial file is left behind");

        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_dir_all(dir);
    }

    #[tokio::test]
    async fn an_image_under_the_ceiling_comes_back_as_image_content() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let mut data = vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52,
        ];
        data.extend_from_slice(&[1u8; 16]);
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, Some("image/png")).await.unwrap();

        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": "https://127.0.0.1:1/",
                "inline": true,
            }),
        )
        .await;

        assert_eq!(result["isError"], false, "{result}");
        let content = result["content"].as_array().unwrap();
        assert!(
            content.iter().any(|block| block["type"] == "image"),
            "an image should be returned as image content: {result}"
        );
        assert!(content.iter().any(|block| block["type"] == "resource_link"));

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    /// The acceptance case for -04 §11.8: a host serving a PNG as
    /// octet-stream. It is reported as `image/png`, by sniffing with no
    /// reference and by the reference's `mime_type`, and comes back inline as
    /// image content.
    #[tokio::test]
    async fn an_octet_stream_png_comes_back_as_an_image() {
        let mut data = vec![
            0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48,
            0x44, 0x52,
        ];
        data.extend_from_slice(&[2u8; 32]);
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();

        for reference in [
            serde_json::json!({}),
            serde_json::json!({ "mime_type": "image/png", "size": data.len() }),
        ] {
            let ctx = test_context();
            let endpoint =
                crate::tools::test_support::one_shot_server(200, data.clone(), true).await;
            let mut arguments = serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "inline": true,
            });
            for (key, value) in reference.as_object().unwrap() {
                arguments[key] = value.clone();
            }

            let result = download_blob(&ctx, &mut test_request(), arguments).await;
            assert_eq!(result["isError"], false, "{reference}: {result}");
            assert_eq!(
                result["structuredContent"]["mimeType"], "image/png",
                "{reference}"
            );
            assert!(result["structuredContent"]["mimeTypeDisagreement"].is_null());
            let content = result["content"].as_array().unwrap();
            assert!(
                content
                    .iter()
                    .any(|block| block["type"] == "image" && block["mimeType"] == "image/png"),
                "{reference}: {result}"
            );
            let _ = std::fs::remove_file(result["structuredContent"]["path"].as_str().unwrap());
        }
    }

    /// Bytes with no magic and no type from the host: the reference's type.
    #[tokio::test]
    async fn a_declared_type_names_a_blob_the_host_does_not() {
        let ctx = test_context();
        let data = b"# a markdown file, served as octet-stream".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        let endpoint = crate::tools::test_support::one_shot_server(200, data.clone(), true).await;
        let result = download_blob(
            &ctx,
            &mut test_request(),
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "mime_type": "text/markdown",
            }),
        )
        .await;
        assert_eq!(result["isError"], false, "{result}");
        assert_eq!(result["structuredContent"]["mimeType"], "text/markdown");
        let _ = std::fs::remove_file(result["structuredContent"]["path"].as_str().unwrap());
    }

    /// A reference whose type the bytes contradict: the bytes' type, with the
    /// disagreement in the text and in `mimeTypeDisagreement`.
    #[tokio::test]
    async fn a_contradicted_declared_type_is_reported() {
        let ctx = test_context();
        let data = b"GIF89a\x01\x00\x01\x00\x00\x00\x00 and the rest".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        let endpoint = crate::tools::test_support::one_shot_server(200, data.clone(), true).await;
        let result = download_blob(
            &ctx,
            &mut test_request(),
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "mime_type": "image/png",
            }),
        )
        .await;
        assert_eq!(result["isError"], false, "{result}");
        assert_eq!(result["structuredContent"]["mimeType"], "image/gif");
        let note = result["structuredContent"]["mimeTypeDisagreement"]
            .as_str()
            .expect("a disagreement");
        assert!(
            note.contains("'image/png'") && note.contains("'image/gif'"),
            "{note}"
        );
        let text = result["content"][0]["text"].as_str().unwrap();
        assert!(text.contains(note), "{text}");
        let _ = std::fs::remove_file(result["structuredContent"]["path"].as_str().unwrap());
    }

    /// The other acceptance case: a size mismatch is refused.
    #[tokio::test]
    async fn a_size_mismatch_is_refused() {
        let ctx = test_context();
        let data = b"thirty-two bytes of blob content".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        let endpoint = crate::tools::test_support::one_shot_server(200, data.clone(), true).await;
        let result = download_blob(
            &ctx,
            &mut test_request(),
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": cid,
                "endpoint": endpoint,
                "size": data.len() + 1,
            }),
        )
        .await;
        assert_eq!(result["isError"], true, "{result}");
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.starts_with("error-atpmcp-tool-22 "), "{message}");
        assert!(
            message.contains(&format!("declares {} bytes", data.len() + 1)),
            "{message}"
        );
    }

    /// `size` and `mime_type` are checked before anything connects: the
    /// endpoint is unroutable, so reaching it would fail differently.
    #[tokio::test]
    async fn a_malformed_size_or_mime_type_is_refused() {
        for (key, value) in [
            ("size", serde_json::json!(0)),
            ("size", serde_json::json!(-1)),
            ("size", serde_json::json!("12")),
            ("size", serde_json::json!(1.5)),
            ("mime_type", serde_json::json!("")),
            ("mime_type", serde_json::json!("png")),
            ("mime_type", serde_json::json!(7)),
        ] {
            let ctx = test_context();
            let mut arguments = serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": "bafkreib2rxk3rh6kzwq5ydyrxc7lhuh6z5s4nmcsn3ynbcpbnkcywxx6iu",
                "endpoint": "https://127.0.0.1:1/",
            });
            arguments[key] = value.clone();
            let result = download_blob(&ctx, &mut test_request(), arguments).await;
            assert_eq!(result["isError"], true, "{key}={value}: {result}");
            let message = result["content"][0]["text"].as_str().unwrap();
            assert!(message.starts_with("error-atpmcp-tool-11 "), "{message}");
            assert!(
                message.contains(&format!("'{key}'")),
                "{key}={value}: {message}"
            );
        }
    }

    /// `output_path` is refused, not ignored, and before anything connects:
    /// the endpoint below is unroutable, so reaching it would fail differently.
    #[tokio::test]
    async fn an_output_path_is_refused() {
        let (ctx, mut rctx) = (test_context_with_cache(), test_request());
        let target =
            std::env::temp_dir().join(format!("atpmcp-output-path-{}", std::process::id()));
        let result = download_blob(
            &ctx,
            &mut rctx,
            serde_json::json!({
                "identity": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
                "cid": "bafkreib2rxk3rh6kzwq5ydyrxc7lhuh6z5s4nmcsn3ynbcpbnkcywxx6iu",
                "endpoint": "https://127.0.0.1:1/",
                "output_path": target.display().to_string(),
            }),
        )
        .await;

        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(
            message.contains("'output_path' is no longer accepted"),
            "expected the refusal, got {message}"
        );
        assert!(!target.exists(), "nothing is written at the named path");

        if let Some(dir) = ctx.cache.dir() {
            let _ = std::fs::remove_dir_all(dir);
        }
    }

    #[tokio::test]
    async fn reading_a_local_file_refuses_a_relative_path() {
        let error = read_local_file("relative/path", 1024).await.unwrap_err();
        assert!(error.to_string().contains("absolute"));
    }

    fn test_context_with_cache() -> Arc<ServerContext> {
        crate::tools::test_support::test_context_with_cache()
    }
}