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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! The transport: reading, dispatching, and shutting down.
//!
//! # Why this is concurrent
//!
//! The obvious shape for a stdio server — read a line, handle it, write the
//! answer, read the next line — cannot implement this revision of MCP. Three
//! requirements break it, and none of them can be retrofitted:
//!
//! - **Cancellation.** On stdio a client cancels by sending
//!   `notifications/cancelled`. A server that is busy handling the request
//!   cannot *read* that notification, so cancellation is structurally
//!   impossible rather than merely unimplemented.
//! - **Subscriptions.** `subscriptions/listen` is a request that does not
//!   return until it is cancelled. In a serial loop it deadlocks the server.
//! - **Notifications during a request.** Progress notifications have to be
//!   written while the request that produces them is still running.
//!
//! So: one task reads, one task writes, and each request gets its own. The
//! reader's job is to never block — it parses, classifies, and either answers
//! in microseconds or spawns. In particular it does **not** wait on the
//! concurrency semaphore, which is acquired inside the spawned task; acquiring
//! it here would reintroduce exactly the head-of-line blocking this design
//! exists to remove.

use std::sync::Arc;
use std::time::Duration;

use atproto_identity::resolve::InnerIdentityResolver;
use serde_json::Value;
use tokio::io::{AsyncBufRead, AsyncBufReadExt, AsyncRead, AsyncWrite, BufReader};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::cache::BlobCache;
use crate::context::{Limits, ServerContext};
use crate::errors::ProtocolError;
use crate::proto::meta::{self, Meta};
use crate::proto::progress;
use crate::proto::writer::{self, Outgoing};
use crate::proto::{
    INVALID_REQUEST, JsonRpcMessage, JsonRpcResponse, METHOD_NOT_FOUND, PARSE_ERROR,
    PROTOCOL_VERSION, RequestKey, complete, discover,
};

/// How long shutdown waits for queued output to drain.
const DRAIN_TIMEOUT: Duration = Duration::from_secs(2);

/// How long shutdown waits for in-flight requests to finish on their own.
///
/// Closing stdin is how a client says "finish up", not "stop": a one-shot
/// invocation such as `echo '{…}' | atpmcp` writes one request and closes the
/// stream immediately, and cancelling on sight would mean it never sees an
/// answer. Requests still running after this are cancelled.
const INFLIGHT_GRACE: Duration = Duration::from_secs(30);

/// How often the shutdown drain re-checks whether work has finished.
const INFLIGHT_POLL: Duration = Duration::from_millis(5);

/// How long shutdown gives subscription tasks to emit their teardown.
const TEARDOWN_GRACE: Duration = Duration::from_millis(50);

/// Everything one request carries with it.
pub struct RequestCtx {
    /// The normalized request id, for the cancellation registry.
    pub key: RequestKey,
    /// The request id as it appeared on the wire.
    pub id: Value,
    /// Validated protocol metadata.
    pub meta: Meta,
    /// Fires when the client cancels this request.
    pub cancel: CancellationToken,
    /// Emits progress, when the client opted in.
    pub progress: Option<progress::Emitter>,
}

impl RequestCtx {
    /// Report progress, if the client asked for it.
    pub fn report_progress(&mut self, current: u64, message: &str) {
        if let Some(emitter) = self.progress.as_mut() {
            emitter.report(current, message);
        }
    }

    /// Record the expected total for progress reporting.
    pub fn set_progress_total(&mut self, total: Option<u64>) {
        if let Some(emitter) = self.progress.as_mut() {
            emitter.set_total(total);
        }
    }

    /// Report the final progress value.
    pub fn finish_progress(&mut self, current: u64, message: &str) {
        if let Some(emitter) = self.progress.as_mut() {
            emitter.finish(current, message);
        }
    }
}

/// Outcome of reading one line from the input stream.
#[derive(Debug, PartialEq, Eq)]
enum ReadOutcome {
    /// A complete line was read into the buffer.
    Line,
    /// The stream ended.
    Eof,
    /// The line exceeded the ceiling and was discarded.
    TooLong,
}

/// Read up to one newline, refusing to buffer more than `max` bytes.
///
/// `AsyncBufReadExt::read_until` would happily buffer a gigabyte, which is a
/// trivial memory-exhaustion vector from a client that never sends a newline.
/// On overflow the rest of the line is drained so the stream resynchronises
/// on the next message rather than desynchronising permanently.
async fn read_line_capped<R>(
    reader: &mut R,
    buffer: &mut Vec<u8>,
    max: usize,
) -> std::io::Result<ReadOutcome>
where
    R: AsyncBufRead + Unpin,
{
    loop {
        let available = reader.fill_buf().await?;
        if available.is_empty() {
            return Ok(if buffer.is_empty() {
                ReadOutcome::Eof
            } else {
                ReadOutcome::Line
            });
        }

        if let Some(index) = available.iter().position(|byte| *byte == b'\n') {
            // Checked before the bytes are accepted. A chunk large enough to
            // hold the whole line would otherwise sail past the ceiling,
            // because the overrun check below only fires when a chunk ends
            // without a newline.
            if buffer.len() + index > max {
                buffer.clear();
                reader.consume(index + 1);
                return Ok(ReadOutcome::TooLong);
            }
            buffer.extend_from_slice(&available[..index]);
            reader.consume(index + 1);
            return Ok(ReadOutcome::Line);
        }

        let consumed = available.len();
        buffer.extend_from_slice(available);
        reader.consume(consumed);

        if buffer.len() > max {
            buffer.clear();
            drain_to_newline(reader).await?;
            return Ok(ReadOutcome::TooLong);
        }
    }
}

