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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! The `invoke_xrpc` tool: JSON in, JSON out.
//!
//! Binary payloads are deliberately not handled here. `uploadBlob` sends raw
//! bytes under the blob's own `Content-Type` and `getBlob` answers with
//! binary, neither of which survives a JSON transport — those live in
//! [`crate::tools::blob`].

use atproto_client::client::{AppPasswordAuth, MAX_JSON_RESPONSE_BYTES};
use atproto_identity::resolve::InnerIdentityResolver;
use atproto_identity::url::build_url;
use futures::StreamExt;
use reqwest::StatusCode;
use reqwest::header::{HeaderMap, HeaderValue};
use serde_json::Value;

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

/// Encode a `params` object as XRPC query parameters.
///
/// The lexicon specification allows a `params` property to be a `boolean`, an
/// `integer`, a `string`, or an array of one of those, and nothing else -- there
/// is no `nullable` on `params` either. So every legal value has an encoding
/// here, and anything without one is a caller error rather than something to
/// drop.
///
/// This used to be `filter_map(|(k, v)| v.as_str()...)`, which kept strings and
/// silently discarded everything else. `{"cursor": "abc", "limit": 50,
/// "reverse": false}` went out as `?cursor=abc`: two of three parameters gone,
/// and the call succeeded, so nothing said the `limit` had not been applied.
/// It also put `invoke_xrpc` in direct contradiction with `validate_xrpc`,
/// which validates against the lexicon and so requires `50` and rejects `"50"`.
///
/// # Errors
///
/// A message naming the parameter, when its value has no query encoding.
fn encode_query_params(
    params: Option<&serde_json::Map<String, Value>>,
) -> Result<Vec<(String, String)>, String> {
    let mut pairs = Vec::new();
    let Some(object) = params else {
        return Ok(pairs);
    };

    for (key, value) in object {
        match value {
            // `params` has no null, so there is nothing to send. Omitted
            // rather than sent as the string "null", which is what the
            // reference client does with it.
            Value::Null => continue,
            // An array is repeated keys: `?a=1&a=2`. The specification says
            // "multiple query parameters with the same name can be used to
            // represent an array of parameters", and both reference
            // implementations append one entry per element.
            Value::Array(items) => {
                for item in items {
                    pairs.push((key.clone(), encode_query_scalar(key, item)?));
                }
            }
            scalar => pairs.push((key.clone(), encode_query_scalar(key, scalar)?)),
        }
    }

    Ok(pairs)
}

/// Encode one scalar `params` value.
///
/// Booleans are `true` and `false` by specification, strings are unquoted, and
/// a number is its JSON form -- which is what the receiving end expects: the
/// reference server requires an integer to match `^-?\d+$` and a boolean to be
/// exactly `true` or `false`, and throws otherwise.
fn encode_query_scalar(key: &str, value: &Value) -> Result<String, String> {
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::Bool(flag) => Ok(if *flag { "true" } else { "false" }.to_string()),
        Value::Number(number) => Ok(number.to_string()),
        Value::Null => Err(format!(
            "The 'params' value for '{key}' contains null, which has no query encoding. \
             Omit the parameter instead."
        )),
        Value::Array(_) => Err(format!(
            "The 'params' value for '{key}' is a nested array. A parameter may be a \
             boolean, an integer, a string, or an array of those."
        )),
        Value::Object(_) => Err(format!(
            "The 'params' value for '{key}' is an object, which is not a parameter type. \
             A parameter may be a boolean, an integer, a string, or an array of those; \
             structured data belongs in 'body'."
        )),
    }
}

