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
//! Determining a blob's content type from its bytes.
//!
//! The content type recorded on a blob at upload is the one every blob
//! reference to it carries, and what a host usually serves it as, and it
//! cannot be corrected afterwards. So it has to be the type determined from
//! the bytes, and never one a caller merely asserted — a caller that is,
//! here, a language model working from a filename.
//!
//! When a caller does declare a type and the bytes disagree, the sniffed type
//! wins and the disagreement is reported rather than swallowed. Silently
//! overriding is how a caller ends up unable to explain what happened.
//!
//! A download is the other direction ([`resolve_served`]). The type a host
//! serves is its own choice, and -04 §11.8 lets it serve every blob as
//! `application/octet-stream`, so a served type of that kind says nothing
//! about the blob. The type the blob reference declares is checked against
//! what the host and the bytes say (§11.7), and stands in for a generic one.

use crate::errors::ToolError;

/// The generic type, which says only that the content is bytes.
pub const OCTET_STREAM: &str = "application/octet-stream";

/// What was decided about a blob's content type, and why.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContentType {
    /// The type to record on the blob.
    pub value: String,
    /// Set when the caller declared a type the bytes contradict.
    pub disagreement: Option<String>,
}

/// Decide the content type for bytes about to be uploaded.
///
/// # Errors
///
/// Returns [`ToolError::ContentTypeUndetermined`] when neither the caller nor
/// the bytes yield an answer. Defaulting to `application/octet-stream` is
/// deliberately not done: an unrecognised type recorded on a blob is permanent
/// and many servers refuse it outright, so failing here costs a retry while
/// guessing costs a blob.
pub fn decide(declared: Option<&str>, data: &[u8]) -> Result<ContentType, ToolError> {
    let sniffed = sniff(data);

    match (declared, sniffed) {
        (Some(declared), Some(sniffed)) if types_agree(declared, sniffed) => Ok(ContentType {
            value: sniffed.to_string(),
            disagreement: None,
        }),
        (Some(declared), Some(sniffed)) => Ok(ContentType {
            value: sniffed.to_string(),
            disagreement: Some(format!(
                "content_type was given as '{declared}' but the bytes are '{sniffed}'; \
                 recorded the type determined from the bytes"
            )),
        }),
        // No confident sniff. The caller's word is all there is, and for text
        // and JSON — which have no magic bytes — it is often right.
        (Some(declared), None) => Ok(ContentType {
            value: declared.to_string(),
            disagreement: None,
        }),
        (None, Some(sniffed)) => Ok(ContentType {
            value: sniffed.to_string(),
            disagreement: None,
        }),
        (None, None) => Err(ToolError::ContentTypeUndetermined),
    }
}

/// Identify a content type from magic bytes, if one is recognised.
#[must_use]
pub fn sniff(data: &[u8]) -> Option<&'static str> {
    infer::get(data).map(|kind| kind.mime_type())
}

/// Whether two content types describe the same thing.
///
/// Compared on the bare type, ignoring parameters and case, so
/// `image/jpeg; charset=binary` agrees with `image/jpeg`.
fn types_agree(one: &str, other: &str) -> bool {
    // `image/jpg` is not a real media type but is common enough in the wild
    // that treating it as a disagreement would be noise rather than signal.
    let normal = |value: &str| {
        let base = base_type(value);
        if base == "image/jpg" {
            "image/jpeg".to_string()
        } else {
            base
        }
    };
    normal(one) == normal(other)
}

/// The bare type of a content type: lower case, without parameters.
fn base_type(value: &str) -> String {
    value
        .split(';')
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase()
}

/// Whether a content type says nothing about the content: empty, or
/// `application/octet-stream` with or without parameters.
#[must_use]
pub fn is_generic(mime_type: &str) -> bool {
    let base = base_type(mime_type);
    base.is_empty() || base == OCTET_STREAM
}

/// Check a content type a caller declares for a blob it is fetching, as a
/// blob reference's `mimeType` would carry it.
///
/// -04 §9.1 says only that it "MUST NOT be an empty string". This asks for a
/// `type/subtype` of RFC 6838 name characters as well, with any parameters
/// in visible ASCII, since the value is reported back and recorded in the
/// cache, and anything else is not a content type.
///
/// # Errors
///
/// A message naming the argument.
pub fn check_declared(value: &str) -> Result<(), String> {
    let name = |part: &str| {
        !part.is_empty()
            && part
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b"!#$&-^_.+".contains(&b))
    };
    let visible = value.len() <= 255 && value.bytes().all(|b| (0x20..0x7f).contains(&b));
    let base = value.split(';').next().unwrap_or("").trim();
    match base.split_once('/') {
        Some((kind, subtype)) if visible && name(kind) && name(subtype) => Ok(()),
        _ => Err(format!(
            "the 'mime_type' argument must be a content type such as 'image/png', as the blob \
             reference's mimeType gives it; got {value:?}"
        )),
    }
}

