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
//! Structured error types for atpmcp operations.
//!
//! All errors follow the project convention of prefixed error codes
//! with descriptive messages: `error-atpmcp-{domain}-{number}`
//!
//! Four domains, distinguished by where they surface:
//!
//! - [`ToolError`] — a tool execution failure. Surfaces as an `isError: true`
//!   tool result, never as a JSON-RPC error, because the model can act on it.
//! - [`ResourceError`] — a `resources/read` failure. Surfaces as a JSON-RPC
//!   error, because a resource read has no result shape that can carry a
//!   failure.
//! - [`ProtocolError`] — a malformed or unsupported request. Surfaces as a
//!   JSON-RPC error before any handler runs.
//! - [`ConfigError`] — an environment variable the server cannot use. Surfaces
//!   before the server starts, as the reason it refuses to.
//!
//! Every error enum here is `#[non_exhaustive]`, which is the workspace rule for a public error
//! enum: a `match` outside the defining crate needs a wildcard arm, and a later release can then
//! name a new failure without the release being a breaking one. `atpmcp` ships a binary and no
//! library target, so nothing outside it can match on one of these today and the attribute binds
//! nothing. It is here so that the day this crate grows a `lib.rs` is not also the day its error
//! types become a semver promise.

use thiserror::Error;

use crate::proto::{INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, UNSUPPORTED_PROTOCOL_VERSION};

