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
//! The resource surface: `resources/list`, `resources/templates/list`, and
//! `resources/read`.
//!
//! # Why `resources/list` is empty
//!
//! The obvious feature — listing the blobs this session has already fetched —
//! is forbidden twice over. The resources specification says the advertised
//! set **MUST NOT** vary "as a side effect of other requests on the
//! connection", and the base protocol says a connection is not a session at
//! all. It would also leak the model's tool history into the client's resource
//! picker.
//!
//! The only spec-legal version of a non-empty list here is an operator pin: a
//! configured set of DIDs enumerated through `com.atproto.sync.listBlobs`,
//! which is a function of configuration and upstream state rather than of this
//! connection's history. That is deliberately not built.
//!
//! Discovery happens through the template instead, which is what a template is
//! for: the blob namespace is unbounded and cannot be enumerated.

use std::sync::Arc;

use serde_json::Value;

use crate::blob::{BlobUri, Expected, Locator, URI_TEMPLATE};
use crate::context::ServerContext;
use crate::errors::{ProtocolError, ResourceError, ToolError};
use crate::proto::serve::RequestCtx;
use crate::proto::{CacheHints, JsonRpcResponse, complete};

/// The `resources/list` result.
#[must_use]
pub fn list(ctx: &Arc<ServerContext>) -> Value {
    complete(
        serde_json::json!({ "resources": [] }),
        Some(CacheHints::short_list()),
        &ctx.server_info,
    )
}

/// The `resources/templates/list` result.
#[must_use]
pub fn templates(ctx: &Arc<ServerContext>) -> Value {
    complete(
        serde_json::json!({
            "resourceTemplates": [
                {
                    "uriTemplate": URI_TEMPLATE,
                    "name": "atproto-blob",
                    "title": "AT Protocol blob",
                    "description": "A blob stored in an AT Protocol repository, addressed by repository DID and blob CID. Reading it fetches the bytes from the repository's PDS, verifies them against the CID, and caches them locally.",
                    // Honest: the real type is per-blob and unknown until read.
                    "mimeType": "application/octet-stream"
                }
            ]
        }),
        Some(CacheHints::constant()),
        &ctx.server_info,
    )
}

/// Handle a `resources/read` request.
pub async fn read(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    params: Option<Value>,
) -> JsonRpcResponse {
    let id = rctx.id.clone();

    let Some(uri) = params
        .as_ref()
        .and_then(|params| params.get("uri"))
        .and_then(Value::as_str)
    else {
        let error = ProtocolError::Malformed {
            reason: "the 'uri' parameter must be a string".to_string(),
        };
        return JsonRpcResponse::error(id, error.code(), error.to_string());
    };

    match read_blob(ctx, rctx, uri).await {
        Ok(contents) => JsonRpcResponse::success(
            id,
            complete(
                serde_json::json!({ "contents": [contents] }),
                Some(CacheHints::immutable_content()),
                &ctx.server_info,
            ),
        ),
        Err(error) => {
            // Never an empty `contents` array: the specification calls that
            // ambiguous, since it cannot be told apart from a resource that
            // exists and holds nothing.
            let data = match error.uri() {
                Some(uri) => serde_json::json!({ "uri": uri }),
                None => serde_json::json!({ "uri": uri }),
            };
            tracing::warn!(uri = %uri, error = %error, "Resource read failed.");
            JsonRpcResponse::error_with_data(id, error.code(), error.to_string(), data)
        }
    }
}

