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
//! Shrinking an image to fit a thumbnail limit.
//!
//! `generate_bsky_post` uses this for a link card's image that is over
//! `app.bsky.embed.external#external.thumb.maxSize`. [`shrink`] fits the image
//! within [`MAX_DIMENSION`] on its longer side, keeps the aspect ratio, and
//! encodes it as JPEG, stepping the quality down through [`QUALITIES`] and
//! then the size down by a quarter at a time until the result fits. An image
//! under the limit is not passed here: it is uploaded as it was served.
//!
//! # The input is a third party's
//!
//! The bytes come from a URL a web page named, so decoding them is decoding
//! hostile input. Four things bound it:
//!
//! - Only JPEG, PNG, GIF and WebP are decoded, by the `image` crate's
//!   pure-Rust decoders. Anything else is refused before decoding.
//! - The dimensions are checked against [`DECODE_MAX_DIMENSION`] before any
//!   pixel is decoded. That is the strict guard against an image whose header
//!   claims a size its bytes never meant to fill: a few hundred bytes can
//!   declare 20,000 by 20,000.
//! - The decoder's allocations are capped at [`DECODE_MAX_ALLOC`]. The
//!   `image` crate documents that cap as one some decoders may ignore, which
//!   is why the dimension check is the one relied on.
//! - The caller runs this on a blocking thread, so a large image costs a
//!   thread for a while and never stalls the server's other requests.
//!
//! # What changes
//!
//! - Transparent pixels are put onto white, because JPEG has no alpha.
//! - An animated GIF gives its first frame.
//! - EXIF orientation is applied to the pixels, since the JPEG written is a
//!   new image and carries no instruction to turn it.
//! - The JPEG carries no metadata, unless the caller asks to preserve EXIF:
//!   then the source's EXIF is copied in, with its orientation set to normal
//!   because the pixels are already turned. XMP and the rest are not copied
//!   either way. The colour profile is copied either way, because it
//!   describes the colours, not the photograph.

use std::borrow::Cow;
use std::io::Cursor;

use image::codecs::jpeg::JpegEncoder;
use image::imageops::FilterType;
use image::metadata::Orientation;
use image::{
    DynamicImage, ImageDecoder, ImageEncoder, ImageFormat, ImageReader, Limits, Rgb, RgbImage,
};

/// The longest side a thumbnail is given, in pixels.
pub const MAX_DIMENSION: u32 = 2000;

/// The longest side an image may claim and still be decoded, in pixels.
pub const DECODE_MAX_DIMENSION: u32 = 8192;

/// The most the decoder may allocate, in bytes: room for an 8192 by 8192 RGBA
/// image (256 MiB) and the decoder's working memory.
pub const DECODE_MAX_ALLOC: u64 = 320 * 1024 * 1024;

/// The JPEG qualities tried at each size, best first.
pub const QUALITIES: &[u8] = &[85, 75, 65, 55, 45];

/// How many times the size is cut by a quarter once every quality is too
/// large at the size before.
const SCALE_STEPS: usize = 6;

/// No thumbnail is made smaller than this on its longer side.
const MIN_DIMENSION: u32 = 64;

/// A thumbnail [`shrink`] made.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Shrunk {
    /// The JPEG.
    pub bytes: Vec<u8>,
    /// Its width, in pixels.
    pub width: u32,
    /// Its height, in pixels.
    pub height: u32,
    /// The image's width before it was shrunk, after orientation.
    pub source_width: u32,
    /// The image's height before it was shrunk, after orientation.
    pub source_height: u32,
    /// The JPEG quality it was encoded at.
    pub quality: u8,
}