#[allow(clippy::enum_variant_names)] // each variant ends in *Failed by domain convention.
/// Errors that can occur during tool operations.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ToolError {
    /// DAG-CBOR serialization of the JSON value failed.
    #[error("error-atpmcp-tool-1 Failed to serialize record to DAG-CBOR: {reason}")]
    SerializationFailed {
        /// Description of the serialization failure.
        reason: String,
    },

    /// Lexicon schema validation failed.
    #[error("error-atpmcp-tool-2 Lexicon schema validation failed: {reason}")]
    ValidationFailed {
        /// Description of the validation failure.
        reason: String,
    },

    /// Handle resolution failed.
    #[error("error-atpmcp-tool-3 Handle resolution failed: {reason}")]
    HandleResolutionFailed {
        /// Description of the resolution failure.
        reason: String,
    },

    /// Identity resolution failed.
    #[error("error-atpmcp-tool-4 Identity resolution failed: {reason}")]
    IdentityResolutionFailed {
        /// Description of the resolution failure.
        reason: String,
    },

    /// Facet parsing failed.
    #[error("error-atpmcp-tool-5 Facet parsing failed: {reason}")]
    FacetParsingFailed {
        /// Description of the parsing failure.
        reason: String,
    },

    /// Record retrieval failed.
    #[error("error-atpmcp-tool-6 Record retrieval failed: {reason}")]
    RecordRetrievalFailed {
        /// Description of the retrieval failure.
        reason: String,
    },

    /// Lexicon retrieval failed.
    #[error("error-atpmcp-tool-7 Lexicon retrieval failed: {reason}")]
    LexiconRetrievalFailed {
        /// Description of the retrieval failure.
        reason: String,
    },

    /// XRPC request failed.
    #[error("error-atpmcp-tool-8 XRPC request failed: {reason}")]
    XrpcRequestFailed {
        /// Description of the request failure.
        reason: String,
    },

    /// XRPC parameter validation failed.
    #[error("error-atpmcp-tool-9 XRPC validation failed: {reason}")]
    XrpcValidationFailed {
        /// Description of the validation failure.
        reason: String,
    },

    /// Uploading a blob to a PDS failed.
    #[error("error-atpmcp-tool-10 Blob upload failed: {reason}")]
    BlobUploadFailed {
        /// Description of the upload failure.
        reason: String,
    },

    /// Downloading a blob from a PDS failed.
    #[error("error-atpmcp-tool-11 Blob download failed: {reason}")]
    BlobDownloadFailed {
        /// Description of the download failure.
        reason: String,
    },

    /// The bytes do not hash to the CID they were requested under.
    ///
    /// On a download this is a security control, not a sanity check: it is
    /// what makes it safe to fetch from a host named by a DID document the
    /// DID's own subject publishes.
    #[error("error-atpmcp-tool-12 Blob CID mismatch: requested {requested}, computed {computed}")]
    BlobCidMismatch {
        /// The CID the caller asked for.
        requested: String,
        /// The CID the bytes actually hash to.
        computed: String,
    },

    /// A caller-named host failed the service-endpoint policy.
    #[error(
        "error-atpmcp-tool-16 Endpoint refused by policy: {endpoint}: {reason}. Set ATPMCP_ALLOW_INSECURE_ENDPOINTS to allow it."
    )]
    EndpointRefused {
        /// The endpoint the caller named.
        endpoint: String,
        /// Why the policy refused it.
        reason: String,
    },

    /// A blob downloaded successfully but is too large to return inline.
    #[error(
        "error-atpmcp-tool-17 Blob too large to inline: {size} bytes exceeds {limit}. The bytes were downloaded; drop 'inline' to take the path of the verified file."
    )]
    BlobTooLargeToInline {
        /// Size of the blob in bytes.
        size: u64,
        /// The configured inline ceiling in bytes.
        limit: u64,
    },

    /// A blob whose size is known exceeds the size ceiling: an upload's
    /// source, a cached copy a download would have served, or the size a
    /// download's blob reference declares, refused before anything is read.
    ///
    /// A download stopped at the ceiling is [`Self::BlobDownloadTooLarge`]
    /// instead, because its size is not known.
    #[error("error-atpmcp-tool-13 Blob too large: {size} bytes exceeds limit {limit}")]
    BlobTooLarge {
        /// The blob's size in bytes, exactly.
        size: u64,
        /// The ceiling in bytes: the configured one, or a lower `max_bytes`.
        limit: u64,
    },

    /// A download was stopped at the size ceiling, before the whole blob
    /// arrived.
    ///
    /// Distinct from [`Self::BlobTooLarge`], whose size is exact. Here it is
    /// either the size the repository declared in `Content-Length`, which is
    /// never verified, or the count received when the read stopped. Both were
    /// reported as `tool-13` with the size given as the blob's, so a caller
    /// could retry with `max_bytes` set to it and be refused again.
    #[error(
        "error-atpmcp-tool-20 Blob too large to download: at least {size} bytes exceeds limit {limit}"
    )]
    BlobDownloadTooLarge {
        /// What the repository declared, or what arrived before the read
        /// stopped: a lower bound on the size, not the size.
        size: u64,
        /// The ceiling in bytes: the configured one, or a lower `max_bytes`.
        limit: u64,
    },

    /// A downloaded blob is not the size its blob reference declares.
    ///
    /// -04 §11.7 has a client verify a blob's "content hash and size". The
    /// CID fixes the bytes, so a whole, verified blob of another size means
    /// the reference is wrong. A read stopped past the declared size, or a
    /// `Content-Length` over it, cannot say which side is, and `actual` is
    /// then a lower bound.
    #[error(
        "error-atpmcp-tool-22 Blob size mismatch: the blob reference declares {declared} bytes, but {}",
        found_size(*.actual, *.at_least)
    )]
    BlobSizeMismatch {
        /// The size the caller passed, from the blob reference.
        declared: u64,
        /// The blob's size, or with `at_least` what the host declared or
        /// sent before the read stopped.
        actual: u64,
        /// Whether `actual` is only a lower bound.
        at_least: bool,
    },

    /// The service answered an XRPC call with a status outside 2xx.
    ///
    /// Distinct from [`Self::XrpcRequestFailed`], which is a call that got no
    /// usable answer at all: this one was answered, and the answer was no.
    #[error("error-atpmcp-tool-18 XRPC error response: HTTP {status}: {body}")]
    XrpcErrorResponse {
        /// The HTTP status the service answered with.
        status: u16,
        /// The response body as the service sent it, or a note that it sent none.
        body: String,
    },

    /// The repository answered a blob fetch with a status outside 2xx.
    ///
    /// Distinct from [`Self::BlobCidMismatch`]: an error answer is not the
    /// blob, so it is never hashed. It was, and a `400
    /// {"error":"BlobNotFound"}` was reported as a CID mismatch, the alarm
    /// for a repository that served the wrong bytes.
    #[error(
        "error-atpmcp-tool-19 Blob fetch error response: {endpoint} answered HTTP {status}: {body}"
    )]
    BlobErrorResponse {
        /// The endpoint the blob was requested from.
        endpoint: String,
        /// The HTTP status it answered with.
        status: u16,
        /// The start of the response body, or a note that it sent none.
        body: String,
    },

    /// A verified blob could not be read back as the bytes that were verified.
    ///
    /// An inline reply reads the file again, through the handle it was
    /// verified through, and hashes what it read. This is that read failing,
    /// or finding different bytes: the file was changed in place after it was
    /// verified. It used to be read back by path, unbounded and unchecked, so
    /// a file replaced in between was inlined as if it had been verified.
    #[error("error-atpmcp-tool-21 Could not read back the verified blob: {path}: {reason}")]
    BlobReadBackFailed {
        /// The file the blob was verified at.
        path: String,
        /// What went wrong: an I/O error, or what the bytes read back are.
        reason: String,
    },

    /// Neither a declared nor a sniffed content type was available.
    #[error(
        "error-atpmcp-tool-14 Could not determine content type from bytes; pass content_type explicitly"
    )]
    ContentTypeUndetermined,

    /// Reading or writing a local file failed.
    #[error("error-atpmcp-tool-15 Local file access failed: {path}: {reason}")]
    LocalFileFailed {
        /// The path that could not be used.
        path: String,
        /// Description of the failure.
        reason: String,
    },

    /// `generate_bsky_post` could not build a post: an argument it cannot
    /// use, or a record that does not validate against the bundled
    /// `app.bsky.feed.post` lexicon.
    #[error("error-atpmcp-tool-23 Post generation failed: {reason}")]
    PostGenerationFailed {
        /// What was wrong.
        reason: String,
    },

    /// `generate_bsky_post` could not read the page its `embed_external`
    /// names, so it has no card to write.
    ///
    /// Distinct from a missing thumbnail, which is not an error: a card
    /// without one is still a valid card, so the tool leaves it out and says
    /// why. A card without the page's title is not what the caller asked for.
    #[error("error-atpmcp-tool-24 Link card failed: {url}: {reason}")]
    LinkCardFailed {
        /// The page the card was for.
        url: String,
        /// Why it could not be read.
        reason: String,
    },

    /// `generate_bsky_post` could not use an image its `gallery` or `images`
    /// argument names, so the call made no post and uploaded nothing.
    ///
    /// Unlike a link card's thumbnail, which is left out when it cannot be
    /// had, these are images the caller asked for by name.
    #[error("error-atpmcp-tool-25 Image failed: {reason}")]
    ImageFailed {
        /// Which image, and why.
        reason: String,
    },
}