/// Fetch, verify, and encode one blob for a `resources/read` result.
async fn read_blob(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    uri: &str,
) -> Result<Value, ResourceError> {
    use base64::Engine as _;

    let parsed = BlobUri::parse(uri)?;

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

    // Nothing to expect: a resource URI names a DID and a CID and carries no
    // blob reference, so the bytes are checked against the CID alone, and an
    // `application/octet-stream` blob is reported by its sniffed type.
    let mut blob = crate::blob::fetch(
        ctx,
        rctx,
        &locator,
        &Expected::default(),
        ctx.limits.blob_max_download_bytes,
    )
    .await
    .map_err(|error| fetch_failure(uri, error))?;

    let size = blob.size;
    if size > ctx.limits.blob_max_inline_bytes {
        // A deliberate deviation from "read returns the bytes". The only
        // delivery mechanism here is base64 in a JSON-RPC response, and a
        // multi-megabyte one is a response no client can usefully handle.
        return Err(ResourceError::TooLarge {
            size,
            limit: ctx.limits.blob_max_inline_bytes,
        });
    }

    // At most `size` bytes, just checked against the inline ceiling, read
    // through the handle they were verified through and hashed again. A
    // failure is local, not a missing resource, so it is the cache failure,
    // `-32603`, where a read-back error used to be reported as not found.
    let data = blob
        .bytes()
        .await
        .map_err(|error| ResourceError::CacheFailure {
            reason: error.to_string(),
        })?;

    Ok(serde_json::json!({
        "uri": parsed.to_uri(),
        "mimeType": blob.mime_type,
        "blob": base64::engine::general_purpose::STANDARD.encode(&data),
    }))
}