/// Execute the `invoke_xrpc` tool.
///
/// `http_client` sends the call, and is the server's request client: it follows
/// no redirects, so a host that passed the endpoint policy cannot send the
/// request, or a procedure's body, somewhere that would not have.
pub async fn invoke_xrpc(
    arguments: Value,
    default_resolver: &InnerIdentityResolver,
    http_client: &reqwest::Client,
    limits: &crate::context::Limits,
) -> Value {
    let Some(nsid) = arguments.get("nsid").and_then(Value::as_str) else {
        return tool_error("The 'nsid' argument must be a string.");
    };

    let endpoint = arguments.get("endpoint").and_then(Value::as_str);
    let identity = arguments.get("identity").and_then(Value::as_str);
    let auth_handle = arguments.get("auth_handle").and_then(Value::as_str);
    let proxy = arguments.get("proxy").and_then(Value::as_str);
    let body = arguments.get("body").cloned();
    let params = arguments.get("params").and_then(Value::as_object);

    // Proxy requires auth_handle.
    if proxy.is_some() && auth_handle.is_none() {
        return tool_error("The 'proxy' parameter requires 'auth_handle' to be set.");
    }

    // A credential goes to the account's own PDS or nowhere.
    //
    // `endpoint` and `identity` both name a host, and both used to win over the
    // stored PDS while the request still carried the account's access token --
    // so a model that had been told to could send the user's credential to any
    // host it liked, which is the shape a prompt injection needs. `upload_blob`
    // has never accepted an endpoint override for exactly this reason, and this
    // crate's own documentation claimed the property that this tool broke.
    //
    // Refused rather than reconciled: comparing a caller's URL against the
    // stored one means deciding whether a trailing slash, a default port or a
    // difference in case makes two hosts the same, and that is not a judgement
    // worth making on a security boundary. Another service is reached with
    // `proxy`, which goes through the user's own PDS.
    if auth_handle.is_some()
        && let Some(argument) = ["endpoint", "identity"]
            .into_iter()
            .find(|name| arguments.get(*name).is_some())
    {
        return tool_error(&format!(
            "'{argument}' cannot be combined with 'auth_handle': an authenticated request is \
             always sent to the account's own PDS, so that a credential cannot be aimed at a \
             host chosen by the caller. Drop '{argument}' to call the account's PDS, use \
             'proxy' to reach another service through it, or drop 'auth_handle' to call \
             '{argument}' without credentials."
        ));
    }

    // Determine the service endpoint.
    let service_endpoint = if let Some(endpoint) = endpoint {
        // A caller-named host, checked before anything connects to it.
        if let Err(error) = crate::host_policy::check_endpoint(limits, endpoint) {
            return tool_error(&error.to_string());
        }
        endpoint.to_string()
    } else if let Some(identity) = identity {
        match default_resolver.resolve(identity).await {
            Ok(document) => {
                // Validated, and never waived: a `serviceEndpoint` is
                // published by the DID subject and is therefore
                // attacker-controlled. See `host_policy`.
                match crate::host_policy::pds_endpoint(&document, false) {
                    Ok(endpoint) => endpoint,
                    Err(unusable) => {
                        let tool_err = ToolError::XrpcRequestFailed {
                            reason: unusable.tool_reason(&document.id, Some("endpoint")),
                        };
                        tracing::error!(identity = %identity, ?unusable, "No usable PDS endpoint.");
                        return tool_error(&tool_err.to_string());
                    }
                }
            }
            Err(error) => {
                let tool_err = ToolError::XrpcRequestFailed {
                    reason: format!("Failed to resolve identity: {error:#}"),
                };
                tracing::error!(error = ?error, identity = %identity, "Identity resolution failed.");
                return tool_error(&tool_err.to_string());
            }
        }
    } else if let Some(handle) = auth_handle {
        match accounts::load_account(handle) {
            Ok(account) => account.pds_endpoint,
            Err(error) => {
                tracing::error!(error = ?error, "Failed to load account.");
                return tool_error(&error.to_string());
            }
        }
    } else {
        return tool_error("Either 'endpoint', 'identity', or 'auth_handle' must be provided.");
    };

    // Build query parameters from the params object.
    let query_pairs = match encode_query_params(params) {
        Ok(pairs) => pairs,
        Err(message) => return tool_error(&message),
    };

    // Build the URL.
    //
    // `params` go on the URL for a procedure too. The procedure branch used to
    // build its URL from `std::iter::empty()`, so anything passed as `params`
    // beside a `body` went nowhere -- silently, since a method that ignores a
    // parameter it never received answers normally.
    let url = match build_url(
        &service_endpoint,
        &format!("/xrpc/{nsid}"),
        query_pairs
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str())),
    ) {
        Ok(url) => url.to_string(),
        Err(error) => {
            let tool_err = ToolError::XrpcRequestFailed {
                reason: format!("Failed to build URL: {error}"),
            };
            return tool_error(&tool_err.to_string());
        }
    };

    // Build headers, including the atproto-proxy header for proxied requests.
    let mut headers = HeaderMap::new();
    if let Some(audience) = proxy {
        match reqwest::header::HeaderValue::from_str(audience) {
            Ok(value) => {
                headers.insert(
                    reqwest::header::HeaderName::from_static("atproto-proxy"),
                    value,
                );
            }
            Err(error) => {
                let tool_err = ToolError::XrpcRequestFailed {
                    reason: format!("Invalid proxy audience header value: {error}"),
                };
                return tool_error(&tool_err.to_string());
            }
        }
    }

    // Make the request. A body makes it a procedure, sent as POST.
    let body = body.as_ref();
    let result = if let Some(handle) = auth_handle {
        let mut account = match accounts::load_account(handle) {
            Ok(account) => account,
            Err(error) => {
                tracing::error!(error = ?error, "Failed to load account.");
                return tool_error(&error.to_string());
            }
        };

        accounts::with_refresh(
            http_client,
            &mut account,
            |auth: AppPasswordAuth| {
                let url = url.as_str();
                let headers = headers.clone();
                async move {
                    let mut headers = headers;
                    let bearer = HeaderValue::from_str(&format!("Bearer {}", auth.access_token))
                        .map_err(|error| {
                            format!("the stored access token is not a valid header: {error}")
                        })?;
                    headers.insert(reqwest::header::AUTHORIZATION, bearer);
                    send(http_client, url, body, headers).await
                }
            },
            |outcome| {
                outcome.as_ref().is_ok_and(|answer| {
                    answer
                        .json()
                        .is_some_and(|value| accounts::is_expired_token_response(&value))
                })
            },
        )
        .await
    } else {
        send(http_client, &url, body, headers).await
    };

    match result {
        Ok(answer) => {
            if !answer.status.is_success() {
                tracing::warn!(status = %answer.status, nsid = %nsid, "XRPC call answered with an error.");
            }
            tool_result(answer)
        }
        Err(reason) => {
            let tool_err = ToolError::XrpcRequestFailed { reason };
            tracing::warn!(error = %tool_err, nsid = %nsid, "XRPC call got no usable answer.");
            tool_error(&tool_err.to_string())
        }
    }
}