/// The second half of [`ToolError::BlobSizeMismatch`]'s message.
fn found_size(actual: u64, at_least: bool) -> String {
    if at_least {
        format!("the host sent at least {actual}")
    } else {
        format!("the blob is {actual}")
    }
}

/// Errors surfaced from the resource surface as JSON-RPC errors.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ResourceError {
    /// The URI does not parse as a resource this server serves.
    #[error("error-atpmcp-resource-1 Malformed resource URI: {uri}: {reason}")]
    MalformedUri {
        /// The offending URI.
        uri: String,
        /// Why it was rejected.
        reason: String,
    },

    /// The URI scheme or authority is not one this server serves.
    #[error("error-atpmcp-resource-2 Unsupported resource scheme: {uri}")]
    UnsupportedScheme {
        /// The offending URI.
        uri: String,
    },

    /// The resource does not exist upstream.
    #[error("error-atpmcp-resource-3 Resource not found: {uri}: {reason}")]
    NotFound {
        /// The URI that could not be read.
        uri: String,
        /// Why the read failed.
        reason: String,
    },

    /// The local blob cache could not be read or written.
    #[error("error-atpmcp-resource-4 Blob cache failure: {reason}")]
    CacheFailure {
        /// Description of the failure.
        reason: String,
    },

    /// The resource is too large to return inline as base64.
    #[error(
        "error-atpmcp-resource-5 Resource too large to inline: {size} bytes exceeds {limit}, the ATPMCP_BLOB_MAX_INLINE_BYTES ceiling"
    )]
    TooLarge {
        /// Size of the resource in bytes.
        size: u64,
        /// The configured inline ceiling in bytes.
        limit: u64,
    },

    /// The blob is larger than this server will fetch, so it was not fetched.
    ///
    /// Distinct from [`Self::TooLarge`] because the remedy is different: this
    /// one is the transfer ceiling, `ATPMCP_BLOB_MAX_DOWNLOAD_BYTES`, and
    /// reporting it as "too large to inline" sent an operator to raise the
    /// inline ceiling, which changes nothing.
    #[error(
        "error-atpmcp-resource-6 Resource too large to fetch: at least {size} bytes exceeds {limit}, the ATPMCP_BLOB_MAX_DOWNLOAD_BYTES ceiling"
    )]
    TooLargeToFetch {
        /// The size of a cached copy, or else what the repository declared or
        /// sent before the fetch stopped, which is a lower bound on the size.
        size: u64,
        /// The configured download ceiling in bytes.
        limit: u64,
    },
}