/// The resource error for a fetch that failed.
///
/// A blob over the transfer ceiling is [`ResourceError::TooLargeToFetch`], not
/// the inline refusal. It was mapped to [`ResourceError::TooLarge`], which
/// reads "too large to inline" and gave the download ceiling as its limit, so
/// an operator raised `ATPMCP_BLOB_MAX_INLINE_BYTES` and nothing changed. The
/// tool side already told the two apart, as `tool-13` and `tool-17`. A cached
/// copy over the ceiling (`tool-13`, an exact size) and a download stopped at
/// it (`tool-20`, a lower bound) both land here, and "at least" is true of
/// either.
fn fetch_failure(uri: &str, error: ToolError) -> ResourceError {
    match error {
        ToolError::BlobTooLarge { size, limit }
        | ToolError::BlobDownloadTooLarge { size, limit } => {
            ResourceError::TooLargeToFetch { size, limit }
        }
        other => ResourceError::NotFound {
            uri: uri.to_string(),
            reason: other.to_string(),
        },
    }
}

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

    #[test]
    fn list_is_empty_and_cacheable() {
        let ctx = test_context();
        let result = list(&ctx);
        assert_eq!(result["resultType"], "complete");
        assert_eq!(result["resources"], serde_json::json!([]));
        assert_eq!(result["cacheScope"], "public");
        assert!(result["ttlMs"].as_u64().unwrap() > 0);
    }

    #[test]
    fn list_does_not_grow_when_the_cache_does() {
        // The invariant behind the "no session state" rule: nothing a previous
        // request did may change what this one advertises.
        let ctx = test_context();
        let before = list(&ctx);
        let after = list(&ctx);
        assert_eq!(before["resources"], after["resources"]);
    }

    #[test]
    fn templates_advertise_the_blob_uri_template() {
        let ctx = test_context();
        let result = templates(&ctx);
        assert_eq!(result["resultType"], "complete");
        let template = &result["resourceTemplates"][0];
        assert_eq!(template["uriTemplate"], URI_TEMPLATE);
        assert_eq!(template["mimeType"], "application/octet-stream");
        assert!(template["name"].is_string());
        assert!(template["description"].is_string());
    }

    #[tokio::test]
    async fn read_requires_a_uri() {
        let ctx = test_context();
        let mut rctx = test_request();
        let response = read(&ctx, &mut rctx, Some(serde_json::json!({}))).await;
        assert_eq!(response.error.unwrap().code, INVALID_PARAMS);
    }

    #[tokio::test]
    async fn a_malformed_uri_is_invalid_params_and_never_empty_contents() {
        let ctx = test_context();
        let mut rctx = test_request();
        let response = read(
            &ctx,
            &mut rctx,
            Some(serde_json::json!({ "uri": "atproto://public/blob/x/y" })),
        )
        .await;

        assert!(response.result.is_none(), "an error carries no result");
        let error = response.error.unwrap();
        assert_eq!(error.code, INVALID_PARAMS);
        assert_eq!(error.data.unwrap()["uri"], "atproto://public/blob/x/y");
    }

    #[tokio::test]
    async fn resource_not_found_never_uses_the_retired_code() {
        let ctx = test_context();
        let mut rctx = test_request();
        let response = read(
            &ctx,
            &mut rctx,
            Some(serde_json::json!({ "uri": "atpmcp://public/blob/did:plc:abc/nope" })),
        )
        .await;
        let code = response.error.unwrap().code;
        assert_eq!(code, INVALID_PARAMS);
        assert_ne!(code, -32002, "-32002 was retired by this revision");
    }

    #[tokio::test]
    async fn a_cached_blob_reads_back_as_base64_with_cache_hints() {
        let ctx = test_context_with_cache();
        let mut rctx = test_request();

        let data = b"a small cached blob".to_vec();
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache
            .put(&cid, &data, Some("text/plain"))
            .await
            .unwrap();

        let uri = BlobUri::new("did:plc:ewvi7nxzyoun6zhxrhs64oiz", &cid).to_uri();
        let response = read(&ctx, &mut rctx, Some(serde_json::json!({ "uri": uri }))).await;

        let result = response.result.expect("a cached blob reads back");
        assert_eq!(result["resultType"], "complete");
        assert_eq!(result["cacheScope"], "public");
        assert_eq!(result["ttlMs"], 86_400_000);

        let contents = result["contents"].as_array().unwrap();
        assert_eq!(contents.len(), 1, "exactly one entry per blob read");
        assert_eq!(contents[0]["uri"], uri);
        assert_eq!(contents[0]["mimeType"], "text/plain");

        use base64::Engine as _;
        let decoded = base64::engine::general_purpose::STANDARD
            .decode(contents[0]["blob"].as_str().unwrap())
            .unwrap();
        assert_eq!(decoded, data);

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

    /// The resource read goes through the same type decision as the tool:
    /// a blob recorded or served as octet-stream is reported by its bytes.
    #[tokio::test]
    async fn an_octet_stream_png_reads_back_as_image_png() {
        let ctx = test_context_with_cache();
        let mut rctx = 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(&[3u8; 16]);
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache
            .put(&cid, &data, Some("application/octet-stream"))
            .await
            .unwrap();

        let uri = BlobUri::new("did:plc:ewvi7nxzyoun6zhxrhs64oiz", &cid).to_uri();
        let response = read(&ctx, &mut rctx, Some(serde_json::json!({ "uri": uri }))).await;
        let result = response.result.expect("a cached blob reads back");
        assert_eq!(result["contents"][0]["mimeType"], "image/png");

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

    /// The finding: a blob over the *transfer* ceiling was reported as too
    /// large to inline, naming the transfer ceiling as the inline limit.
    #[test]
    fn a_blob_over_the_download_ceiling_is_not_reported_as_too_large_to_inline() {
        let error = fetch_failure(
            "atpmcp://public/blob/did:plc:x/bafkrei",
            ToolError::BlobTooLarge {
                size: 16_777_217,
                limit: 16_777_216,
            },
        );
        assert!(
            matches!(
                error,
                ResourceError::TooLargeToFetch {
                    size: 16_777_217,
                    limit: 16_777_216
                }
            ),
            "{error:?}"
        );
        assert_eq!(error.code(), INVALID_PARAMS);
        let message = error.to_string();
        assert!(message.starts_with("error-atpmcp-resource-6 "), "{message}");
        assert!(
            message.contains("ATPMCP_BLOB_MAX_DOWNLOAD_BYTES"),
            "{message}"
        );
        assert!(!message.contains("inline"), "{message}");
    }

    /// A download stopped at the ceiling is the transfer refusal too. Its
    /// size is a lower bound, which `resource-6` already says.
    #[test]
    fn a_download_stopped_at_the_ceiling_is_too_large_to_fetch() {
        let error = fetch_failure(
            "atpmcp://public/blob/did:plc:x/bafkrei",
            ToolError::BlobDownloadTooLarge {
                size: 16_842_752,
                limit: 16_777_216,
            },
        );
        assert!(
            matches!(
                error,
                ResourceError::TooLargeToFetch {
                    size: 16_842_752,
                    limit: 16_777_216
                }
            ),
            "{error:?}"
        );
        assert!(error.to_string().contains("at least 16842752 bytes"));
    }

    /// Every other fetch failure is still a missing resource, carrying why.
    #[test]
    fn any_other_fetch_failure_is_not_found() {
        let error = fetch_failure(
            "atpmcp://public/blob/did:plc:x/bafkrei",
            ToolError::BlobDownloadFailed {
                reason: "connection refused".to_string(),
            },
        );
        assert!(
            matches!(&error, ResourceError::NotFound { uri, reason }
                if uri == "atpmcp://public/blob/did:plc:x/bafkrei" && reason.contains("connection refused")),
            "{error:?}"
        );
    }

    /// A repository that answers "not found" makes the resource not found,
    /// with the answer as the reason. It used to reach here as `tool-12`, a
    /// CID mismatch, because the error body was hashed like a blob.
    #[test]
    fn an_error_answer_from_the_repository_is_not_found_with_its_status() {
        let error = fetch_failure(
            "atpmcp://public/blob/did:plc:x/bafkrei",
            ToolError::BlobErrorResponse {
                endpoint: "https://pds.example.com".to_string(),
                status: 400,
                body: r#"{"error":"BlobNotFound"}"#.to_string(),
            },
        );
        assert_eq!(error.code(), INVALID_PARAMS);
        let message = error.to_string();
        assert!(message.starts_with("error-atpmcp-resource-3 "), "{message}");
        assert!(message.contains("HTTP 400"), "{message}");
        assert!(message.contains("BlobNotFound"), "{message}");
    }

    /// `resources/read` of a cached blob over the download ceiling is the
    /// transfer refusal, `resource-6`, end to end. The hit used to be served
    /// whatever its size, and before that the refusal was reported as too
    /// large to inline.
    #[tokio::test]
    async fn a_cached_blob_over_the_download_ceiling_is_too_large_to_fetch() {
        let ctx = crate::tools::test_support::test_context_with_cache_and_limits(
            crate::context::Limits {
                blob_max_download_bytes: 1024,
                blob_max_inline_bytes: 1024,
                ..crate::context::Limits::default()
            },
        );
        let mut rctx = test_request();

        let data = vec![8u8; 4096];
        let cid = atproto_dasl::compute_raw_cid(&data).to_string();
        ctx.cache.put(&cid, &data, None).await.unwrap();

        let uri = BlobUri::new("did:plc:ewvi7nxzyoun6zhxrhs64oiz", &cid).to_uri();
        let response = read(&ctx, &mut rctx, Some(serde_json::json!({ "uri": uri }))).await;

        let error = response.error.expect("refused");
        assert_eq!(error.code, INVALID_PARAMS);
        assert!(
            error.message.starts_with("error-atpmcp-resource-6 "),
            "{}",
            error.message
        );
        assert!(
            error.message.contains("ATPMCP_BLOB_MAX_DOWNLOAD_BYTES"),
            "{}",
            error.message
        );

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

    #[tokio::test]
    async fn a_blob_over_the_inline_ceiling_is_refused_with_a_reason() {
        let ctx = test_context_with_cache();
        let mut rctx = 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 uri = BlobUri::new("did:plc:ewvi7nxzyoun6zhxrhs64oiz", &cid).to_uri();
        let response = read(&ctx, &mut rctx, Some(serde_json::json!({ "uri": uri }))).await;

        let error = response.error.expect("oversize reads are refused");
        assert_eq!(error.code, INVALID_PARAMS);
        assert!(error.message.contains("error-atpmcp-resource-5"));
        assert!(
            error.message.contains("ATPMCP_BLOB_MAX_INLINE_BYTES"),
            "the refusal names the ceiling that governs it: {}",
            error.message
        );

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