/// Discard input up to and including the next newline.
async fn drain_to_newline<R>(reader: &mut R) -> std::io::Result<()>
where
    R: AsyncBufRead + Unpin,
{
    loop {
        let available = reader.fill_buf().await?;
        if available.is_empty() {
            return Ok(());
        }
        if let Some(index) = available.iter().position(|byte| *byte == b'\n') {
            reader.consume(index + 1);
            return Ok(());
        }
        let consumed = available.len();
        reader.consume(consumed);
    }
}

/// Serve MCP over a pair of streams until the input ends.
///
/// Generic over its streams so the transport can be driven by an in-memory
/// duplex in tests. Welding it to the process's real stdio is what made every
/// interesting property here — out-of-order completion, cancellation,
/// non-interleaving — untestable.
///
/// # Errors
///
/// Returns an error only if the input stream fails in a way that is not a
/// clean end.
pub async fn serve<R, W>(
    reader: R,
    writer: W,
    resolver: Arc<InnerIdentityResolver>,
    cache: Arc<BlobCache>,
    limits: Limits,
) -> anyhow::Result<()>
where
    R: AsyncRead + Unpin,
    W: AsyncWrite + Unpin + Send + 'static,
{
    let (tx, rx) = mpsc::channel::<Outgoing>(writer::CHANNEL_CAPACITY);
    let writer_handle = tokio::spawn(writer::run(writer, rx));

    let ctx = Arc::new(ServerContext::new(resolver, cache, limits, tx)?);
    let mut reader = BufReader::new(reader);
    let mut buffer = Vec::with_capacity(8 * 1024);

    loop {
        buffer.clear();
        match read_line_capped(&mut reader, &mut buffer, limits.max_message_bytes).await {
            Ok(ReadOutcome::Eof) => break,
            Ok(ReadOutcome::Line) => {
                if buffer.iter().all(u8::is_ascii_whitespace) {
                    continue;
                }
                dispatch(&buffer, &ctx).await;
            }
            Ok(ReadOutcome::TooLong) => {
                let error = ProtocolError::MessageTooLarge {
                    limit: limits.max_message_bytes,
                };
                tracing::warn!(
                    limit = limits.max_message_bytes,
                    "Refused an oversize message."
                );
                send(
                    &ctx,
                    JsonRpcResponse::error(Value::Null, error.code(), error.to_string()),
                )
                .await;
            }
            Err(error) => {
                tracing::error!(error = ?error, "Failed to read from the input stream.");
                break;
            }
        }
    }

    shutdown(ctx, writer_handle).await;
    Ok(())
}

/// Tear everything down in order, bounded by [`DRAIN_TIMEOUT`].
async fn shutdown<T>(ctx: Arc<ServerContext>, writer_handle: tokio::task::JoinHandle<T>) {
    tracing::debug!("Input closed; shutting down.");

    // Subscriptions first: they are parked on their tokens and need a moment
    // to emit their teardown messages before the channel goes away.
    ctx.subscriptions.cancel_all();
    if !ctx.subscriptions.is_empty() {
        tokio::time::sleep(TEARDOWN_GRACE).await;
    }

    // In-flight requests are given a bounded chance to finish and answer.
    let deadline = tokio::time::Instant::now() + INFLIGHT_GRACE;
    while !ctx.inflight.is_empty() && tokio::time::Instant::now() < deadline {
        tokio::time::sleep(INFLIGHT_POLL).await;
    }

    if !ctx.inflight.is_empty() {
        tracing::warn!(
            count = ctx.inflight.len(),
            "Cancelling requests still running after the shutdown grace period."
        );
        ctx.inflight.cancel_all();
    }

    drop(ctx);

    // The writer returns once every sender is gone. A task that refuses to
    // die must not hold the process open, hence the bound.
    if tokio::time::timeout(DRAIN_TIMEOUT, writer_handle)
        .await
        .is_err()
    {
        tracing::warn!("Output did not drain within the shutdown grace period.");
    }
}

