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
548
549
//! Identity tools: handle resolution, DID documents, and record retrieval.

use atproto_identity::model::Document;
use atproto_identity::plc::directory_base;
use atproto_identity::resolve::{InnerIdentityResolver, InputType, parse_input};
use serde_json::Value;

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

/// Build a resolver for an alternate PLC directory, when one was asked for.
///
/// Returns `None` when `plc_hostname` is already what `default_resolver`
/// would use, so the caller can keep using the shared resolver rather than
/// cloning one per request. Compared against `default_resolver`'s own
/// configured hostname, not the literal `"plc.directory"`: this process's
/// default is itself configurable (`PLC_HOSTNAME`, see
/// `crate::default_plc_hostname` in `main.rs`), and comparing against the
/// literal made the two hardcoded strings cancel out only by coincidence --
/// a deployment whose configured default is a self-hosted directory would
/// have silently used it even for a call that explicitly asked for the
/// literal public `plc.directory`, while a call that explicitly named that
/// same self-hosted default built a redundant (if harmless) extra clone.
///
/// The two are compared as the URLs the resolver would request
/// ([`directory_base`]), so `plc.directory` and `https://plc.directory/` are
/// one directory.
fn resolver_override(
    default_resolver: &InnerIdentityResolver,
    plc_hostname: &str,
) -> Option<InnerIdentityResolver> {
    (directory_base(plc_hostname) != directory_base(&default_resolver.plc_hostname)).then(|| {
        InnerIdentityResolver {
            dns_resolver: default_resolver.dns_resolver.clone(),
            http_client: default_resolver.http_client.clone(),
            plc_hostname: plc_hostname.to_string(),
        }
    })
}

/// The resolver for a call's `plc_directory_hostname`, when it names a
/// directory other than the configured one; `None` to use the shared one.
///
/// Only such a directory goes through the host policy. The configured one is
/// the operator's `PLC_HOSTNAME`, and the policy is for hosts a model names:
/// an operator can widen it and a prompt cannot, so the operator's own choice
/// is not held to it. It used to be, in this tool and `get_record` alone --
/// every other tool, `login` included, resolved through the same directory
/// unchecked -- so `PLC_HOSTNAME=http://localhost:2582` worked for
/// `resolve_handle_to_did` and was refused here. A call naming the configured
/// directory itself changes nothing, so it is not refused either.
///
/// # Errors
///
/// [`ToolError::EndpointRefused`] for a directory the policy refuses.
fn plc_resolver(
    default_resolver: &InnerIdentityResolver,
    requested: Option<&str>,
    limits: &crate::context::Limits,
) -> Result<Option<InnerIdentityResolver>, ToolError> {
    let Some(requested) = requested else {
        return Ok(None);
    };
    let Some(resolver) = resolver_override(default_resolver, requested) else {
        return Ok(None);
    };
    crate::host_policy::check_plc_hostname(limits, requested)?;
    Ok(Some(resolver))
}

/// Execute the `resolve_handle_to_did` tool.
///
/// An unverified handle is still answered, as the reference implementations
/// do, rather than refused: the result says so, and the model decides.
pub async fn resolve_handle_to_did(arguments: Value, resolver: &InnerIdentityResolver) -> Value {
    let Some(handle) = arguments.get("handle").and_then(Value::as_str) else {
        return tool_error("The 'handle' argument must be a string.");
    };

    match resolver.resolve(handle).await {
        Ok(document) => resolved_handle(handle, &document),
        Err(error) => {
            let tool_err = ToolError::HandleResolutionFailed {
                // `{:#}`, not `to_string()`: atproto-identity's HTTP errors
                // carry their cause as a source, so the top line alone says a
                // request failed and not why.
                reason: format!("{error:#}"),
            };
            tracing::error!(error = ?error, handle = %handle, "Handle resolution failed.");
            tool_error(&tool_err.to_string())
        }
    }
}

/// The `resolve_handle_to_did` result for a subject that resolved to `document`.
///
/// For a handle, `verified` says whether the document lists `at://<handle>` in
/// `alsoKnownAs`, and an unverified result says so in its text too, for a
/// client that reads only that. A DID has no handle to confirm and passes
/// through, as it does in `IdentityResolver::resolve_verified`.
fn resolved_handle(subject: &str, document: &Document) -> Value {
    let did = document.id.as_str();
    let Ok(InputType::Handle(handle)) = parse_input(subject) else {
        return tool_structured(
            did,
            serde_json::json!({ "did": did, "verified": true }),
            vec![],
        );
    };

    let verified = document.confirms_handle(&handle);
    let summary = if verified {
        did.to_string()
    } else {
        format!("{did} (unverified: its DID document does not list at://{handle})")
    };
    tool_structured(
        &summary,
        serde_json::json!({ "did": did, "handle": handle, "verified": verified }),
        vec![],
    )
}