/// Shrink `data` to a JPEG of at most `max_bytes`, copying its EXIF only
/// when `preserve_exif` says to.
///
/// # Errors
///
/// Why there is no thumbnail, as a clause that completes "the image is over
/// the limit, and …": a format this does not decode, an image that does not
/// decode or claims dimensions over [`DECODE_MAX_DIMENSION`], or one that
/// stays over `max_bytes` down to [`MIN_DIMENSION`].
pub fn shrink(data: &[u8], max_bytes: usize, preserve_exif: bool) -> Result<Shrunk, String> {
    let mut reader = ImageReader::new(Cursor::new(data))
        .with_guessed_format()
        .map_err(|error| format!("its format could not be read: {error}"))?;
    match reader.format() {
        Some(ImageFormat::Jpeg | ImageFormat::Png | ImageFormat::Gif | ImageFormat::WebP) => {}
        Some(other) => {
            return Err(format!(
                "it is {}, which atpmcp does not shrink",
                other.to_mime_type()
            ));
        }
        None => return Err("its format is not one atpmcp shrinks".to_string()),
    }

    // `Limits` is non-exhaustive, so it is built from its default.
    let mut limits = Limits::default();
    limits.max_image_width = Some(DECODE_MAX_DIMENSION);
    limits.max_image_height = Some(DECODE_MAX_DIMENSION);
    limits.max_alloc = Some(DECODE_MAX_ALLOC);
    reader.limits(limits);

    let undecodable = |error: image::ImageError| format!("it could not be decoded: {error}");
    let mut decoder = reader.into_decoder().map_err(undecodable)?;
    let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
    let metadata = Metadata {
        icc: decoder.icc_profile().ok().flatten(),
        exif: if preserve_exif {
            decoder.exif_metadata().ok().flatten().map(|mut exif| {
                // The encoder writes its own `Exif\0\0` prefix.
                if exif.starts_with(b"Exif\0\0") {
                    exif.drain(..6);
                }
                // The pixels are turned below, so the copy must not say to
                // turn them again.
                let _ = Orientation::remove_from_exif_chunk(&mut exif);
                exif
            })
        } else {
            None
        },
    };
    let mut image = DynamicImage::from_decoder(decoder).map_err(undecodable)?;
    image.apply_orientation(orientation);

    let (source_width, source_height) = (image.width(), image.height());
    let mut bound = MAX_DIMENSION.min(source_width.max(source_height));
    for _ in 0..=SCALE_STEPS {
        let fitted = fit(&image, bound);
        let rgb = onto_white(&fitted);
        for &quality in QUALITIES {
            let bytes = encode(&rgb, quality, &metadata)?;
            if bytes.len() <= max_bytes {
                return Ok(Shrunk {
                    bytes,
                    width: rgb.width(),
                    height: rgb.height(),
                    source_width,
                    source_height,
                    quality,
                });
            }
        }
        bound = bound * 3 / 4;
        if bound < MIN_DIMENSION {
            break;
        }
    }
    Err(format!(
        "it stays over {max_bytes} bytes even at {MIN_DIMENSION} pixels"
    ))
}

/// The width and height `data` is shown at: its stored dimensions, swapped
/// when its EXIF orientation turns it a quarter, as a viewer would.
///
/// Reads only the header, under the same limits as [`shrink`].
///
/// # Errors
///
/// A clause about the image ("its dimensions could not be read: …") when it
/// is not a JPEG, PNG, GIF or WebP whose header decodes.
pub fn display_dimensions(data: &[u8]) -> Result<(u32, u32), String> {
    let unreadable = |error: String| format!("its dimensions could not be read: {error}");
    let mut reader = ImageReader::new(Cursor::new(data))
        .with_guessed_format()
        .map_err(|error| unreadable(error.to_string()))?;
    let mut limits = Limits::default();
    limits.max_image_width = Some(DECODE_MAX_DIMENSION);
    limits.max_image_height = Some(DECODE_MAX_DIMENSION);
    limits.max_alloc = Some(DECODE_MAX_ALLOC);
    reader.limits(limits);
    let mut decoder = reader
        .into_decoder()
        .map_err(|error| unreadable(error.to_string()))?;
    let (width, height) = decoder.dimensions();
    let turned = matches!(
        decoder.orientation().unwrap_or(Orientation::NoTransforms),
        Orientation::Rotate90
            | Orientation::Rotate270
            | Orientation::Rotate90FlipH
            | Orientation::Rotate270FlipH
    );
    Ok(if turned {
        (height, width)
    } else {
        (width, height)
    })
}