/// Send one message, applying backpressure if the client is not reading.
async fn send(ctx: &Arc<ServerContext>, response: JsonRpcResponse) {
    if ctx.out.send(Outgoing::response(response)).await.is_err() {
        tracing::debug!("Output channel closed; dropping a response.");
    }
}

/// Parse, classify, and either answer or spawn.
async fn dispatch(line: &[u8], ctx: &Arc<ServerContext>) {
    let message: JsonRpcMessage = match serde_json::from_slice(line) {
        Ok(message) => message,
        Err(error) => {
            tracing::warn!(error = ?error, "Failed to parse a JSON-RPC message.");
            send(
                ctx,
                JsonRpcResponse::error(Value::Null, PARSE_ERROR, "Parse error"),
            )
            .await;
            return;
        }
    };

    if message.jsonrpc != "2.0" {
        let id = message.id.clone().unwrap_or(Value::Null);
        send(
            ctx,
            JsonRpcResponse::error(id, INVALID_REQUEST, "Invalid JSON-RPC version"),
        )
        .await;
        return;
    }

    let Some(raw_id) = message.id.clone() else {
        handle_notification(&message, ctx);
        return;
    };

    let Some(key) = RequestKey::from_value(&raw_id) else {
        send(
            ctx,
            JsonRpcResponse::error(
                Value::Null,
                INVALID_REQUEST,
                "Request id must be a string or an integer",
            ),
        )
        .await;
        return;
    };

    // Methods this revision removed are answered before `_meta` validation, so
    // a client still speaking an earlier revision gets a diagnostic naming the
    // problem instead of a complaint about a field its revision never had.
    if let Some(response) = removed_method_diagnostic(&message.method, raw_id.clone()) {
        send(ctx, response).await;
        return;
    }

    let meta = match meta::parse(message.params.as_ref()) {
        Ok(meta) => meta,
        Err(error) => {
            let data = match &error {
                ProtocolError::UnsupportedVersion { requested } => {
                    Some(meta::unsupported_version_data(requested))
                }
                _ => None,
            };
            let response = match data {
                Some(data) => {
                    JsonRpcResponse::error_with_data(raw_id, error.code(), error.to_string(), data)
                }
                None => JsonRpcResponse::error(raw_id, error.code(), error.to_string()),
            };
            send(ctx, response).await;
            return;
        }
    };

    if ctx.inflight.len() >= ctx.limits.max_queued_requests {
        let error = ProtocolError::Busy {
            inflight: ctx.inflight.len(),
        };
        send(
            ctx,
            JsonRpcResponse::error(raw_id, error.code(), error.to_string()),
        )
        .await;
        return;
    }

    if message.method == "subscriptions/listen" {
        spawn_subscription(ctx, key, raw_id, message.params);
        return;
    }

    spawn_request(ctx, key, raw_id, meta, message.method, message.params);
}

/// A diagnostic for a method this revision removed.
///
/// A legacy client has no fall-forward mechanism, so the error text may be the
/// only thing a user ever sees. The specification asks a modern-only server to
/// name the versions it supports in any error it returns to `initialize`.
fn removed_method_diagnostic(method: &str, id: Value) -> Option<JsonRpcResponse> {
    let message = match method {
        "initialize" => format!(
            "atpmcp implements MCP {PROTOCOL_VERSION}, which removed the initialize handshake. \
             This client appears to speak an earlier revision. Supported versions: \
             {PROTOCOL_VERSION}."
        ),
        "ping" => format!(
            "The ping method was removed in MCP {PROTOCOL_VERSION}. Use server/discover to check \
             that this server is reachable."
        ),
        _ => return None,
    };

    Some(JsonRpcResponse::error_with_data(
        id,
        METHOD_NOT_FOUND,
        message,
        serde_json::json!({ "supportedVersions": [PROTOCOL_VERSION] }),
    ))
}

/// Handle a notification inline.
///
/// Cancellation is handled here rather than on a spawned task so it can never
/// queue behind the request it is trying to cancel. It is a map lookup.
fn handle_notification(message: &JsonRpcMessage, ctx: &Arc<ServerContext>) {
    if message.method != "notifications/cancelled" {
        tracing::debug!(method = %message.method, "Ignoring a notification.");
        return;
    }

    let Some(request_id) = message
        .params
        .as_ref()
        .and_then(|params| params.get("requestId"))
    else {
        tracing::debug!("Ignoring a cancellation with no requestId.");
        return;
    };

    let Some(key) = RequestKey::from_value(request_id) else {
        tracing::debug!("Ignoring a cancellation with a malformed requestId.");
        return;
    };

    let reason = message
        .params
        .as_ref()
        .and_then(|params| params.get("reason"))
        .and_then(Value::as_str)
        .unwrap_or("(none given)");

    if ctx.subscriptions.cancel_by_client(&key) {
        tracing::info!(reason = %reason, "Client ended a subscription.");
        return;
    }

    if ctx.inflight.cancel(&key) {
        tracing::info!(reason = %reason, "Client cancelled a request.");
    } else {
        // Unknown, already finished, or never ours. All three are ignored:
        // cancellations race with completion by nature.
        tracing::debug!("Ignoring a cancellation for an unknown request.");
    }
}