/// Execute the `resolve_identity` tool.
///
/// The PLC directory is, in order: the call's own `plc_directory_hostname`
/// argument if it gave one, else this process's configured default (the
/// `PLC_HOSTNAME` environment variable, else `plc.directory` -- see
/// `crate::default_plc_hostname` in `main.rs`). A directory the call names,
/// other than the configured one, goes through
/// [`crate::host_policy::check_plc_hostname`] before anything resolves
/// through it; see [`plc_resolver`].
pub async fn resolve_identity(
    arguments: Value,
    default_resolver: &InnerIdentityResolver,
    limits: &crate::context::Limits,
) -> Value {
    let Some(did) = arguments.get("did").and_then(Value::as_str) else {
        return tool_error("The 'did' argument must be a string.");
    };

    // A caller-named directory, checked before anything resolves through it.
    let requested = arguments
        .get("plc_directory_hostname")
        .and_then(Value::as_str);
    let override_resolver = match plc_resolver(default_resolver, requested, limits) {
        Ok(resolver) => resolver,
        Err(error) => return tool_error(&error.to_string()),
    };
    let resolver = override_resolver.as_ref().unwrap_or(default_resolver);

    match resolver.resolve(did).await {
        Ok(document) => match serde_json::to_string(&document) {
            Ok(json) => tool_success(&json),
            Err(error) => {
                let tool_err = ToolError::IdentityResolutionFailed {
                    reason: error.to_string(),
                };
                tracing::error!(error = ?error, "Failed to serialize DID document.");
                tool_error(&tool_err.to_string())
            }
        },
        Err(error) => {
            let tool_err = ToolError::IdentityResolutionFailed {
                // With the chain: the cause is a source, not in the top line.
                reason: format!("{error:#}"),
            };
            tracing::error!(error = ?error, did = %did, "Identity resolution failed.");
            tool_error(&tool_err.to_string())
        }
    }
}