/// `image` scaled to fit within `bound` on its longer side, or `image` itself
/// when it already fits. Never enlarged.
fn fit(image: &DynamicImage, bound: u32) -> Cow<'_, DynamicImage> {
    if image.width() <= bound && image.height() <= bound {
        Cow::Borrowed(image)
    } else {
        Cow::Owned(image.resize(bound, bound, FilterType::CatmullRom))
    }
}

/// `image` as RGB, with any transparency put onto white.
fn onto_white(image: &DynamicImage) -> RgbImage {
    if !image.color().has_alpha() {
        return image.to_rgb8();
    }
    let rgba = image.to_rgba8();
    let mut rgb = RgbImage::new(rgba.width(), rgba.height());
    for (out, pixel) in rgb.pixels_mut().zip(rgba.pixels()) {
        let [red, green, blue, alpha] = pixel.0;
        let alpha = u32::from(alpha);
        // Rounded, so an opaque pixel keeps its value exactly.
        let blend = |channel: u8| {
            let mixed = (u32::from(channel) * alpha + 255 * (255 - alpha) + 127) / 255;
            u8::try_from(mixed).unwrap_or(u8::MAX)
        };
        *out = Rgb([blend(red), blend(green), blend(blue)]);
    }
    rgb
}

/// What [`shrink`] copies from the source into the JPEG.
struct Metadata {
    /// The colour profile, always copied.
    icc: Option<Vec<u8>>,
    /// The EXIF block, copied only when it is to be preserved.
    exif: Option<Vec<u8>>,
}

fn encode(rgb: &RgbImage, quality: u8, metadata: &Metadata) -> Result<Vec<u8>, String> {
    let mut bytes = Vec::new();
    let mut encoder = JpegEncoder::new_with_quality(&mut bytes, quality);
    // The JPEG encoder accepts both; an error here would be the encoder
    // refusing metadata, and the image is still worth having without it.
    if let Some(icc) = &metadata.icc {
        let _ = encoder.set_icc_profile(icc.clone());
    }
    if let Some(exif) = &metadata.exif {
        let _ = encoder.set_exif_metadata(exif.clone());
    }
    encoder
        .encode_image(rgb)
        .map_err(|error| format!("it could not be encoded as JPEG: {error}"))?;
    Ok(bytes)
}

#[cfg(test)]
pub(crate) mod tests {
    use image::codecs::gif::GifEncoder;
    use image::codecs::png::PngEncoder;
    use image::{Delay, Frame, ImageEncoder, Rgba, RgbaImage};

    use super::*;