/// Spawn a handler for one request.
fn spawn_request(
    ctx: &Arc<ServerContext>,
    key: RequestKey,
    id: Value,
    meta: Meta,
    method: String,
    params: Option<Value>,
) {
    // Registered before the task is spawned, which closes the race where a
    // cancellation arrives before the handler has announced itself.
    let cancel = ctx.inflight.register(key.clone());

    let ctx = Arc::clone(ctx);
    let supervisor_cancel = cancel.clone();
    let supervisor_key = key.clone();
    let supervisor_id = id.clone();

    tokio::spawn(async move {
        let inner_ctx = Arc::clone(&ctx);
        let progress = progress::Emitter::new(meta.progress_token.clone(), ctx.out.clone());
        let mut rctx = RequestCtx {
            key,
            id,
            meta,
            cancel,
            progress,
        };

        let permits = Arc::clone(&ctx.permits);
        let mut inner = tokio::spawn(async move {
            // Acquired here rather than in the reader: waiting for a permit
            // must never stop the server from reading its input.
            let _permit = permits.acquire_owned().await;
            route(&inner_ctx, &mut rctx, &method, params).await
        });

        let response = tokio::select! {
            biased;
            () = supervisor_cancel.cancelled() => {
                inner.abort();
                tracing::debug!("Abandoned a cancelled request.");
                return;
            }
            joined = &mut inner => match joined {
                Ok(response) => response,
                Err(error) if error.is_panic() => {
                    tracing::error!(error = ?error, "A request handler panicked.");
                    let internal = ProtocolError::Internal {
                        reason: "the handler failed unexpectedly".to_string(),
                    };
                    JsonRpcResponse::error(supervisor_id, internal.code(), internal.to_string())
                }
                Err(_) => return,
            },
        };

        // The decision point. If the entry is gone, the request was cancelled
        // between the handler finishing and this line, and the specification
        // says not to answer it.
        if ctx.inflight.take(&supervisor_key).is_some() {
            let _ = ctx.out.send(Outgoing::response(response)).await;
        }
    });
}

/// Spawn a parked task holding one subscription open.
///
/// Deliberately outside the concurrency budget: a subscription spends its life
/// blocked on a token, and letting one occupy a permit would starve real work.
fn spawn_subscription(ctx: &Arc<ServerContext>, key: RequestKey, id: Value, params: Option<Value>) {
    use crate::proto::subs;

    let subscription = ctx.subscriptions.register(key.clone());
    let ctx = Arc::clone(ctx);

    tokio::spawn(async move {
        let requested = params
            .as_ref()
            .and_then(|params| params.get("notifications"))
            .cloned();

        // The acknowledgment must precede every notification on this
        // subscription. Sent synchronously here, before anything else can
        // reference the id, with a single writer preserving the order.
        let _ = ctx
            .out
            .send(Outgoing::notification(subs::acknowledgement(
                &key,
                requested.as_ref(),
            )))
            .await;

        subscription.token.cancelled().await;

        if subscription
            .client_cancelled
            .load(std::sync::atomic::Ordering::SeqCst)
        {
            // The client asked for the end. The general cancellation rule
            // applies: do not answer a cancelled request.
            tracing::debug!("Subscription ended by client cancellation.");
            return;
        }

        // Server-initiated teardown. Cancellation requires the notification;
        // the subscriptions page asks for a graceful completion response. The
        // two pages describe one event and do not agree on which message
        // carries it, so both are sent and a client ignores whichever it does
        // not expect.
        let _ = ctx
            .out
            .send(Outgoing::notification(subs::teardown_notification(&key)))
            .await;

        let payload = complete(subs::graceful_closure_payload(&key), None, &ctx.server_info);
        let _ = ctx
            .out
            .send(Outgoing::response(JsonRpcResponse::success(id, payload)))
            .await;

        ctx.subscriptions.remove(&key);
    });
}

/// The client's self-reported name, for logging only.
///
/// `clientInfo` is unverified by the protocol, so it is never used to change
/// behaviour. Extracted rather than inlined because inside `tracing`'s macros
/// `Value` resolves to `tracing::Value`, not `serde_json::Value`.
fn client_name(rctx: &RequestCtx) -> &str {
    rctx.meta
        .client_info
        .as_ref()
        .and_then(|info| info.get("name"))
        .and_then(serde_json::Value::as_str)
        .unwrap_or("(unidentified)")
}