/// A service's answer to one XRPC call: its status, and its body as bytes.
#[derive(Debug)]
struct XrpcAnswer {
    status: StatusCode,
    body: Vec<u8>,
}

impl XrpcAnswer {
    /// The body as JSON, when it is JSON.
    fn json(&self) -> Option<Value> {
        serde_json::from_slice(&self.body).ok()
    }
}

/// Send one XRPC call and read the answer, status line included.
///
/// This replaced `atproto-client`'s `get_json_with_headers`,
/// `post_json_with_headers` and their app-password twins, which parse the body
/// whatever the status and return only the parse. A `400
/// {"error":"InvalidRequest"}` answering `deleteRecord` therefore came back as
/// a successful tool result, and a host deciding on `isError` took the failed
/// delete as done.
///
/// The body is read under [`MAX_JSON_RESPONSE_BYTES`] whichever the method.
/// Only the unauthenticated GET was bounded before; the other three read
/// whatever the host chose to send.
///
/// # Errors
///
/// A reason, when no answer arrived or its body was over the bound.
async fn send(
    http_client: &reqwest::Client,
    url: &str,
    body: Option<&Value>,
    headers: HeaderMap,
) -> Result<XrpcAnswer, String> {
    let request = match body {
        Some(body) => http_client.post(url).headers(headers).json(body),
        None => http_client.get(url).headers(headers),
    };
    // Logged here, with the error's `Debug`, because that is what names a
    // refused redirect's target: the `Display` stops at "error following
    // redirect".
    let response = request.send().await.map_err(|error| {
        tracing::error!(error = ?error, "XRPC request failed.");
        error.to_string()
    })?;
    let status = response.status();

    // `Content-Length` is the peer's claim, so it only refuses early; the
    // running total below is what bounds the read.
    let too_large = || format!("the response from {url} exceeds {MAX_JSON_RESPONSE_BYTES} bytes");
    if response
        .content_length()
        .is_some_and(|declared| declared > MAX_JSON_RESPONSE_BYTES)
    {
        return Err(too_large());
    }
    let mut stream = response.bytes_stream();
    let mut collected = Vec::new();
    while let Some(chunk) = stream.next().await {
        let chunk =
            chunk.map_err(|error| format!("reading the response from {url} failed: {error}"))?;
        if collected.len() as u64 + chunk.len() as u64 > MAX_JSON_RESPONSE_BYTES {
            return Err(too_large());
        }
        collected.extend_from_slice(&chunk);
    }

    Ok(XrpcAnswer {
        status,
        body: collected,
    })
}