/// Whether [`resolve_served`] can use a sniff of the bytes: the served type
/// is generic or missing, or there is a declared type to check.
#[must_use]
pub fn wants_sniff(served: Option<&str>, declared: Option<&str>) -> bool {
    served.is_none_or(is_generic) || declared.is_some_and(|declared| !is_generic(declared))
}

/// What a download decided about a blob's content type.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServedType {
    /// The type to report the blob as, and to record in the cache.
    pub value: String,
    /// Set when the declared type disagrees with the served type or the
    /// bytes. Reported, not refused: see [`resolve_served`].
    pub disagreement: Option<String>,
}

/// Decide the type a fetched blob is reported as, from the type the host
/// served (or the cache recorded), the type the caller's blob reference
/// declares, and the type sniffed from the verified bytes.
///
/// A served type that names something stands: it is what the host says, and
/// this does not second-guess it. A generic or missing one gives way, since
/// -04 §11.8 lets a host serve every blob as `application/octet-stream`. Then
/// the declared type is used, unless the bytes are recognised as something
/// else, when the sniffed type is: a type chosen here is never one the bytes
/// contradict. With neither, the blob is `application/octet-stream`.
///
/// The declared type is checked against the served type and the bytes, as
/// -04 §11.7 asks a client to verify "the media type declared in the blob
/// metadata", and a disagreement is reported rather than refused. A sniff is
/// a heuristic over magic bytes, text formats have none, and a host may serve
/// a type the reference spells differently, so refusing would make readable
/// blobs unreadable. A size, by contrast, is exact, and the download refuses
/// a mismatch.
#[must_use]
pub fn resolve_served(
    served: Option<&str>,
    declared: Option<&str>,
    sniffed: Option<&str>,
) -> ServedType {
    let served_specific = served.filter(|served| !is_generic(served));
    let declared_specific = declared.filter(|declared| !is_generic(declared));

    let value = match (served_specific, declared_specific, sniffed) {
        (Some(served), _, _) => served,
        (None, Some(declared), Some(sniffed)) if !types_agree(declared, sniffed) => sniffed,
        (None, Some(declared), _) => declared,
        (None, None, Some(sniffed)) => sniffed,
        (None, None, None) => OCTET_STREAM,
    };

    let mut disagreements = Vec::new();
    if let Some(declared) = declared_specific {
        if let Some(served) = served_specific
            && !types_agree(declared, served)
        {
            disagreements.push(format!(
                "the blob reference declares '{declared}' but the host served '{served}'"
            ));
        }
        if let Some(sniffed) = sniffed
            && !types_agree(declared, sniffed)
        {
            disagreements.push(format!(
                "the blob reference declares '{declared}' but the bytes are '{sniffed}'"
            ));
        }
    }

    ServedType {
        value: value.to_string(),
        disagreement: (!disagreements.is_empty()).then(|| disagreements.join("; ")),
    }
}

/// Whether a content type names an image.
///
/// Images under the inline ceiling are returned to the model as image content
/// rather than as base64 text, which hosts tokenise very differently.
#[must_use]
pub fn is_image(mime_type: &str) -> bool {
    base_type(mime_type).starts_with("image/")
}

#[cfg(test)]
mod tests {
    use super::*;

    const PNG: &[u8] = &[
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44,
        0x52,
    ];
    const GIF: &[u8] = b"GIF89a\x01\x00\x01\x00\x00\x00\x00";

    #[test]
    fn sniffs_known_formats() {
        assert_eq!(sniff(PNG), Some("image/png"));
        assert_eq!(sniff(GIF), Some("image/gif"));
    }

    #[test]
    fn plain_text_has_no_magic_bytes() {
        assert_eq!(sniff(b"just some text"), None);
    }

    #[test]
    fn sniffed_type_is_used_when_nothing_is_declared() {
        let decided = decide(None, PNG).unwrap();
        assert_eq!(decided.value, "image/png");
        assert!(decided.disagreement.is_none());
    }

    #[test]
    fn agreeing_declaration_produces_no_complaint() {
        let decided = decide(Some("image/png"), PNG).unwrap();
        assert_eq!(decided.value, "image/png");
        assert!(decided.disagreement.is_none());
    }

    #[test]
    fn parameters_and_case_do_not_count_as_disagreement() {
        let decided = decide(Some("IMAGE/PNG; charset=binary"), PNG).unwrap();
        assert!(decided.disagreement.is_none());
    }

    #[test]
    fn image_jpg_is_treated_as_image_jpeg() {
        let jpeg = &[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46];
        let decided = decide(Some("image/jpg"), jpeg).unwrap();
        assert_eq!(decided.value, "image/jpeg");
        assert!(decided.disagreement.is_none());
    }

    #[test]
    fn disagreement_is_reported_and_the_bytes_win() {
        let decided = decide(Some("image/gif"), PNG).unwrap();
        assert_eq!(decided.value, "image/png");
        let complaint = decided.disagreement.expect("disagreement is reported");
        assert!(complaint.contains("image/gif"));
        assert!(complaint.contains("image/png"));
    }

