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
//! Local tools: CID computation, TID generation, and facet parsing.

use atproto_identity::resolve::InnerIdentityResolver;
use atproto_record::tid::Tid;
use serde_json::Value;

use crate::errors::ToolError;
use crate::tools::{optional_whole_number, tool_error, tool_success};

/// Execute the `create_record_cid` tool.
#[must_use]
pub fn create_record_cid(arguments: Value) -> Value {
    let record = arguments.get("record").cloned().unwrap_or(Value::Null);

    if !record.is_object() {
        return tool_error("The 'record' argument must be a JSON object.");
    }

    // The record is AT Protocol JSON, so `{"$link": ...}` and `{"$bytes": ...}`
    // are data-model sentinels, not maps. `compute_cid_from_json` lifts them to
    // tag-42 links and byte strings before encoding, which is what a repository
    // hashed. Encoding the `Value` directly would hash them as plain maps.
    match atproto_dasl::compute_cid_from_json(&record) {
        Ok(cid) => tool_success(&cid.to_string()),
        Err(error) => {
            let tool_err = ToolError::SerializationFailed {
                reason: error.to_string(),
            };
            tracing::error!(error = ?error, "DAG-CBOR serialization failed.");
            tool_error(&tool_err.to_string())
        }
    }
}

/// Execute the `generate_tid` tool.
///
/// `timestamp_micros` is range-checked here, before [`Tid::new_with_time`]
/// sees it, because that function panics above
/// [`Tid::MAX_TIMESTAMP_MICROS`]. The panic was caught by the request
/// supervisor and answered as `-32603 error-atpmcp-protocol-6`, a protocol
/// error a model cannot act on, for an input as ordinary as a timestamp in
/// nanoseconds.
#[must_use]
pub fn generate_tid(arguments: Value) -> Value {
    let count = match optional_whole_number(&arguments, "count") {
        Ok(count) => count.unwrap_or(1),
        Err(message) => return tool_error(&message),
    };

    if count == 0 || count > MAX_TID_COUNT {
        return tool_error(&format!(
            "The 'count' argument must be between 1 and {MAX_TID_COUNT}."
        ));
    }

    let timestamp_micros = match optional_whole_number(&arguments, "timestamp_micros") {
        Ok(timestamp) => timestamp,
        Err(message) => return tool_error(&message),
    };

    if let Some(timestamp) = timestamp_micros
        && timestamp > Tid::MAX_TIMESTAMP_MICROS
    {
        return tool_error(&format!(
            "The 'timestamp_micros' argument must be at most {}, the largest timestamp a TID can \
             hold (in the year 2255); {timestamp} is past it. It is in microseconds: a value this \
             large is often nanoseconds, which are 1000 times larger.",
            Tid::MAX_TIMESTAMP_MICROS
        ));
    }

    let tids: Vec<String> = (0..count)
        .map(|_| {
            let tid = match timestamp_micros {
                Some(timestamp) => Tid::new_with_time(timestamp),
                None => Tid::new(),
            };
            tid.to_string()
        })
        .collect();

    if tids.len() == 1 {
        tool_success(&tids[0])
    } else {
        tool_success(&tids.join("\n"))
    }
}

/// The most TIDs one `generate_tid` call returns.
pub const MAX_TID_COUNT: u64 = 100;