    /// Pseudo-random bytes, which no codec compresses, from a fixed seed.
    pub(crate) fn noise(len: usize, seed: u64) -> Vec<u8> {
        let mut state = seed | 1;
        (0..len)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                (state >> 32) as u8
            })
            .collect()
    }

    /// A PNG of RGB noise, `width` by `height`.
    pub(crate) fn noise_png(width: u32, height: u32) -> Vec<u8> {
        let pixels = noise((width * height * 3) as usize, u64::from(width * height));
        let mut png = Vec::new();
        PngEncoder::new(&mut png)
            .write_image(&pixels, width, height, image::ExtendedColorType::Rgb8)
            .expect("encode PNG");
        png
    }

    fn decode(jpeg: &[u8]) -> DynamicImage {
        image::load_from_memory_with_format(jpeg, ImageFormat::Jpeg).expect("a JPEG")
    }

    #[test]
    fn noise_over_the_limit_comes_out_under_it() {
        let png = noise_png(600, 400);
        let limit = 60_000;
        assert!(png.len() > limit);

        let shrunk = shrink(&png, limit, false).expect("shrunk");
        assert!(shrunk.bytes.len() <= limit, "{}", shrunk.bytes.len());
        assert_eq!((shrunk.source_width, shrunk.source_height), (600, 400));
        // Noise needs more than a lower quality: the size came down too, and
        // the aspect ratio held, to within a pixel of rounding.
        assert!(shrunk.width < 600);
        let expected_height = shrunk.width * 2 / 3;
        assert!(
            shrunk.height.abs_diff(expected_height) <= 1,
            "{}x{}",
            shrunk.width,
            shrunk.height
        );
        let decoded = decode(&shrunk.bytes);
        assert_eq!(
            (decoded.width(), decoded.height()),
            (shrunk.width, shrunk.height)
        );
    }

    #[test]
    fn a_large_image_is_fitted_within_the_dimension_bound() {
        let image = DynamicImage::ImageRgb8(RgbImage::from_fn(3000, 1000, |x, _| {
            Rgb([(x % 256) as u8, 128, 64])
        }));
        let mut png = Vec::new();
        image
            .write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
            .expect("PNG");

        let shrunk = shrink(&png, 1_000_000, false).expect("shrunk");
        assert_eq!((shrunk.width, shrunk.height), (2000, 667));
        assert_eq!(shrunk.quality, QUALITIES[0]);
    }

    #[test]
    fn a_small_image_is_never_enlarged() {
        let image = DynamicImage::ImageRgb8(RgbImage::from_pixel(40, 30, Rgb([10, 20, 30])));
        let mut png = Vec::new();
        image
            .write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
            .expect("PNG");
        let shrunk = shrink(&png, 1_000_000, false).expect("shrunk");
        assert_eq!((shrunk.width, shrunk.height), (40, 30));
    }

    #[test]
    fn transparency_goes_onto_white() {
        let image = RgbaImage::from_fn(16, 16, |x, _| {
            if x < 8 {
                Rgba([0, 0, 0, 0])
            } else {
                Rgba([0, 0, 255, 255])
            }
        });
        let mut png = Vec::new();
        DynamicImage::ImageRgba8(image)
            .write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
            .expect("PNG");

        let decoded = decode(&shrink(&png, 1_000_000, false).expect("shrunk").bytes).to_rgb8();
        let clear = decoded.get_pixel(2, 8).0;
        assert!(clear.iter().all(|&c| c > 240), "{clear:?}");
        let opaque = decoded.get_pixel(13, 8).0;
        assert!(opaque[2] > 200 && opaque[0] < 60, "{opaque:?}");
    }

    #[test]
    fn an_animated_gif_gives_its_first_frame() {
        let frame = |colour: [u8; 4]| {
            Frame::from_parts(
                RgbaImage::from_pixel(8, 8, Rgba(colour)),
                0,
                0,
                Delay::from_numer_denom_ms(100, 1),
            )
        };
        let mut gif = Vec::new();
        GifEncoder::new(&mut gif)
            .encode_frames([frame([255, 0, 0, 255]), frame([0, 255, 0, 255])])
            .expect("GIF");

        let decoded = decode(&shrink(&gif, 1_000_000, false).expect("shrunk").bytes).to_rgb8();
        let pixel = decoded.get_pixel(4, 4).0;
        assert!(pixel[0] > 200 && pixel[1] < 60, "{pixel:?}");
    }

    /// EXIF orientation 6 is a quarter turn clockwise: a wide image stored
    /// that way is shown tall, and the thumbnail is tall, because the JPEG
    /// written carries no EXIF to say so.
    #[test]
    fn exif_orientation_is_applied() {
        // A TIFF header and one IFD entry: tag 0x0112 (Orientation), SHORT,
        // count 1, value 6.
        let exif = [
            b'I', b'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 0x01, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0,
            0,
        ];
        let mut jpeg = Vec::new();
        let mut encoder = JpegEncoder::new_with_quality(&mut jpeg, 90);
        encoder.set_exif_metadata(exif.to_vec()).expect("EXIF");
        encoder
            .encode_image(&RgbImage::from_pixel(40, 20, Rgb([200, 100, 50])))
            .expect("JPEG");

        let shrunk = shrink(&jpeg, 1_000_000, false).expect("shrunk");
        assert_eq!((shrunk.width, shrunk.height), (20, 40));
    }

    /// By default the JPEG carries no EXIF; preserved, it carries the
    /// source's, with the orientation made normal, since the pixels are
    /// already turned. The colour profile is copied either way.
    #[test]
    fn exif_is_copied_only_when_preserved_and_the_profile_always() {
        use crate::image_metadata::tests::{ICC, SECRET, jpeg_with_metadata};
        let contains = |haystack: &[u8], needle: &[u8]| {
            haystack
                .windows(needle.len())
                .any(|window| window == needle)
        };
        let source = jpeg_with_metadata(6);

        let stripped = shrink(&source, 1_000_000, false).expect("shrunk");
        assert!(!contains(&stripped.bytes, SECRET));
        assert!(!contains(&stripped.bytes, b"Exif\0\0"));
        assert!(contains(&stripped.bytes, ICC));

        let kept = shrink(&source, 1_000_000, true).expect("shrunk");
        assert!(contains(&kept.bytes, SECRET), "the source's EXIF is copied");
        assert!(contains(&kept.bytes, ICC));
        let mut decoder = ImageReader::new(Cursor::new(&kept.bytes))
            .with_guessed_format()
            .unwrap()
            .into_decoder()
            .unwrap();
        assert_eq!(decoder.orientation().unwrap(), Orientation::NoTransforms);
        // Turned once, by the pixels: 24 by 16 stored, 16 by 24 shown.
        assert_eq!((kept.width, kept.height), (16, 24));
    }

    #[test]
    fn display_dimensions_follow_the_exif_orientation() {
        use crate::image_metadata::tests::jpeg_with_metadata;
        // The fixture is stored 24 by 16.
        assert_eq!(display_dimensions(&jpeg_with_metadata(1)), Ok((24, 16)));
        assert_eq!(display_dimensions(&jpeg_with_metadata(6)), Ok((16, 24)));
        assert_eq!(display_dimensions(&jpeg_with_metadata(3)), Ok((24, 16)));
        assert!(display_dimensions(b"not an image").is_err());
    }

    /// A PNG that claims 20,000 by 20,000 is refused on its header, before
    /// anything is allocated for it.
    #[test]
    fn claimed_dimensions_over_the_cap_are_refused() {
        let mut png = Vec::new();
        DynamicImage::ImageRgb8(RgbImage::new(1, 1))
            .write_to(&mut Cursor::new(&mut png), ImageFormat::Png)
            .expect("PNG");
        // IHDR's width and height are bytes 16..24, and its CRC, over the
        // chunk type and data (bytes 12..29), is bytes 29..33.
        png[16..20].copy_from_slice(&20_000u32.to_be_bytes());
        png[20..24].copy_from_slice(&20_000u32.to_be_bytes());
        let crc = crc32(&png[12..29]);
        png[29..33].copy_from_slice(&crc.to_be_bytes());

        let error = shrink(&png, 1_000_000, false).expect_err("refused");
        assert!(error.starts_with("it could not be decoded"), "{error}");
    }

    #[test]
    fn a_format_it_does_not_shrink_is_refused() {
        let mut bmp = Vec::new();
        DynamicImage::ImageRgb8(RgbImage::new(2, 2))
            .write_to(&mut Cursor::new(&mut bmp), ImageFormat::Bmp)
            .unwrap_or_else(|_| bmp.extend_from_slice(b"BM\x46\0\0\0\0\0\0\0\x36\0\0\0"));
        let error = shrink(&bmp, 1_000_000, false).expect_err("refused");
        assert!(error.contains("does not shrink"), "{error}");

        let error = shrink(b"not an image at all", 1_000_000, false).expect_err("refused");
        assert!(error.contains("not one atpmcp shrinks"), "{error}");
    }

    /// CRC-32 (IEEE), as PNG uses it.
    pub(crate) fn crc32(bytes: &[u8]) -> u32 {
        let mut crc = 0xFFFF_FFFFu32;
        for &byte in bytes {
            crc ^= u32::from(byte);
            for _ in 0..8 {
                crc = if crc & 1 == 1 {
                    (crc >> 1) ^ 0xEDB8_8320
                } else {
                    crc >> 1
                };
            }
        }
        !crc
    }
}