impl ResourceError {
    /// The JSON-RPC error code this failure is reported under.
    ///
    /// Note that a missing resource is `-32602`, not `-32002`: the 2026-07-28
    /// revision moved it, and reserved the old code so it can never be reused.
    #[must_use]
    pub fn code(&self) -> i64 {
        match self {
            Self::MalformedUri { .. }
            | Self::UnsupportedScheme { .. }
            | Self::NotFound { .. }
            | Self::TooLarge { .. }
            | Self::TooLargeToFetch { .. } => INVALID_PARAMS,
            Self::CacheFailure { .. } => INTERNAL_ERROR,
        }
    }

    /// The URI this failure concerns, for the error's `data` member.
    #[must_use]
    pub fn uri(&self) -> Option<&str> {
        match self {
            Self::MalformedUri { uri, .. }
            | Self::UnsupportedScheme { uri }
            | Self::NotFound { uri, .. } => Some(uri),
            Self::CacheFailure { .. } | Self::TooLarge { .. } | Self::TooLargeToFetch { .. } => {
                None
            }
        }
    }
}

/// Errors raised by the protocol layer: while validating a request, or when its handler fails.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ProtocolError {
    /// A required `_meta` field was absent.
    #[error("error-atpmcp-protocol-1 Missing required _meta field: {field}")]
    MissingMeta {
        /// The fully qualified `_meta` key that was absent.
        field: String,
    },

    /// The client asked for a protocol version this server does not implement.
    #[error("error-atpmcp-protocol-2 Unsupported protocol version: {requested}")]
    UnsupportedVersion {
        /// The version the client asked for.
        requested: String,
    },

    /// The request could not be understood.
    #[error("error-atpmcp-protocol-3 Malformed request: {reason}")]
    Malformed {
        /// Why the request was rejected.
        reason: String,
    },

    /// The message exceeded the configured line ceiling.
    #[error("error-atpmcp-protocol-4 Message exceeds {limit} bytes")]
    MessageTooLarge {
        /// The configured ceiling in bytes.
        limit: usize,
    },

    /// Too many requests are already in flight.
    #[error("error-atpmcp-protocol-5 Server busy: {inflight} requests in flight")]
    Busy {
        /// How many requests were in flight when this one arrived.
        inflight: usize,
    },

    /// A request's handler failed on the server's side, by panicking.
    #[error("error-atpmcp-protocol-6 Internal error: {reason}")]
    Internal {
        /// What failed.
        reason: String,
    },
}