/// Route a validated request to its handler.
async fn route(
    ctx: &Arc<ServerContext>,
    rctx: &mut RequestCtx,
    method: &str,
    params: Option<Value>,
) -> JsonRpcResponse {
    let id = rctx.id.clone();

    // `clientInfo` is self-reported and unverified, so it is logged and never
    // acted on. It is the only handle an operator has on which client sent
    // what when two are pointed at the same binary.
    tracing::debug!(
        method = %method,
        request = ?rctx.key,
        protocol = %rctx.meta.protocol_version,
        client = client_name(rctx),
        "Handling a request."
    );

    match method {
        "server/discover" => JsonRpcResponse::success(
            id,
            complete(
                discover::payload(ctx),
                Some(crate::proto::CacheHints::constant()),
                &ctx.server_info,
            ),
        ),
        "tools/list" => JsonRpcResponse::success(id, crate::tools::list(ctx)),
        "tools/call" => crate::tools::call(ctx, rctx, params).await,
        "resources/list" => JsonRpcResponse::success(id, crate::resources::list(ctx)),
        "resources/templates/list" => {
            JsonRpcResponse::success(id, crate::resources::templates(ctx))
        }
        "resources/read" => crate::resources::read(ctx, rctx, params).await,
        _ => JsonRpcResponse::error(id, METHOD_NOT_FOUND, format!("Method not found: {method}")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::io::AsyncWriteExt;

    async fn read_capped(input: &str, max: usize) -> (ReadOutcome, String) {
        let mut reader = BufReader::new(input.as_bytes());
        let mut buffer = Vec::new();
        let outcome = read_line_capped(&mut reader, &mut buffer, max)
            .await
            .unwrap();
        (outcome, String::from_utf8_lossy(&buffer).to_string())
    }

    #[tokio::test]
    async fn reads_one_line_at_a_time() {
        let (outcome, line) = read_capped("first\nsecond\n", 1024).await;
        assert_eq!(outcome, ReadOutcome::Line);
        assert_eq!(line, "first");
    }

    #[tokio::test]
    async fn reports_end_of_stream() {
        let (outcome, line) = read_capped("", 1024).await;
        assert_eq!(outcome, ReadOutcome::Eof);
        assert!(line.is_empty());
    }

    #[tokio::test]
    async fn a_final_line_without_a_newline_is_still_a_line() {
        let (outcome, line) = read_capped("trailing", 1024).await;
        assert_eq!(outcome, ReadOutcome::Line);
        assert_eq!(line, "trailing");
    }

    #[tokio::test]
    async fn an_oversize_line_is_refused_and_the_stream_resynchronises() {
        let oversize = "x".repeat(64);
        let input = format!("{oversize}\nshort\n");
        let mut reader = BufReader::new(input.as_bytes());
        let mut buffer = Vec::new();

        let first = read_line_capped(&mut reader, &mut buffer, 16)
            .await
            .unwrap();
        assert_eq!(first, ReadOutcome::TooLong);

        buffer.clear();
        let second = read_line_capped(&mut reader, &mut buffer, 16)
            .await
            .unwrap();
        assert_eq!(second, ReadOutcome::Line);
        assert_eq!(String::from_utf8_lossy(&buffer), "short");
    }

    #[test]
    fn initialize_is_answered_with_a_diagnostic_naming_the_version() {
        let response = removed_method_diagnostic("initialize", serde_json::json!(1))
            .expect("initialize is answered");
        let error = response.error.unwrap();
        assert_eq!(error.code, METHOD_NOT_FOUND);
        assert!(error.message.contains(PROTOCOL_VERSION));
        assert!(error.message.contains("initialize handshake"));
        assert_eq!(
            error.data.unwrap()["supportedVersions"][0],
            PROTOCOL_VERSION
        );
    }

    #[test]
    fn ping_is_answered_as_removed() {
        let response =
            removed_method_diagnostic("ping", serde_json::json!(1)).expect("ping is answered");
        let error = response.error.unwrap();
        assert_eq!(error.code, METHOD_NOT_FOUND);
        assert!(error.message.contains("removed"));
    }

    #[test]
    fn live_methods_get_no_removal_diagnostic() {
        for method in ["tools/list", "server/discover", "resources/read"] {
            assert!(removed_method_diagnostic(method, serde_json::json!(1)).is_none());
        }
    }

    /// Drive `serve` with an in-memory duplex and collect the lines it emits.
    pub(crate) async fn exchange(input: &str) -> Vec<Value> {
        let (mut client, server) = tokio::io::duplex(1 << 20);
        let (server_read, server_write) = tokio::io::split(server);

        let resolver = Arc::new(InnerIdentityResolver {
            dns_resolver: Arc::new(
                atproto_identity::resolve::HickoryDnsResolver::create_resolver(&[]),
            ),
            http_client: reqwest::Client::new(),
            plc_hostname: "plc.directory".to_string(),
        });
        let cache = Arc::new(BlobCache::new(None, 0));

        let handle = tokio::spawn(serve(
            server_read,
            server_write,
            resolver,
            cache,
            Limits::default(),
        ));

        client.write_all(input.as_bytes()).await.unwrap();
        client.shutdown().await.unwrap();

        let mut output = Vec::new();
        tokio::io::AsyncReadExt::read_to_end(&mut client, &mut output)
            .await
            .unwrap();
        let _ = tokio::time::timeout(Duration::from_secs(5), handle).await;

        String::from_utf8(output)
            .unwrap()
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(|line| serde_json::from_str(line).expect("every line is JSON"))
            .collect()
    }

    fn request(id: i64, method: &str, params: Value) -> String {
        let mut params = params;
        params["_meta"] = serde_json::json!({
            meta::KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
            meta::KEY_CLIENT_CAPABILITIES: {},
        });
        format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": method,
                "params": params,
            })
        )
    }

    #[tokio::test]
    async fn discover_returns_a_complete_cacheable_result() {
        let messages = exchange(&request(1, "server/discover", serde_json::json!({}))).await;
        assert_eq!(messages.len(), 1);
        let result = &messages[0]["result"];
        assert_eq!(result["resultType"], "complete");
        assert_eq!(result["supportedVersions"][0], PROTOCOL_VERSION);
        assert_eq!(result["ttlMs"], 3_600_000);
        assert_eq!(result["cacheScope"], "public");
        assert_eq!(result["_meta"][meta::KEY_SERVER_INFO]["name"], "atpmcp");
    }

    #[tokio::test]
    async fn a_request_without_meta_is_invalid_params() {
        let line = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n";
        let messages = exchange(line).await;
        assert_eq!(messages[0]["error"]["code"], crate::proto::INVALID_PARAMS);
        assert!(
            messages[0]["error"]["message"]
                .as_str()
                .unwrap()
                .contains("error-atpmcp-protocol-1")
        );
    }

    #[tokio::test]
    async fn a_legacy_version_is_refused_with_the_supported_list() {
        let line = format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "tools/list",
                "params": { "_meta": {
                    meta::KEY_PROTOCOL_VERSION: "2025-11-25",
                    meta::KEY_CLIENT_CAPABILITIES: {},
                }},
            })
        );
        let messages = exchange(&line).await;
        let error = &messages[0]["error"];
        assert_eq!(error["code"], crate::proto::UNSUPPORTED_PROTOCOL_VERSION);
        assert_eq!(error["data"]["supported"][0], PROTOCOL_VERSION);
        assert_eq!(error["data"]["requested"], "2025-11-25");
    }

    #[tokio::test]
    async fn an_initialize_handshake_is_refused_with_a_diagnostic() {
        let line = "{\"jsonrpc\":\"2.0\",\"id\":0,\"method\":\"initialize\",\
                    \"params\":{\"protocolVersion\":\"2025-11-25\"}}\n";
        let messages = exchange(line).await;
        let error = &messages[0]["error"];
        assert_eq!(error["code"], METHOD_NOT_FOUND);
        assert!(
            error["message"]
                .as_str()
                .unwrap()
                .contains("initialize handshake")
        );
    }

    #[tokio::test]
    async fn malformed_json_is_a_parse_error_with_a_null_id() {
        let messages = exchange("{not json}\n").await;
        assert_eq!(messages[0]["error"]["code"], PARSE_ERROR);
        assert_eq!(messages[0]["id"], Value::Null);
    }

    #[tokio::test]
    async fn a_null_id_is_an_invalid_request() {
        let line = "{\"jsonrpc\":\"2.0\",\"id\":null,\"method\":\"tools/list\"}\n";
        let messages = exchange(line).await;
        assert_eq!(messages[0]["error"]["code"], INVALID_REQUEST);
    }

    #[tokio::test]
    async fn an_unknown_method_is_method_not_found() {
        let messages = exchange(&request(1, "does/not/exist", serde_json::json!({}))).await;
        assert_eq!(messages[0]["error"]["code"], METHOD_NOT_FOUND);
    }

    #[tokio::test]
    async fn a_notification_produces_no_response() {
        let line = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\
                    \"params\":{\"requestId\":42}}\n";
        assert!(exchange(line).await.is_empty());
    }

    #[tokio::test]
    async fn a_subscription_is_acknowledged_with_an_empty_filter() {
        let line = request(
            7,
            "subscriptions/listen",
            serde_json::json!({ "notifications": { "toolsListChanged": true } }),
        );
        let messages = exchange(&line).await;

        let ack = messages
            .iter()
            .find(|message| message["method"] == "notifications/subscriptions/acknowledged")
            .expect("the subscription is acknowledged");
        assert_eq!(ack["params"]["_meta"][meta::KEY_SUBSCRIPTION_ID], 7);
        assert_eq!(ack["params"]["notifications"], serde_json::json!({}));
    }

    #[tokio::test]
    async fn shutdown_tears_a_subscription_down_gracefully() {
        let line = request(7, "subscriptions/listen", serde_json::json!({}));
        let messages = exchange(&line).await;

        // Input closes immediately, so the server tears the stream down on its
        // own initiative: both the cancellation and the graceful response.
        assert!(
            messages
                .iter()
                .any(|message| message["method"] == "notifications/cancelled"
                    && message["params"]["requestId"] == 7)
        );
        let closure = messages
            .iter()
            .find(|message| message["id"] == 7 && message.get("result").is_some())
            .expect("the listen request is answered on graceful closure");
        assert_eq!(closure["result"]["resultType"], "complete");
        assert_eq!(closure["result"]["_meta"][meta::KEY_SUBSCRIPTION_ID], 7);
    }

    #[tokio::test]
    async fn a_client_cancellation_suppresses_the_subscription_response() {
        let mut input = request(7, "subscriptions/listen", serde_json::json!({}));
        input.push_str(
            "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/cancelled\",\
             \"params\":{\"requestId\":7,\"reason\":\"done\"}}\n",
        );
        let messages = exchange(&input).await;

        assert!(
            messages
                .iter()
                .any(|message| message["method"] == "notifications/subscriptions/acknowledged")
        );
        assert!(
            !messages
                .iter()
                .any(|message| message["id"] == 7 && message.get("result").is_some()),
            "a client-cancelled request must not be answered"
        );
    }

    #[tokio::test]
    async fn concurrent_requests_are_all_answered() {
        let mut input = String::new();
        for id in 1..=5 {
            input.push_str(&request(id, "tools/list", serde_json::json!({})));
        }
        let messages = exchange(&input).await;

        let mut ids: Vec<i64> = messages
            .iter()
            .filter_map(|message| message["id"].as_i64())
            .collect();
        ids.sort_unstable();
        assert_eq!(ids, vec![1, 2, 3, 4, 5]);
    }
}