/// Execute the `get_record` tool.
///
/// The PLC directory follows the same precedence as [`resolve_identity`]: the
/// call's own `plc_directory_hostname` argument, else this process's
/// configured default, and only the first is policy-checked. The record itself
/// is fetched with `http_client`, the server's request client, which follows
/// no redirects.
pub async fn get_record(
    arguments: Value,
    default_resolver: &InnerIdentityResolver,
    http_client: &reqwest::Client,
    limits: &crate::context::Limits,
) -> Value {
    let Some(uri) = arguments.get("uri").and_then(Value::as_str) else {
        return tool_error("The 'uri' argument must be a string.");
    };

    let cid = arguments.get("cid").and_then(Value::as_str);

    let aturi = match uri.parse::<atproto_record::aturi::ATURI>() {
        Ok(aturi) => aturi,
        Err(error) => {
            let tool_err = ToolError::RecordRetrievalFailed {
                reason: format!("Invalid AT-URI: {error}"),
            };
            tracing::error!(error = ?error, uri = %uri, "Failed to parse AT-URI.");
            return tool_error(&tool_err.to_string());
        }
    };

    // A caller-named directory, checked before anything resolves through it.
    let requested = arguments
        .get("plc_directory_hostname")
        .and_then(Value::as_str);
    let override_resolver = match plc_resolver(default_resolver, requested, limits) {
        Ok(resolver) => resolver,
        Err(error) => return tool_error(&error.to_string()),
    };
    let resolver = override_resolver.as_ref().unwrap_or(default_resolver);

    let document = match resolver.resolve(&aturi.authority).await {
        Ok(document) => document,
        Err(error) => {
            let tool_err = ToolError::RecordRetrievalFailed {
                reason: format!("Failed to resolve identity: {error:#}"),
            };
            tracing::error!(error = ?error, authority = %aturi.authority, "Identity resolution failed.");
            return tool_error(&tool_err.to_string());
        }
    };

    // A `serviceEndpoint` is published by the DID subject, so it is
    // attacker-controlled. The validated form rejects non-https, address
    // literals, embedded credentials and non-default ports, and the waiver
    // never reaches it: see `host_policy`.
    let pds_url = match crate::host_policy::pds_endpoint(&document, false) {
        Ok(pds_url) => pds_url,
        Err(unusable) => {
            let tool_err = ToolError::RecordRetrievalFailed {
                reason: unusable.tool_reason(&aturi.authority, None),
            };
            tracing::error!(did = %aturi.authority, ?unusable, "No usable PDS endpoint.");
            return tool_error(&tool_err.to_string());
        }
    };

    match atproto_client::com::atproto::repo::get_record(
        http_client,
        &atproto_client::client::Auth::None,
        &pds_url,
        &aturi.authority,
        &aturi.collection,
        &aturi.record_key,
        cid,
    )
    .await
    {
        Ok(atproto_client::com::atproto::repo::GetRecordResponse::Record { value, .. }) => {
            match serde_json::to_string(&value) {
                Ok(json) => tool_success(&json),
                Err(error) => {
                    let tool_err = ToolError::RecordRetrievalFailed {
                        reason: error.to_string(),
                    };
                    tracing::error!(error = ?error, "Failed to serialize record.");
                    tool_error(&tool_err.to_string())
                }
            }
        }
        Ok(atproto_client::com::atproto::repo::GetRecordResponse::Error(err)) => {
            let error_str = err.error.as_deref().unwrap_or("unknown");
            let message_str = err.message.as_deref().unwrap_or("unknown");
            let tool_err = ToolError::RecordRetrievalFailed {
                reason: format!("{error_str}: {message_str}"),
            };
            tracing::error!(error = %error_str, message = %message_str, "Record retrieval returned error.");
            tool_error(&tool_err.to_string())
        }
        Err(error) => {
            let tool_err = ToolError::RecordRetrievalFailed {
                // With the chain: the cause is a source, not in the top line.
                reason: format!("{error:#}"),
            };
            tracing::error!(error = ?error, uri = %uri, "Record retrieval failed.");
            tool_error(&tool_err.to_string())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::Limits;
    use crate::tools::test_support::{create_test_resolver, test_request_client};

    /// A resolver whose configured default is a self-hosted directory, not
    /// the public one -- standing in for a deployment with `PLC_HOSTNAME` set.
    fn resolver_with_default(plc_hostname: &str) -> InnerIdentityResolver {
        InnerIdentityResolver {
            plc_hostname: plc_hostname.to_string(),
            ..create_test_resolver()
        }
    }

    /// The regression: a call that explicitly names the literal public
    /// `plc.directory` must not be silently redirected to a self-hosted
    /// configured default just because the comparison was against the
    /// literal instead of that default.
    #[test]
    fn resolver_override_honours_an_explicit_public_directory_over_a_self_hosted_default() {
        let default_resolver = resolver_with_default("plc.example.internal");
        let overridden = resolver_override(&default_resolver, "plc.directory")
            .expect("an explicit plc.directory must override a different configured default");
        assert_eq!(overridden.plc_hostname, "plc.directory");
    }

    /// A call that names the deployment's own configured default -- whatever
    /// it is -- reuses the shared resolver rather than cloning an equivalent
    /// one.
    #[test]
    fn resolver_override_is_none_when_the_hostname_matches_the_configured_default() {
        let default_resolver = resolver_with_default("plc.example.internal");
        assert!(resolver_override(&default_resolver, "plc.example.internal").is_none());
    }

    /// Same, for the common case where the configured default is itself the
    /// public directory.
    #[test]
    fn resolver_override_is_none_for_the_public_directory_when_that_is_the_default() {
        let default_resolver = create_test_resolver();
        assert!(resolver_override(&default_resolver, "plc.directory").is_none());
    }

    /// A hostname that differs from the configured default, whatever that
    /// default is, still builds an override.
    #[test]
    fn resolver_override_is_built_for_a_hostname_unlike_the_configured_default() {
        let default_resolver = resolver_with_default("plc.example.internal");
        let overridden = resolver_override(&default_resolver, "mirror.example")
            .expect("a hostname unlike the default should override");
        assert_eq!(overridden.plc_hostname, "mirror.example");
    }

    /// A directory spelled with its scheme is the same directory.
    #[test]
    fn resolver_override_compares_directories_not_spellings() {
        let default_resolver = create_test_resolver();
        for same in [
            "https://plc.directory",
            "https://plc.directory/",
            "plc.directory/",
        ] {
            assert!(
                resolver_override(&default_resolver, same).is_none(),
                "{same} is the configured directory"
            );
        }
    }

    /// The operator's directory is not held to the policy, whoever names it.
    /// `PLC_HOSTNAME=http://localhost:2582` is a local directory an operator
    /// chose, and was refused by `resolve_identity` and `get_record` alone.
    #[test]
    fn the_configured_directory_is_not_policy_checked() {
        let default_resolver = resolver_with_default("http://localhost:2582");
        let limits = Limits::default();

        assert!(
            plc_resolver(&default_resolver, None, &limits)
                .expect("no argument")
                .is_none()
        );
        assert!(
            plc_resolver(&default_resolver, Some("http://localhost:2582/"), &limits)
                .expect("naming the configured directory changes nothing")
                .is_none()
        );
    }

    /// A different directory named by the caller is checked, and one given
    /// with a scheme is checked as written.
    #[test]
    fn a_caller_named_directory_is_policy_checked() {
        let default_resolver = create_test_resolver();
        let limits = Limits::default();

        let overridden = plc_resolver(&default_resolver, Some("https://plc.example.com"), &limits)
            .expect("an https directory passes")
            .expect("and overrides the configured one");
        assert_eq!(overridden.plc_hostname, "https://plc.example.com");

        for refused in ["http://localhost:2582", "169.254.169.254", "localhost"] {
            let Err(error) = plc_resolver(&default_resolver, Some(refused), &limits) else {
                panic!("{refused} should be refused");
            };
            assert!(
                error.to_string().starts_with("error-atpmcp-tool-16 "),
                "{refused}: {error}"
            );
        }
    }

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

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

    fn document_for(did: &str, also_known_as: &[&str]) -> Document {
        also_known_as
            .iter()
            .fold(
                atproto_identity::model::DocumentBuilder::new().id(did.to_string()),
                |builder, alias| builder.add_also_known_as(*alias),
            )
            .build()
            .unwrap()
    }

    #[test]
    fn a_handle_its_did_claims_back_is_verified() {
        let document = document_for(
            "did:plc:z3f2222fa222f5c33c2f27ez",
            &["at://alice.example.com"],
        );
        let result = resolved_handle("@Alice.Example.com", &document);
        assert_eq!(result["isError"], false);
        assert_eq!(
            result["structuredContent"],
            serde_json::json!({
                "did": "did:plc:z3f2222fa222f5c33c2f27ez",
                "handle": "alice.example.com",
                "verified": true,
            })
        );
        assert_eq!(
            result["content"][0]["text"],
            "did:plc:z3f2222fa222f5c33c2f27ez"
        );
    }

    #[test]
    fn a_handle_its_did_does_not_claim_is_reported_unverified() {
        let document = document_for(
            "did:plc:z3f2222fa222f5c33c2f27ez",
            &["at://someone-else.example.com"],
        );
        let result = resolved_handle("alice.example.com", &document);
        assert_eq!(result["isError"], false);
        assert_eq!(result["structuredContent"]["verified"], false);
        assert_eq!(
            result["structuredContent"]["did"],
            "did:plc:z3f2222fa222f5c33c2f27ez"
        );
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("unverified")
        );
    }

    #[test]
    fn a_did_passes_through() {
        let document = document_for("did:plc:z3f2222fa222f5c33c2f27ez", &[]);
        let result = resolved_handle("did:plc:z3f2222fa222f5c33c2f27ez", &document);
        assert_eq!(
            result["structuredContent"],
            serde_json::json!({ "did": "did:plc:z3f2222fa222f5c33c2f27ez", "verified": true })
        );
    }

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

    #[tokio::test]
    async fn resolve_identity_rejects_a_non_string_did() {
        let resolver = create_test_resolver();
        assert_eq!(
            resolve_identity(
                serde_json::json!({ "did": 123 }),
                &resolver,
                &Limits::default()
            )
            .await["isError"],
            true
        );
    }

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

    #[tokio::test]
    async fn get_record_rejects_a_non_string_uri() {
        let resolver = create_test_resolver();
        assert_eq!(
            get_record(
                serde_json::json!({ "uri": 123 }),
                &resolver,
                &test_request_client(),
                &Limits::default()
            )
            .await["isError"],
            true
        );
    }

    #[tokio::test]
    async fn get_record_rejects_a_malformed_at_uri() {
        let resolver = create_test_resolver();
        let result = get_record(
            serde_json::json!({ "uri": "not-an-aturi" }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("error-atpmcp-tool-6")
        );
    }
}