impl ProtocolError {
    /// The JSON-RPC error code this failure is reported under.
    #[must_use]
    pub fn code(&self) -> i64 {
        match self {
            Self::MissingMeta { .. } | Self::Malformed { .. } => INVALID_PARAMS,
            Self::UnsupportedVersion { .. } => UNSUPPORTED_PROTOCOL_VERSION,
            Self::MessageTooLarge { .. } => INVALID_REQUEST,
            Self::Busy { .. } | Self::Internal { .. } => INTERNAL_ERROR,
        }
    }
}

/// An environment variable the server cannot use, and so will not start with.
///
/// Each of these used to be ignored in silence: a value that did not parse
/// kept the default, a value below a floor was raised to it, and a waiver
/// spelled any way but four was read as off. The case that mattered was an
/// operator lowering a ceiling -- `ATPMCP_BLOB_MAX_UPLOAD_BYTES=1M` -- who got
/// the 16 MiB default and no word about it. A server started by an MCP host
/// usually has its stderr out of sight, so a warning would have been nearly
/// as silent; refusing to start is not.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// A numeric variable holds something other than a whole number.
    #[error(
        "error-atpmcp-config-1 {name}={value:?} is not a whole number. Write it as digits alone, like its default of {default}"
    )]
    NotANumber {
        /// The variable.
        name: &'static str,
        /// What it held.
        value: String,
        /// The default, as an example of the accepted form.
        default: u64,
    },

    /// A numeric variable is below the smallest value the server can run with.
    #[error("error-atpmcp-config-2 {name}={value} is below its minimum of {minimum}")]
    BelowMinimum {
        /// The variable.
        name: &'static str,
        /// What it held.
        value: u64,
        /// The smallest value accepted.
        minimum: u64,
    },

    /// An on/off variable (the endpoint waiver, `ATPMCP_PRESERVE_EXIF`) holds a
    /// value that is neither on nor off.
    #[error(
        "error-atpmcp-config-3 {name}={value:?} is neither on nor off. Use 1, true, yes or on to turn it on, or 0, false, no, off or an empty value to leave it off"
    )]
    NotAWaiver {
        /// The variable.
        name: &'static str,
        /// What it held.
        value: String,
    },

    /// The PLC directory variable holds something no request URL can be
    /// built from: an empty value, one with no host, or one that is not a
    /// URL once `https://` is put in front of a bare hostname. Or one that
    /// builds the wrong URL: a scheme one slash short, `http:/x`, would be a
    /// host named `http`, so a `:` after the host must introduce a port.
    ///
    /// Well-formedness only. The operator's directory is trusted, so the
    /// endpoint policy is not applied to it; a plain-HTTP loopback directory
    /// is a valid setting.
    #[error(
        "error-atpmcp-config-4 {name}={value:?} is not a usable PLC directory: {reason}. Write a hostname, like plc.directory, or an http:// or https:// URL, like http://localhost:2582"
    )]
    NotAPlcDirectory {
        /// The variable.
        name: &'static str,
        /// What it held.
        value: String,
        /// What is wrong with it.
        reason: String,
    },

    /// The nameserver variable holds an entry that is not an IP address.
    ///
    /// It is read by `atproto_identity::config::DnsNameservers`, the parser
    /// every binary in the workspace that reads it shares, so the separator is
    /// the one that parser splits on.
    #[error(
        "error-atpmcp-config-5 {name}={value:?} is not a list of nameserver addresses: {entry:?} is not an IP address. Separate addresses with '{separator}', like 1.1.1.1{separator}8.8.8.8"
    )]
    NotANameserverList {
        /// The variable.
        name: &'static str,
        /// What it held.
        value: String,
        /// The entry that is not an address.
        entry: String,
        /// The character entries are separated by.
        separator: char,
    },
}