#[cfg(test)]
mod transport_tests {
    //! Properties of the transport itself, driven over an in-memory duplex.
    //!
    //! None of these could be written against the previous serial loop, which
    //! was welded to the process's real stdio and handled one message at a
    //! time.

    use super::tests::exchange;
    use super::*;
    use crate::proto::INTERNAL_ERROR;

    fn call(id: i64, tool: &str) -> String {
        format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": id,
                "method": "tools/call",
                "params": {
                    "name": tool,
                    "arguments": {},
                    "_meta": {
                        meta::KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
                        meta::KEY_CLIENT_CAPABILITIES: {},
                    },
                },
            })
        )
    }

    fn cancel(id: i64) -> String {
        format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "notifications/cancelled",
                "params": { "requestId": id, "reason": "test" },
            })
        )
    }

    #[tokio::test]
    async fn a_cancelled_request_produces_no_response() {
        let input = format!("{}{}", call(1, "__test_slow"), cancel(1));
        let messages = exchange(&input).await;

        assert!(
            !messages.iter().any(|message| message["id"] == 1),
            "a cancelled request must not be answered: {messages:?}"
        );
    }

    #[tokio::test]
    async fn a_cancellation_does_not_queue_behind_the_request_it_cancels() {
        // The head-of-line test. Both handlers are slow and only one permit is
        // available, so if the reader waited on handler work — or on a permit
        // — the cancellation could not be read at all and both would answer.
        let input = format!(
            "{}{}{}",
            call(1, "__test_slow"),
            call(2, "__test_slow"),
            cancel(1)
        );
        let messages = exchange(&input).await;

        assert!(!messages.iter().any(|message| message["id"] == 1));
        assert!(
            messages.iter().any(|message| message["id"] == 2),
            "the uncancelled request must still be answered: {messages:?}"
        );
    }

    #[tokio::test]
    async fn a_panicking_handler_yields_an_internal_error_and_the_server_survives() {
        let input = format!(
            "{}{}",
            call(1, "__test_panic"),
            call(2, "create_record_cid")
        );
        let messages = exchange(&input).await;

        let panicked = messages
            .iter()
            .find(|message| message["id"] == 1)
            .expect("a panicking handler still answers");
        assert_eq!(panicked["error"]["code"], INTERNAL_ERROR);
        assert!(
            panicked["error"]["message"]
                .as_str()
                .is_some_and(|message| message.starts_with("error-atpmcp-protocol-6 ")),
            "a panic is the server's fault, not a malformed request: {panicked}"
        );

        assert!(
            messages.iter().any(|message| message["id"] == 2),
            "the server keeps serving after a handler panics: {messages:?}"
        );
    }

    #[tokio::test]
    async fn an_unknown_tool_is_invalid_params_not_method_not_found() {
        let messages = exchange(&call(1, "no_such_tool")).await;
        let error = &messages[0]["error"];
        assert_eq!(error["code"], crate::proto::INVALID_PARAMS);
        assert_ne!(
            error["code"], METHOD_NOT_FOUND,
            "an earlier revision used -32601 here"
        );
    }

    #[tokio::test]
    async fn every_emitted_line_is_one_whole_message() {
        let mut input = String::new();
        for id in 1..=8 {
            input.push_str(&call(id, "create_record_cid"));
        }
        // `exchange` parses every line as JSON, so interleaving or a raw
        // newline inside a message would fail here rather than silently
        // corrupting the stream.
        let messages = exchange(&input).await;
        assert_eq!(messages.len(), 8);
        assert!(messages.iter().all(|message| message["jsonrpc"] == "2.0"));
    }

    #[tokio::test]
    async fn an_oversize_message_is_refused_over_the_wire() {
        let mut oversize =
            String::from("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\",\"pad\":\"");
        oversize.push_str(&"x".repeat(2048));
        oversize.push_str("\"}\n");

        let (mut client, server) = tokio::io::duplex(1 << 20);
        let (server_read, server_write) = tokio::io::split(server);
        let limits = Limits {
            max_message_bytes: 512,
            ..Limits::default()
        };

        let resolver = Arc::new(InnerIdentityResolver {
            dns_resolver: Arc::new(
                atproto_identity::resolve::HickoryDnsResolver::create_resolver(&[]),
            ),
            http_client: reqwest::Client::new(),
            plc_hostname: "plc.directory".to_string(),
        });

        let handle = tokio::spawn(serve(
            server_read,
            server_write,
            resolver,
            Arc::new(BlobCache::new(None, 0)),
            limits,
        ));

        use tokio::io::AsyncWriteExt;
        client.write_all(oversize.as_bytes()).await.unwrap();
        client.shutdown().await.unwrap();

        let mut output = Vec::new();
        tokio::io::AsyncReadExt::read_to_end(&mut client, &mut output)
            .await
            .unwrap();
        let _ = tokio::time::timeout(Duration::from_secs(5), handle).await;

        let text = String::from_utf8(output).unwrap();
        let message: Value = serde_json::from_str(text.lines().next().unwrap()).unwrap();
        assert_eq!(message["error"]["code"], INVALID_REQUEST);
        assert!(
            message["error"]["message"]
                .as_str()
                .unwrap()
                .contains("error-atpmcp-protocol-4")
        );
    }

    #[tokio::test]
    async fn tools_list_is_complete_and_cacheable_over_the_wire() {
        let messages = exchange(&format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "tools/list",
                "params": { "_meta": {
                    meta::KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
                    meta::KEY_CLIENT_CAPABILITIES: {},
                }},
            })
        ))
        .await;

        let result = &messages[0]["result"];
        assert_eq!(result["resultType"], "complete");
        assert_eq!(result["cacheScope"], "public");
        assert!(result["ttlMs"].as_u64().unwrap() > 0);
        assert_eq!(result["tools"].as_array().unwrap().len(), 13);
    }

    #[tokio::test]
    async fn a_tool_call_result_carries_no_cache_hints() {
        // `tools/call` is not in the cacheable set, and emitting hints there
        // would invite a client to reuse the result of an action.
        let messages = exchange(&call(1, "create_record_cid")).await;
        let result = &messages[0]["result"];
        assert_eq!(result["resultType"], "complete");
        assert!(result.get("ttlMs").is_none());
        assert!(result.get("cacheScope").is_none());
    }

    #[tokio::test]
    async fn resource_templates_are_served_over_the_wire() {
        let messages = exchange(&format!(
            "{}\n",
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "resources/templates/list",
                "params": { "_meta": {
                    meta::KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
                    meta::KEY_CLIENT_CAPABILITIES: {},
                }},
            })
        ))
        .await;

        let template = &messages[0]["result"]["resourceTemplates"][0];
        assert_eq!(template["uriTemplate"], crate::blob::URI_TEMPLATE);
    }

    #[test]
    fn the_retired_resource_not_found_code_appears_nowhere() {
        // `-32002` meant "resource not found" through 2025-11-25 and is
        // reserved by this revision, which forbids emitting it. It is the
        // obvious code to reach for from an older SDK example, so its absence
        // is asserted rather than assumed.
        for (name, source) in [
            ("proto/mod.rs", include_str!("mod.rs")),
            ("proto/serve.rs", include_str!("serve.rs")),
            ("errors.rs", include_str!("../errors.rs")),
            ("resources.rs", include_str!("../resources.rs")),
        ] {
            // Only the production half of each file. Tests legitimately name
            // the code in order to assert its absence, and comments name it in
            // order to warn about it; neither is an emission.
            let production = source.split("#[cfg(test)]").next().unwrap_or(source);
            let offending: Vec<&str> = production
                .lines()
                .filter(|line| !line.trim_start().starts_with("//"))
                .filter(|line| line.contains("-32002"))
                .collect();
            assert!(
                offending.is_empty(),
                "{name} references the retired code: {offending:?}"
            );
        }
    }
}