    #[test]
    fn a_declaration_stands_when_the_bytes_are_unrecognised() {
        let decided = decide(Some("text/plain"), b"just some text").unwrap();
        assert_eq!(decided.value, "text/plain");
        assert!(decided.disagreement.is_none());
    }

    #[test]
    fn undetermined_is_an_error_rather_than_a_guess() {
        let error = decide(None, b"just some text").expect_err("nothing to go on");
        assert!(matches!(error, ToolError::ContentTypeUndetermined));
        assert!(error.to_string().contains("error-atpmcp-tool-14"));
    }

    // -- A download's type: resolve_served ------------------------------

    /// The acceptance case: a host serving a PNG as octet-stream, which -04
    /// §11.8 allows, reports it as a PNG by the reference or by sniffing.
    #[test]
    fn an_octet_stream_png_is_reported_by_its_reference_or_its_bytes() {
        let by_reference = resolve_served(Some(OCTET_STREAM), Some("image/png"), Some("image/png"));
        assert_eq!(by_reference.value, "image/png");
        assert!(by_reference.disagreement.is_none());

        let by_bytes = resolve_served(Some(OCTET_STREAM), None, Some("image/png"));
        assert_eq!(by_bytes.value, "image/png");
        assert!(by_bytes.disagreement.is_none());
    }

    #[test]
    fn a_declared_type_stands_in_for_a_generic_one_when_the_bytes_say_nothing() {
        for served in [
            Some(OCTET_STREAM),
            Some("Application/Octet-Stream; charset=binary"),
            Some(""),
            None,
        ] {
            let decided = resolve_served(served, Some("text/plain"), None);
            assert_eq!(decided.value, "text/plain", "{served:?}");
            assert!(decided.disagreement.is_none());
        }
    }

    /// A type chosen in place of the host's is never one the bytes contradict.
    #[test]
    fn the_bytes_win_over_a_declared_type_they_contradict() {
        let decided = resolve_served(
            Some(OCTET_STREAM),
            Some("image/png"),
            Some("application/pdf"),
        );
        assert_eq!(decided.value, "application/pdf");
        let note = decided.disagreement.expect("the contradiction is reported");
        assert!(
            note.contains("image/png") && note.contains("application/pdf"),
            "{note}"
        );
    }

    #[test]
    fn a_specific_served_type_stands_and_a_declared_one_is_checked_against_it() {
        let alone = resolve_served(Some("image/jpeg"), None, None);
        assert_eq!(alone.value, "image/jpeg");
        assert!(alone.disagreement.is_none());

        let disagreeing = resolve_served(Some("image/jpeg"), Some("image/png"), Some("image/png"));
        assert_eq!(disagreeing.value, "image/jpeg");
        let note = disagreeing.disagreement.expect("reported, not refused");
        assert!(note.contains("the host served 'image/jpeg'"), "{note}");
        assert!(!note.contains("the bytes"), "the bytes agree: {note}");

        // Parameters, case and image/jpg are not disagreements.
        let agreeing = resolve_served(Some("IMAGE/JPEG; q=1"), Some("image/jpg"), None);
        assert!(agreeing.disagreement.is_none());
    }

    #[test]
    fn with_nothing_to_go_on_a_blob_is_octet_stream() {
        let decided = resolve_served(None, None, None);
        assert_eq!(decided.value, OCTET_STREAM);
        // A reference that says octet-stream, as §9.1 has it for an unknown
        // type, neither stands in for nor disagrees with anything.
        let generic = resolve_served(Some(OCTET_STREAM), Some(OCTET_STREAM), Some("image/gif"));
        assert_eq!(generic.value, "image/gif");
        assert!(generic.disagreement.is_none());
    }

    #[test]
    fn a_sniff_is_wanted_only_when_it_can_change_the_answer() {
        assert!(wants_sniff(None, None));
        assert!(wants_sniff(Some(OCTET_STREAM), None));
        assert!(wants_sniff(Some("image/png"), Some("image/png")));
        assert!(!wants_sniff(Some("image/png"), None));
        assert!(!wants_sniff(Some("image/png"), Some(OCTET_STREAM)));
    }

    #[test]
    fn a_declared_type_must_be_a_content_type() {
        for good in [
            "image/png",
            "text/plain; charset=utf-8",
            "application/vnd.ipld.car",
            "image/svg+xml",
        ] {
            assert!(check_declared(good).is_ok(), "{good}");
        }
        for bad in [
            "",
            "png",
            "image/",
            "/png",
            "image/png/x",
            "image /png",
            "image/png\n",
            "imäge/png",
        ] {
            let error = check_declared(bad).expect_err(bad);
            assert!(error.contains("'mime_type'"), "{error}");
        }
        assert!(check_declared(&format!("image/{}", "x".repeat(300))).is_err());
    }

    #[test]
    fn image_detection_ignores_parameters() {
        assert!(is_image("image/png"));
        assert!(is_image("IMAGE/JPEG; charset=binary"));
        assert!(!is_image("application/pdf"));
        assert!(!is_image("text/plain"));
    }
}