/// The tool result for an answer. The status decides, not the body's shape.
///
/// A non-2xx is an error result carrying the status and the body verbatim --
/// the XRPC `{"error", "message"}` pair when the service sent one, a proxy's
/// HTML when it did not. Judging by a top-level `error` field instead would
/// pass a proxy's `502` as a success, and fail a method whose lexicon puts an
/// `error` field in a successful output.
///
/// A 2xx with no body is a success too. A procedure with no output answers
/// that way -- `com.atproto.identity.updateHandle`,
/// `app.bsky.actor.putPreferences` -- and the JSON helpers this replaced
/// failed to parse the empty body, so those calls were reported as failures
/// after they had taken effect.
fn tool_result(answer: XrpcAnswer) -> Value {
    if !answer.status.is_success() {
        let body = match answer.json() {
            Some(value) => value.to_string(),
            None if answer.body.is_empty() => "(no body)".to_string(),
            None => String::from_utf8_lossy(&answer.body).into_owned(),
        };
        let tool_err = ToolError::XrpcErrorResponse {
            status: answer.status.as_u16(),
            body,
        };
        return tool_error(&tool_err.to_string());
    }

    if answer.body.is_empty() {
        return tool_success(&format!(
            "The call succeeded (HTTP {}) and the service returned no body.",
            answer.status.as_u16()
        ));
    }

    match answer.json() {
        Some(value) => tool_success(&value.to_string()),
        None => {
            let tool_err = ToolError::XrpcRequestFailed {
                reason: format!(
                    "the service answered HTTP {} with a body that is not JSON; invoke_xrpc \
                     handles JSON only",
                    answer.status.as_u16()
                ),
            };
            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};

    /// `params` are encoded by type, not filtered down to the strings.
    ///
    /// Every case here was silently dropped: the encoder kept `as_str()` and
    /// discarded the rest, so a `limit` the caller set simply never applied.
    #[test]
    fn params_of_every_legal_type_are_encoded() {
        let params = serde_json::json!({
            "cursor": "abc",
            "limit": 50,
            "reverse": false,
            "enabled": true,
        });
        let mut pairs = encode_query_params(params.as_object()).expect("all legal");
        pairs.sort();

        assert_eq!(
            pairs,
            vec![
                ("cursor".to_string(), "abc".to_string()),
                ("enabled".to_string(), "true".to_string()),
                ("limit".to_string(), "50".to_string()),
                ("reverse".to_string(), "false".to_string()),
            ]
        );
    }

    /// An array is repeated keys, in order.
    ///
    /// The specification: "multiple query parameters with the same name can be
    /// used to represent an array of parameters".
    #[test]
    fn an_array_becomes_repeated_keys() {
        let params = serde_json::json!({"collections": ["a.b.c", "d.e.f"]});
        let pairs = encode_query_params(params.as_object()).expect("legal");

        assert_eq!(
            pairs,
            vec![
                ("collections".to_string(), "a.b.c".to_string()),
                ("collections".to_string(), "d.e.f".to_string()),
            ],
            "order is preserved, and the key repeats"
        );
    }

    /// Booleans are the two words the specification names, not 1 and 0.
    #[test]
    fn booleans_are_the_words_true_and_false() {
        let params = serde_json::json!({"a": true, "b": false});
        let mut pairs = encode_query_params(params.as_object()).expect("legal");
        pairs.sort();
        assert_eq!(pairs[0].1, "true");
        assert_eq!(pairs[1].1, "false");
    }

    /// Null is omitted rather than sent as the string "null".
    #[test]
    fn a_null_parameter_is_omitted() {
        let params = serde_json::json!({"cursor": null, "limit": 1});
        let pairs = encode_query_params(params.as_object()).expect("legal");
        assert_eq!(pairs, vec![("limit".to_string(), "1".to_string())]);
    }

    /// A value with no query encoding is refused, naming the parameter.
    ///
    /// Refused rather than dropped: dropping is what let this go unnoticed,
    /// since the call then succeeds and nothing says a parameter is missing.
    /// The lexicon specification allows only a boolean, an integer, a string,
    /// or an array of those in `params`.
    #[test]
    fn a_value_with_no_encoding_is_refused_not_dropped() {
        for (label, params) in [
            ("object", serde_json::json!({"filter": {"nested": true}})),
            ("nested array", serde_json::json!({"a": [["x"]]})),
            (
                "null inside an array",
                serde_json::json!({"a": ["x", null]}),
            ),
        ] {
            let error = encode_query_params(params.as_object())
                .expect_err(&format!("{label} has no query encoding"));
            assert!(
                error.contains('a') || error.contains("filter"),
                "the message should name the parameter: {error}"
            );
        }
    }

    /// No params at all is not an error.
    #[test]
    fn absent_params_encode_to_nothing() {
        assert!(encode_query_params(None).expect("fine").is_empty());
        let empty = serde_json::json!({});
        assert!(
            encode_query_params(empty.as_object())
                .expect("fine")
                .is_empty()
        );
    }

    /// An answer with `status` and `body`, as `send` would read it.
    fn answer(status: u16, body: &[u8]) -> XrpcAnswer {
        XrpcAnswer {
            status: StatusCode::from_u16(status).expect("a status"),
            body: body.to_vec(),
        }
    }

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

    /// The finding: an XRPC error response is an error result.
    ///
    /// Every case here came back `isError: false`, because the helpers this
    /// replaced parsed the body without looking at the status.
    #[test]
    fn a_non_2xx_answer_is_an_error_result_carrying_the_body() {
        let result = tool_result(answer(
            400,
            br#"{"error":"InvalidRequest","message":"Could not locate record"}"#,
        ));
        assert_eq!(result["isError"], true);
        let message = text(&result);
        assert!(message.starts_with("error-atpmcp-tool-18 "), "{message}");
        assert!(message.contains("HTTP 400"), "{message}");
        assert!(message.contains("InvalidRequest"), "{message}");
        assert!(message.contains("Could not locate record"), "{message}");

        // A proxy's page, not JSON: still an error, still with its status.
        let result = tool_result(answer(502, b"<html>Bad Gateway</html>"));
        assert_eq!(result["isError"], true);
        let message = text(&result);
        assert!(message.contains("HTTP 502"), "{message}");
        assert!(message.contains("Bad Gateway"), "{message}");

        let result = tool_result(answer(500, b""));
        assert_eq!(result["isError"], true);
        assert!(text(&result).contains("(no body)"), "{}", text(&result));
    }

    /// The status decides, not the body's shape: a success whose output
    /// happens to have an `error` field is still a success.
    #[test]
    fn a_2xx_answer_is_a_success_whatever_its_fields() {
        let result = tool_result(answer(200, br#"{"uri":"at://x","error":"none"}"#));
        assert_eq!(result["isError"], false);
        let returned: Value = serde_json::from_str(text(&result)).expect("JSON");
        assert_eq!(returned["uri"], "at://x");
    }

    /// A procedure with no output answers 2xx with no body, and that is a
    /// success. It used to fail to parse and come back as an error after the
    /// call had taken effect.
    #[test]
    fn a_2xx_answer_with_no_body_is_a_success() {
        let result = tool_result(answer(200, b""));
        assert_eq!(result["isError"], false);
        assert!(text(&result).contains("no body"), "{}", text(&result));
    }

    #[test]
    fn a_2xx_answer_that_is_not_json_is_an_error() {
        let result = tool_result(answer(200, b"\x3a\xa2not json"));
        assert_eq!(result["isError"], true);
        let message = text(&result);
        assert!(message.starts_with("error-atpmcp-tool-8 "), "{message}");
        assert!(message.contains("not JSON"), "{message}");
    }

    /// A host that reads one request, head and body, and answers it with
    /// `status`, `body` and a `Content-Length` of `declared` bytes; and its
    /// URL.
    ///
    /// The body is read before answering so that closing the connection does
    /// not reset one that still has bytes unread.
    fn answering(status: u16, body: &'static [u8], declared: usize) -> String {
        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
        let url = format!("http://{}", listener.local_addr().expect("addr"));
        std::thread::spawn(move || {
            use std::io::{Read as _, Write as _};
            let Ok((mut stream, _)) = listener.accept() else {
                return;
            };
            let mut raw = Vec::new();
            let mut buffer = [0u8; 4096];
            let head_end = loop {
                if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
                    break end + 4;
                }
                match stream.read(&mut buffer) {
                    Ok(0) | Err(_) => return,
                    Ok(read) => raw.extend_from_slice(&buffer[..read]),
                }
            };
            let head = String::from_utf8_lossy(&raw[..head_end]).to_ascii_lowercase();
            let length: usize = head
                .lines()
                .find_map(|line| line.strip_prefix("content-length:"))
                .map_or(0, |value| value.trim().parse().unwrap_or(0));
            while raw.len() < head_end + length {
                match stream.read(&mut buffer) {
                    Ok(0) | Err(_) => return,
                    Ok(read) => raw.extend_from_slice(&buffer[..read]),
                }
            }
            let _ = write!(
                stream,
                "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {declared}\r\nConnection: close\r\n\r\n"
            );
            let _ = stream.write_all(body);
        });
        url
    }

    /// Limits under which a loopback `endpoint` is allowed, as an operator
    /// developing against a local PDS would set them.
    fn waived() -> Limits {
        Limits {
            allow_insecure_endpoints: true,
            ..Limits::default()
        }
    }

    /// The finding end to end: a `deleteRecord` the service refuses is an
    /// error result, with the service's own error in it.
    #[tokio::test]
    async fn a_refused_procedure_is_an_error_result() {
        const REFUSAL: &[u8] = br#"{"error":"InvalidRequest","message":"Could not locate record"}"#;
        let endpoint = answering(400, REFUSAL, REFUSAL.len());
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.deleteRecord",
                "endpoint": endpoint,
                "body": { "repo": "did:plc:x", "collection": "app.bsky.feed.post", "rkey": "3k" },
            }),
            &create_test_resolver(),
            &test_request_client(),
            &waived(),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        let message = text(&result);
        assert!(message.starts_with("error-atpmcp-tool-18 "), "{message}");
        assert!(message.contains("HTTP 400"), "{message}");
        assert!(message.contains("InvalidRequest"), "{message}");
    }

    /// The reverse, end to end: a procedure with no output that succeeded.
    #[tokio::test]
    async fn a_procedure_with_no_output_is_a_success() {
        let endpoint = answering(200, b"", 0);
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.identity.updateHandle",
                "endpoint": endpoint,
                "body": { "handle": "alice.example.com" },
            }),
            &create_test_resolver(),
            &test_request_client(),
            &waived(),
        )
        .await;

        assert_eq!(result["isError"], false, "{result}");
    }

    /// A procedure's answer is bounded like a query's. It was read whole.
    #[tokio::test]
    async fn a_procedure_answer_over_the_bound_is_refused() {
        let declared = usize::try_from(MAX_JSON_RESPONSE_BYTES).expect("fits") + 1;
        let endpoint = answering(200, b"{}", declared);
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.createRecord",
                "endpoint": endpoint,
                "body": {},
            }),
            &create_test_resolver(),
            &test_request_client(),
            &waived(),
        )
        .await;

        assert_eq!(result["isError"], true, "{result}");
        assert!(text(&result).contains("exceeds"), "{}", text(&result));
    }

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

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

    #[tokio::test]
    async fn requires_a_target() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({ "nsid": "com.atproto.repo.describeRepo" }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("endpoint")
        );
    }

    /// The combination that leaked: a credential plus a caller-named host.
    ///
    /// Refused before the account is loaded or the identity resolved, so
    /// nothing is read from disk and no request is made.
    #[tokio::test]
    async fn an_endpoint_cannot_be_combined_with_an_auth_handle() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.describeRepo",
                "auth_handle": "alice.test",
                "endpoint": "https://attacker.example",
            }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;

        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("endpoint"), "{message}");
        assert!(message.contains("auth_handle"), "{message}");
        assert!(
            message.contains("proxy"),
            "the refusal should name the supported alternative: {message}"
        );
    }

    /// `identity` resolves to *another account's* PDS, so it is the same hole.
    #[tokio::test]
    async fn an_identity_cannot_be_combined_with_an_auth_handle() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.describeRepo",
                "auth_handle": "alice.test",
                "identity": "mallory.example",
            }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;

        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(message.contains("identity"), "{message}");
        assert!(message.contains("auth_handle"), "{message}");
    }

    /// Refused even when the named host is plausible.
    ///
    /// The rule is not "refuse hosts that look hostile" — it cannot be, since
    /// nothing here can tell. Any caller-named host is refused alongside a
    /// credential, including one that may well be the account's own.
    #[tokio::test]
    async fn a_plausible_endpoint_is_refused_too() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.describeRepo",
                "auth_handle": "alice.test",
                "endpoint": "https://bsky.social",
            }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;
        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(
            message.contains("cannot be combined"),
            "must be refused by the argument rule, not by whatever happens next: {message}"
        );
    }

    /// An unauthenticated call still takes either host argument.
    ///
    /// The refusal is about the *combination*; without a credential there is
    /// nothing to forward. These reach the network and are expected to fail
    /// there, which is the point: they get past the argument check.
    #[tokio::test]
    async fn a_host_argument_alone_is_not_refused() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "com.atproto.repo.describeRepo",
                "endpoint": "http://127.0.0.1:1",
            }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;

        // It fails, but on the transport rather than on the argument rule.
        assert_eq!(result["isError"], true);
        let message = result["content"][0]["text"].as_str().unwrap();
        assert!(
            !message.contains("cannot be combined"),
            "an unauthenticated endpoint must not be refused: {message}"
        );
    }

    #[tokio::test]
    async fn proxy_requires_an_auth_handle() {
        let resolver = create_test_resolver();
        let result = invoke_xrpc(
            serde_json::json!({
                "nsid": "app.bsky.feed.getTimeline",
                "endpoint": "https://example.com",
                "proxy": "did:web:api.bsky.app#bsky_appview",
            }),
            &resolver,
            &test_request_client(),
            &Limits::default(),
        )
        .await;
        assert_eq!(result["isError"], true);
        assert!(
            result["content"][0]["text"]
                .as_str()
                .unwrap()
                .contains("auth_handle")
        );
    }
}