/// Execute the `parse_facets` tool.
pub async fn parse_facets(arguments: Value, resolver: &InnerIdentityResolver) -> Value {
    let Some(text) = arguments.get("text").and_then(Value::as_str) else {
        return tool_error("The 'text' argument must be a string.");
    };

    let limits = atproto_extras::FacetLimits::default();

    match atproto_extras::parse_facets_from_text(text, resolver, &limits).await {
        Some(facets) => match serde_json::to_string(&facets) {
            Ok(json) => tool_success(&json),
            Err(error) => {
                let tool_err = ToolError::FacetParsingFailed {
                    reason: error.to_string(),
                };
                tracing::error!(error = ?error, "Failed to serialize facets.");
                tool_error(&tool_err.to_string())
            }
        },
        None => tool_success("[]"),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tools::test_support::create_test_resolver;

    #[test]
    fn create_record_cid_success() {
        let args = serde_json::json!({
            "record": {
                "$type": "app.bsky.feed.post",
                "text": "Hello, world!",
                "createdAt": "2024-01-01T00:00:00.000Z"
            }
        });
        let result = create_record_cid(args);
        assert_eq!(result["isError"], false);
        let cid = result["content"][0]["text"].as_str().unwrap();
        assert!(cid.starts_with("bafy"));
    }

    /// A post with an image blob, captured from Jetstream with the CID its
    /// repository published (`atproto-jetstream/tests/fixtures/v2/commit_with_blob.json`).
    /// The blob's `ref` is a `$link`, so this only matches when the link is
    /// encoded as a CID rather than as a one-key map.
    #[test]
    fn create_record_cid_encodes_link_sentinels_as_cids() {
        let args = serde_json::json!({
            "record": {
                "$type": "app.bsky.feed.post",
                "createdAt": "2026-08-19T13:51:15.388Z",
                "embed": {
                    "$type": "app.bsky.embed.images",
                    "images": [{
                        "alt": "",
                        "image": {
                            "$type": "blob",
                            "mimeType": "image/jpeg",
                            "ref": {"$link": "bafkreifqmr7cv5il64qpgvy7smwd6llou4uvfjiaok2qiqgjv4idflb5ty"},
                            "size": 232033
                        }
                    }]
                },
                "text": "[F]Ig[U]Re:Re!!"
            }
        });
        let result = create_record_cid(args);
        assert_eq!(result["isError"], false);
        assert_eq!(
            result["content"][0]["text"],
            "bafyreicupfyigj4xq5cwa4q7pt2mg5lx2ct7luuwevw7n3nhutbhhx2ra4"
        );
    }

    #[test]
    fn create_record_cid_is_deterministic() {
        let args = serde_json::json!({ "record": { "a": 1, "b": "two" } });
        let first = create_record_cid(args.clone());
        let second = create_record_cid(args);
        assert_eq!(first["content"][0]["text"], second["content"][0]["text"]);
    }

    #[test]
    fn create_record_cid_differs_for_different_inputs() {
        let first = create_record_cid(serde_json::json!({ "record": { "a": 1 } }));
        let second = create_record_cid(serde_json::json!({ "record": { "a": 2 } }));
        assert_ne!(first["content"][0]["text"], second["content"][0]["text"]);
    }

    #[test]
    fn create_record_cid_rejects_a_non_object() {
        let result = create_record_cid(serde_json::json!({ "record": "not an object" }));
        assert_eq!(result["isError"], true);
    }

    #[test]
    fn create_record_cid_rejects_a_missing_record() {
        let result = create_record_cid(serde_json::json!({}));
        assert_eq!(result["isError"], true);
    }

    #[test]
    fn generate_tid_defaults_to_one() {
        let result = generate_tid(serde_json::json!({}));
        assert_eq!(result["isError"], false);
        let tid = result["content"][0]["text"].as_str().unwrap();
        assert_eq!(tid.len(), 13);
    }

    #[test]
    fn generate_tid_honours_count() {
        let result = generate_tid(serde_json::json!({ "count": 5 }));
        assert_eq!(result["isError"], false);
        let tids: Vec<&str> = result["content"][0]["text"]
            .as_str()
            .unwrap()
            .lines()
            .collect();
        assert_eq!(tids.len(), 5);
        assert!(tids.iter().all(|tid| tid.len() == 13));
    }

    #[test]
    fn generate_tid_accepts_a_timestamp() {
        let result =
            generate_tid(serde_json::json!({ "timestamp_micros": 1_704_067_200_000_000u64 }));
        assert_eq!(result["isError"], false);
        assert_eq!(result["content"][0]["text"].as_str().unwrap().len(), 13);
    }

    #[test]
    fn generate_tid_rejects_zero() {
        assert_eq!(
            generate_tid(serde_json::json!({ "count": 0 }))["isError"],
            true
        );
    }

    #[test]
    fn generate_tid_rejects_more_than_the_maximum() {
        assert_eq!(
            generate_tid(serde_json::json!({ "count": 101 }))["isError"],
            true
        );
    }

    fn text(result: &Value) -> &str {
        result["content"][0]["text"].as_str().expect("a text block")
    }

    /// The finding: a timestamp a TID cannot hold reached `Tid::new_with_time`,
    /// which panics, and the call was answered as a protocol error. A timestamp
    /// in nanoseconds is the ordinary way to get there.
    #[test]
    fn generate_tid_refuses_a_timestamp_past_the_largest_a_tid_can_hold() {
        for timestamp in [
            Tid::MAX_TIMESTAMP_MICROS + 1,
            1_704_067_200_000_000_000, // 2024-01-01 in nanoseconds
            u64::MAX,
        ] {
            let result = generate_tid(serde_json::json!({ "timestamp_micros": timestamp }));
            assert_eq!(result["isError"], true, "{timestamp}");
            let message = text(&result);
            assert!(
                message.contains(&Tid::MAX_TIMESTAMP_MICROS.to_string()),
                "the refusal states the maximum: {message}"
            );
            assert!(message.contains("nanoseconds"), "{message}");
        }
    }

    #[test]
    fn generate_tid_accepts_the_largest_timestamp_a_tid_can_hold() {
        let result =
            generate_tid(serde_json::json!({ "timestamp_micros": Tid::MAX_TIMESTAMP_MICROS }));
        assert_eq!(result["isError"], false);
        let tid = Tid::decode(text(&result)).expect("a TID");
        assert_eq!(tid.timestamp_micros(), Tid::MAX_TIMESTAMP_MICROS);
    }

    /// A `count` that is not a whole number used to become 1 without a word.
    #[test]
    fn generate_tid_refuses_a_count_that_is_not_a_whole_number() {
        for count in [
            serde_json::json!("5"),
            serde_json::json!(-1),
            serde_json::json!(5.5),
            serde_json::json!(true),
        ] {
            let result = generate_tid(serde_json::json!({ "count": count }));
            assert_eq!(result["isError"], true, "{count}");
            assert!(text(&result).contains("'count'"), "{}", text(&result));
        }
    }

    /// A `timestamp_micros` that is not a whole number used to become the
    /// current time, so a caller asking for a backdated TID got today's.
    #[test]
    fn generate_tid_refuses_a_timestamp_that_is_not_a_whole_number() {
        for timestamp in [
            serde_json::json!("1704067200000000"),
            serde_json::json!(-1),
            serde_json::json!(1.5),
        ] {
            let result = generate_tid(serde_json::json!({ "timestamp_micros": timestamp }));
            assert_eq!(result["isError"], true, "{timestamp}");
            assert!(
                text(&result).contains("'timestamp_micros'"),
                "{}",
                text(&result)
            );
        }
    }

    /// JSON Schema's `integer` includes a number with a zero fractional part,
    /// so `5.0` is five, not a refusal and not one.
    #[test]
    fn generate_tid_reads_a_whole_number_written_with_a_fraction() {
        let result = generate_tid(serde_json::json!({
            "count": 5.0,
            "timestamp_micros": 1_704_067_200_000_000.0,
        }));
        assert_eq!(result["isError"], false, "{result}");
        let tids: Vec<&str> = text(&result).lines().collect();
        assert_eq!(tids.len(), 5);
        for tid in tids {
            assert_eq!(
                Tid::decode(tid).expect("a TID").timestamp_micros(),
                1_704_067_200_000_000
            );
        }
    }

    /// `null` is how many clients spell an argument they are not setting.
    #[test]
    fn generate_tid_reads_null_as_absent() {
        let result = generate_tid(serde_json::json!({ "count": null, "timestamp_micros": null }));
        assert_eq!(result["isError"], false, "{result}");
        assert_eq!(text(&result).len(), 13);
    }

    #[tokio::test]
    async fn parse_facets_requires_text() {
        let resolver = create_test_resolver();
        assert_eq!(
            parse_facets(serde_json::json!({}), &resolver).await["isError"],
            true
        );
    }

    #[tokio::test]
    async fn parse_facets_rejects_non_string_text() {
        let resolver = create_test_resolver();
        assert_eq!(
            parse_facets(serde_json::json!({ "text": 123 }), &resolver).await["isError"],
            true
        );
    }

    #[tokio::test]
    async fn parse_facets_returns_an_empty_array_for_plain_text() {
        let resolver = create_test_resolver();
        let result = parse_facets(serde_json::json!({ "text": "" }), &resolver).await;
        assert_eq!(result["isError"], false);
        assert_eq!(result["content"][0]["text"], "[]");
    }

    #[tokio::test]
    async fn parse_facets_finds_a_url() {
        let resolver = create_test_resolver();
        let result = parse_facets(
            serde_json::json!({ "text": "Check out https://example.com" }),
            &resolver,
        )
        .await;
        assert_eq!(result["isError"], false);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("example.com")
        );
    }

    #[tokio::test]
    async fn parse_facets_finds_a_hashtag() {
        let resolver = create_test_resolver();
        let result = parse_facets(serde_json::json!({ "text": "Hello #atproto" }), &resolver).await;
        assert_eq!(result["isError"], false);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("atproto")
        );
    }

    /// A mention that does not resolve is dropped, and the rest still parses.
    ///
    /// This is the behaviour the tool's description promises, checked through
    /// the tool rather than through `atproto-extras`, because the description
    /// and the function it delegates to are in different crates and drifted
    /// apart once already.
    ///
    /// `.invalid` is reserved by RFC 2606 and resolves nowhere, so the handle
    /// is syntactically valid -- the mention scanner finds it -- and the
    /// resolution then fails without depending on what does or does not exist
    /// on the live network.
    #[tokio::test]
    async fn parse_facets_omits_a_mention_it_cannot_resolve() {
        let text = "Hi @nobody.example.invalid see https://example.com";

        // Without this the test is vacuous: if the scanner stopped recognising
        // the handle, nothing would be dropped for want of a DID and the
        // assertion below would still hold.
        let spans = atproto_extras::parse_mention_spans(text);
        assert_eq!(
            spans
                .iter()
                .map(|span| span.handle.as_str())
                .collect::<Vec<_>>(),
            vec!["nobody.example.invalid"],
            "the mention must be found before resolution can drop it"
        );

        let resolver = create_test_resolver();
        let result = parse_facets(serde_json::json!({ "text": text }), &resolver).await;

        assert_eq!(result["isError"], false);
        let facets: Vec<serde_json::Value> =
            serde_json::from_str(result["content"][0]["text"].as_str().unwrap())
                .expect("the tool returns a JSON array of facets");

        let kinds: Vec<&str> = facets
            .iter()
            .filter_map(|facet| facet["features"][0]["$type"].as_str())
            .collect();
        assert_eq!(
            kinds,
            vec!["app.bsky.richtext.facet#link"],
            "only the link should survive: {facets:?}"
        );
    }
}