anda_engine 0.18.2

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
//! HTTP byte policy under rmcp's lifecycle, request routing, and SSE transport.
//! All protocol messages use rmcp types; this adapter only handles HTTP responses.

use anda_core::BoxError;
use futures::{StreamExt, TryStreamExt};
use http::{HeaderName, HeaderValue};
use reqwest::{Client, Response, StatusCode};
use rmcp::{
    model::{ClientJsonRpcMessage, ClientRequest, ErrorData, ServerJsonRpcMessage},
    transport::{
        auth::WWWAuthenticateParams,
        common::client_side_sse::BoxedSseResponse,
        streamable_http_client::{
            AuthRequiredError, HttpStatusError, InsufficientScopeError, StreamableHttpClient,
            StreamableHttpError, StreamableHttpPostResponse, StreamableHttpResponseLimits,
        },
    },
};
use std::{collections::HashMap, sync::Arc, time::Duration};

const MAX_RETRY_AFTER_BYTES: usize = 128;

#[derive(Debug, thiserror::Error)]
pub(super) enum HttpError {
    #[error(transparent)]
    Request(#[from] reqwest::Error),
    #[error("MCP HTTP response exceeds the byte budget")]
    Limit,
    #[error("MCP HTTP status {0}")]
    Status(u16),
}

type Error = StreamableHttpError<HttpError>;

#[derive(Clone)]
pub(super) struct McpHttpClient {
    client: Client,
    limit: usize,
}
impl McpHttpClient {
    pub fn new(limit: usize) -> Result<Self, BoxError> {
        Ok(Self {
            client: Client::builder()
                .redirect(reqwest::redirect::Policy::none())
                .connect_timeout(Duration::from_secs(15))
                .build()?,
            limit,
        })
    }

    fn request(
        &self,
        method: reqwest::Method,
        uri: &str,
        session: Option<&str>,
        token: Option<&str>,
        headers: HashMap<HeaderName, HeaderValue>,
    ) -> Result<reqwest::RequestBuilder, Error> {
        let mut request = self
            .client
            .request(method, uri)
            .header("accept", "application/json, text/event-stream");
        for (name, value) in headers {
            if matches!(
                name.as_str(),
                "accept" | "mcp-session-id" | "last-event-id" | "content-length" | "host"
            ) {
                return Err(StreamableHttpError::ReservedHeaderConflict(
                    name.to_string(),
                ));
            }
            request = request.header(name, value);
        }
        if let Some(session) = session {
            request = request.header("mcp-session-id", session);
        }
        if let Some(token) = token {
            request = request.bearer_auth(token);
        }
        Ok(request)
    }

    fn check_auth(uri: &str, response: &Response) -> Result<(), Error> {
        let status = response.status();
        if !matches!(status, StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN) {
            return Ok(());
        }
        let Some(header) = response
            .headers()
            .get("www-authenticate")
            .and_then(|h| h.to_str().ok())
        else {
            return Err(StreamableHttpError::Client(HttpError::Status(
                status.as_u16(),
            )));
        };
        if status == StatusCode::UNAUTHORIZED {
            Err(StreamableHttpError::AuthRequired(AuthRequiredError::new(
                header.to_string(),
            )))
        } else {
            let scope = reqwest::Url::parse(uri)
                .ok()
                .and_then(|base_url| WWWAuthenticateParams::parse(header, &base_url).scope);
            Err(StreamableHttpError::InsufficientScope(
                InsufficientScopeError::new(header.to_string(), scope),
            ))
        }
    }

    async fn body_with_limit(&self, response: Response, limit: usize) -> Result<Vec<u8>, Error> {
        let limit = self.limit.min(limit);
        if response.content_length().is_some_and(|n| n > limit as u64) {
            return Err(StreamableHttpError::Client(HttpError::Limit));
        }
        let mut bytes = Vec::new();
        let mut stream = response.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let chunk =
                chunk.map_err(|err| StreamableHttpError::Client(HttpError::Request(err)))?;
            if chunk.len() > limit.saturating_sub(bytes.len()) {
                return Err(StreamableHttpError::Client(HttpError::Limit));
            }
            bytes.extend_from_slice(&chunk);
        }
        Ok(bytes)
    }

    #[cfg(test)]
    fn events(&self, response: Response) -> BoxedSseResponse {
        self.events_with_limit(response, self.limit)
    }

    fn events_with_limit(&self, response: Response, max_sse_event_size: usize) -> BoxedSseResponse {
        let limit = self.limit.min(max_sse_event_size);
        let mut budget = EventBudget::default();
        let bounded = response.bytes_stream().map(move |chunk| {
            let chunk = chunk.map_err(HttpError::Request)?;
            budget.observe(&chunk, limit)?;
            Ok::<_, HttpError>(chunk)
        });
        // Move the decoded fields into rmcp's public SSE type at the transport boundary.
        sse_stream::SseByteStream::new(bounded)
            .map_ok(|event| rmcp_sse_stream::Sse {
                event: event.event,
                data: event.data,
                id: event.id,
                retry: event.retry,
            })
            .map_err(|err| match err {
                sse_stream::Error::Body(source) => rmcp_sse_stream::Error::Body(source),
                sse_stream::Error::Utf8Parse(source) => rmcp_sse_stream::Error::Utf8Parse(source),
                _ => rmcp_sse_stream::Error::InvalidLine,
            })
            .boxed()
    }
}

fn http_status_error(status: StatusCode, headers: &http::HeaderMap) -> Option<HttpStatusError> {
    if status != StatusCode::TOO_MANY_REQUESTS && !status.is_server_error() {
        return None;
    }
    let retry_after = headers
        .get(http::header::RETRY_AFTER)
        .filter(|value| value.as_bytes().len() <= MAX_RETRY_AFTER_BYTES)
        .and_then(|value| std::str::from_utf8(value.as_bytes()).ok())
        .map(str::to_owned);
    Some(HttpStatusError::new(status.as_u16(), retry_after))
}

fn media_type_is(header: &str, expected: &str) -> bool {
    header
        .split(';')
        .next()
        .is_some_and(|ty| ty.trim().eq_ignore_ascii_case(expected))
}

/// Count raw event bytes before the SSE parser can accumulate them. CR, LF and
/// split CRLF are supported. Comments count toward the same conservative budget.
#[derive(Default)]
pub(super) struct EventBudget {
    line: usize,
    event: usize,
    was_cr: bool,
}
impl EventBudget {
    pub(super) fn observe(&mut self, bytes: &[u8], limit: usize) -> Result<(), HttpError> {
        for &byte in bytes {
            if self.was_cr {
                self.was_cr = false;
                if byte == b'\n' {
                    continue;
                }
            }
            if byte == b'\r' || byte == b'\n' {
                if self.line == 0 {
                    self.event = 0;
                } else {
                    self.event = self.event.saturating_add(self.line).saturating_add(1);
                }
                self.line = 0;
                self.was_cr = byte == b'\r';
            } else {
                self.line = self.line.saturating_add(1);
            }
            if self.event.saturating_add(self.line) > limit {
                return Err(HttpError::Limit);
            }
        }
        Ok(())
    }
}

impl StreamableHttpClient for McpHttpClient {
    type Error = HttpError;

    async fn post_message(
        &self,
        uri: Arc<str>,
        message: ClientJsonRpcMessage,
        session: Option<Arc<str>>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
    ) -> Result<StreamableHttpPostResponse, Error> {
        let mut limits = StreamableHttpResponseLimits::default();
        limits.max_sse_event_size = self.limit;
        limits.max_json_response_size = self.limit;
        self.post_message_with_response_limits(uri, message, session, token, headers, limits)
            .await
    }

    async fn post_message_with_max_sse_event_size(
        &self,
        uri: Arc<str>,
        message: ClientJsonRpcMessage,
        session: Option<Arc<str>>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
        max_sse_event_size: usize,
    ) -> Result<StreamableHttpPostResponse, Error> {
        let mut limits = StreamableHttpResponseLimits::default();
        limits.max_sse_event_size = max_sse_event_size;
        limits.max_json_response_size = self.limit;
        self.post_message_with_response_limits(uri, message, session, token, headers, limits)
            .await
    }

    async fn post_message_with_response_limits(
        &self,
        uri: Arc<str>,
        message: ClientJsonRpcMessage,
        session: Option<Arc<str>>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
        limits: StreamableHttpResponseLimits,
    ) -> Result<StreamableHttpPostResponse, Error> {
        let response = self
            .request(
                reqwest::Method::POST,
                &uri,
                session.as_deref(),
                token.as_deref(),
                headers,
            )?
            .json(&message)
            .send()
            .await
            .map_err(|err| StreamableHttpError::Client(HttpError::Request(err)))?;
        Self::check_auth(&uri, &response)?;
        let status = response.status();
        if matches!(status, StatusCode::ACCEPTED | StatusCode::NO_CONTENT) {
            return Ok(StreamableHttpPostResponse::Accepted);
        }
        if status == StatusCode::NOT_FOUND && session.is_some() {
            return Err(StreamableHttpError::SessionExpired);
        }
        let content_type = response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("")
            .to_string();
        let is_json = media_type_is(&content_type, "application/json");
        let is_sse = media_type_is(&content_type, "text/event-stream");
        let status_error = http_status_error(status, response.headers());
        // Rate limits and non-JSON server failures return body-free metadata
        // without buffering the response stream.
        if let Some(error) = status_error.as_ref()
            && (!is_json || status == StatusCode::TOO_MANY_REQUESTS)
        {
            return Err(HttpStatusError::new(error.status, error.retry_after.clone()).into());
        }
        let returned_session = response
            .headers()
            .get("mcp-session-id")
            .and_then(|v| v.to_str().ok())
            .map(str::to_string);
        if status.is_success() && is_sse {
            return Ok(StreamableHttpPostResponse::Sse(
                self.events_with_limit(response, limits.max_sse_event_size),
                returned_session,
            ));
        }
        let awaits_no_response = !matches!(message, ClientJsonRpcMessage::Request(_));
        if status.is_success() && awaits_no_response && !is_json {
            return Ok(StreamableHttpPostResponse::Accepted);
        }
        if !status.is_success() {
            // Let the SDK classify legacy discovery rejection, including middleware
            // that uses a different id. Authorization and 5xx never trigger this path.
            let discover_request_id = if session.is_none()
                && status.is_client_error()
                && let ClientJsonRpcMessage::Request(request) = &message
                && matches!(request.request, ClientRequest::DiscoverRequest(_))
            {
                Some(request.id.clone())
            } else {
                None
            };
            if !is_json {
                if let Some(request_id) = discover_request_id {
                    return Ok(StreamableHttpPostResponse::Json(
                        ServerJsonRpcMessage::error(
                            ErrorData::invalid_request(
                                format!("discovery rejected: HTTP {status}"),
                                None,
                            ),
                            Some(request_id),
                        ),
                        None,
                    ));
                }
                return Err(StreamableHttpError::Client(HttpError::Status(
                    status.as_u16(),
                )));
            }
            let body = match self
                .body_with_limit(response, limits.max_json_response_size)
                .await
            {
                Ok(body) => body,
                Err(StreamableHttpError::Client(HttpError::Limit)) if status_error.is_some() => {
                    return Err(status_error.expect("checked above").into());
                }
                Err(err) => return Err(err),
            };
            if let Some(request_id) = discover_request_id {
                let error = match serde_json::from_slice::<ServerJsonRpcMessage>(&body) {
                    Ok(ServerJsonRpcMessage::Error(error)) => error.error,
                    _ => ErrorData::invalid_request(
                        format!("discovery rejected: HTTP {status}"),
                        None,
                    ),
                };
                return Ok(StreamableHttpPostResponse::Json(
                    ServerJsonRpcMessage::error(error, Some(request_id)),
                    None,
                ));
            }
            if let Ok(error @ ServerJsonRpcMessage::Error(_)) = serde_json::from_slice(&body) {
                return Ok(StreamableHttpPostResponse::Json(error, returned_session));
            }
            if let Some(error) = status_error {
                return Err(error.into());
            }
            return Err(StreamableHttpError::Client(HttpError::Status(
                status.as_u16(),
            )));
        }
        if !is_json {
            return Err(StreamableHttpError::UnexpectedContentType(Some(
                content_type,
            )));
        }
        let body = self
            .body_with_limit(response, limits.max_json_response_size)
            .await?;
        if awaits_no_response && body.is_empty() {
            return Ok(StreamableHttpPostResponse::Accepted);
        }
        match serde_json::from_slice(&body) {
            Ok(message) => Ok(StreamableHttpPostResponse::Json(message, returned_session)),
            Err(_) if awaits_no_response => Ok(StreamableHttpPostResponse::Accepted),
            Err(err) => Err(StreamableHttpError::Deserialize(err)),
        }
    }

    async fn get_stream(
        &self,
        uri: Arc<str>,
        session: Option<Arc<str>>,
        last_event_id: Option<String>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
    ) -> Result<BoxedSseResponse, Error> {
        self.get_stream_with_max_sse_event_size(
            uri,
            session,
            last_event_id,
            token,
            headers,
            self.limit,
        )
        .await
    }

    async fn get_stream_with_max_sse_event_size(
        &self,
        uri: Arc<str>,
        session: Option<Arc<str>>,
        last_event_id: Option<String>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
        max_sse_event_size: usize,
    ) -> Result<BoxedSseResponse, Error> {
        let mut request = self.request(
            reqwest::Method::GET,
            &uri,
            session.as_deref(),
            token.as_deref(),
            headers,
        )?;
        if let Some(id) = last_event_id {
            request = request.header("last-event-id", id);
        }
        let response = request
            .send()
            .await
            .map_err(|err| StreamableHttpError::Client(HttpError::Request(err)))?;
        Self::check_auth(&uri, &response)?;
        if response.status() == StatusCode::METHOD_NOT_ALLOWED {
            return Err(StreamableHttpError::ServerDoesNotSupportSse);
        }
        if let Some(error) = http_status_error(response.status(), response.headers()) {
            return Err(error.into());
        }
        if !response.status().is_success() {
            return Err(StreamableHttpError::Client(HttpError::Status(
                response.status().as_u16(),
            )));
        }
        let content_type = response
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        if !media_type_is(content_type, "text/event-stream") {
            return Err(StreamableHttpError::UnexpectedContentType(Some(
                content_type.into(),
            )));
        }
        Ok(self.events_with_limit(response, max_sse_event_size))
    }

    async fn delete_session(
        &self,
        uri: Arc<str>,
        session: Arc<str>,
        token: Option<String>,
        headers: HashMap<HeaderName, HeaderValue>,
    ) -> Result<(), Error> {
        let response = self
            .request(
                reqwest::Method::DELETE,
                &uri,
                Some(&session),
                token.as_deref(),
                headers,
            )?
            .send()
            .await
            .map_err(|err| StreamableHttpError::Client(HttpError::Request(err)))?;
        Self::check_auth(&uri, &response)?;
        if response.status().is_success() || response.status() == StatusCode::METHOD_NOT_ALLOWED {
            Ok(())
        } else if let Some(error) = http_status_error(response.status(), response.headers()) {
            Err(error.into())
        } else {
            Err(StreamableHttpError::Client(HttpError::Status(
                response.status().as_u16(),
            )))
        }
    }
}

/// Retry safe reads only, with the caller's outer deadline spanning every attempt.
pub(super) async fn retry_read<T, F, Fut>(mut operation: F) -> Result<T, BoxError>
where
    F: FnMut() -> Fut,
    Fut: std::future::Future<Output = Result<T, rmcp::service::ServiceError>>,
{
    for delay in [250, 1_000] {
        match operation().await {
            Ok(value) => return Ok(value),
            Err(err) if is_transient(&err) => {
                tokio::time::sleep(Duration::from_millis(delay)).await
            }
            Err(err) => return Err(err.into()),
        }
    }
    Ok(operation().await?)
}

pub(super) fn is_transient(error: &(dyn std::error::Error + 'static)) -> bool {
    use rmcp::service::{ClientInitializeError, ServiceError};
    if let Some(ServiceError::TransportSend(transport)) = error.downcast_ref::<ServiceError>() {
        return is_transient(transport.error.as_ref());
    }
    if let Some(error) = error.downcast_ref::<ClientInitializeError>() {
        return match error {
            ClientInitializeError::TransportError { error, .. } => {
                is_transient(error.error.as_ref())
            }
            ClientInitializeError::LegacyFallbackFailed { fallback, .. } => {
                is_transient(fallback.as_ref())
            }
            _ => false,
        };
    }
    match error.downcast_ref::<StreamableHttpError<HttpError>>() {
        Some(StreamableHttpError::HttpStatus(error)) => {
            matches!(error.status, 408 | 429 | 500 | 502 | 503 | 504)
        }
        Some(StreamableHttpError::Client(HttpError::Status(408 | 429 | 500 | 502 | 503 | 504))) => {
            true
        }
        Some(StreamableHttpError::Client(HttpError::Request(error))) => {
            error.is_connect() || error.is_timeout()
        }
        _ => false,
    }
}

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

    #[test]
    fn media_types_match_case_insensitively_and_in_full() {
        assert!(media_type_is(
            "Application/JSON; charset=utf-8",
            "application/json"
        ));
        assert!(media_type_is("TEXT/EVENT-STREAM", "text/event-stream"));
        assert!(!media_type_is("application/json-seq", "application/json"));
    }

    #[tokio::test]
    async fn sdk_receives_complete_decoded_events_and_budget_errors() {
        let client = McpHttpClient::new(64).unwrap();
        let chunks = [
            b"id: 42\r".as_slice(),
            b"\nevent: message\nretry: 250\ndata: first\ndata: second\n\n",
        ];
        let body = reqwest::Body::wrap_stream(futures::stream::iter(
            chunks.into_iter().map(Ok::<_, std::io::Error>),
        ));
        let mut events = client.events(Response::from(http::Response::new(body)));
        let event = events.next().await.unwrap().unwrap();
        assert_eq!(event.event.as_deref(), Some("message"));
        assert_eq!(event.data.as_deref(), Some("first\nsecond"));
        assert_eq!(event.id.as_deref(), Some("42"));
        assert_eq!(event.retry, Some(250));
        assert!(events.next().await.is_none());

        let comments = ":a keep-alive comment\n".repeat(4);
        let mut events = client.events(Response::from(http::Response::new(comments)));
        assert!(
            events
                .next()
                .await
                .unwrap()
                .unwrap_err()
                .to_string()
                .contains("byte budget")
        );
        assert!(events.next().await.is_none());
    }

    #[tokio::test]
    async fn http_client_handles_3_11_status_scope_notification_and_limits() {
        use axum::{Router, extract::Path, response::IntoResponse, routing::post};
        use rmcp::model::{
            ClientJsonRpcMessage, ClientNotification, ClientRequest, DiscoverRequest,
            DiscoverRequestParams, InitializedNotification, NumberOrString,
        };

        async fn handler(Path(mode): Path<String>) -> axum::response::Response {
            match mode.as_str() {
                "forbidden_scope" => (
                    StatusCode::FORBIDDEN,
                    [(
                        "www-authenticate",
                        r#"Bearer error="insufficient_scope", scope="files:read files:write""#,
                    )],
                    "forbidden",
                )
                    .into_response(),
                "rate_limit" => (
                    StatusCode::TOO_MANY_REQUESTS,
                    [("retry-after", "30"), ("content-type", "application/json")],
                    "x".repeat(4096),
                )
                    .into_response(),
                "unavailable" => (
                    StatusCode::SERVICE_UNAVAILABLE,
                    [("retry-after", "5"), ("content-type", "text/plain")],
                    "x".repeat(4096),
                )
                    .into_response(),
                "json_500_rpc" => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    [("content-type", "application/json")],
                    r#"{"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"boom"}}"#,
                )
                    .into_response(),
                "json_500_huge" => (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    [("content-type", "application/json")],
                    format!(r#"{{"pad":"{}"}}"#, "x".repeat(4096)),
                )
                    .into_response(),
                "notify_text" => {
                    (StatusCode::OK, [("content-type", "text/plain")], "accepted").into_response()
                }
                "discover_html_404" => (
                    StatusCode::NOT_FOUND,
                    [("content-type", "text/html")],
                    format!("<html>{}</html>", "x".repeat(4096)),
                )
                    .into_response(),
                "ok_json" => (
                    StatusCode::OK,
                    [("content-type", "application/json")],
                    r#"{"jsonrpc":"2.0","id":1,"result":{"tools":[]}}"#,
                )
                    .into_response(),
                _ => StatusCode::NOT_FOUND.into_response(),
            }
        }

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let app = Router::new().route("/{mode}", post(handler));
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let client = McpHttpClient::new(256).unwrap();
        let req_msg = ClientJsonRpcMessage::request(
            ClientRequest::DiscoverRequest(DiscoverRequest::new(DiscoverRequestParams {})),
            NumberOrString::Number(7),
        );
        let notify_msg = ClientJsonRpcMessage::notification(
            ClientNotification::InitializedNotification(InitializedNotification::default()),
        );

        // 403 WWW-Authenticate preserves required_scope.
        let err = client
            .post_message(
                Arc::from(format!("{base}/forbidden_scope")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap_err();
        match err {
            StreamableHttpError::InsufficientScope(scope_err) => {
                assert_eq!(
                    scope_err.required_scope.as_deref(),
                    Some("files:read files:write")
                );
                assert!(scope_err.can_upgrade());
            }
            other => panic!("expected InsufficientScope, got {other:?}"),
        }

        // 429 returns body-free HttpStatusError with Retry-After even when body > limit.
        let err = client
            .post_message(
                Arc::from(format!("{base}/rate_limit")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap_err();
        assert!(is_transient(&err));
        match err {
            StreamableHttpError::HttpStatus(status_err) => {
                assert_eq!(status_err.status, 429);
                assert_eq!(status_err.retry_after.as_deref(), Some("30"));
            }
            other => panic!("expected HttpStatus(429), got {other:?}"),
        }

        // 503 non-JSON returns body-free HttpStatusError with Retry-After.
        let err = client
            .post_message(
                Arc::from(format!("{base}/unavailable")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap_err();
        assert!(is_transient(&err));
        match err {
            StreamableHttpError::HttpStatus(status_err) => {
                assert_eq!(status_err.status, 503);
                assert_eq!(status_err.retry_after.as_deref(), Some("5"));
            }
            other => panic!("expected HttpStatus(503), got {other:?}"),
        }

        // 500 JSON-RPC error is preserved.
        let resp = client
            .post_message(
                Arc::from(format!("{base}/json_500_rpc")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap();
        assert!(matches!(
            resp,
            StreamableHttpPostResponse::Json(ServerJsonRpcMessage::Error(_), _)
        ));

        // Oversized 500 JSON falls back to body-free HttpStatusError(500).
        let err = client
            .post_message(
                Arc::from(format!("{base}/json_500_huge")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap_err();
        assert!(matches!(
            err,
            StreamableHttpError::HttpStatus(status_err) if status_err.status == 500
        ));

        // 200 OK with non-JSON content-type on a notification POST is Accepted.
        let resp = client
            .post_message(
                Arc::from(format!("{base}/notify_text")),
                notify_msg,
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap();
        assert!(matches!(resp, StreamableHttpPostResponse::Accepted));

        // 404 oversized HTML on sessionless discover synthesizes invalid_request without OOM/limit error.
        let resp = client
            .post_message(
                Arc::from(format!("{base}/discover_html_404")),
                req_msg.clone(),
                None,
                None,
                HashMap::new(),
            )
            .await
            .unwrap();
        match resp {
            StreamableHttpPostResponse::Json(ServerJsonRpcMessage::Error(err), None) => {
                assert_eq!(err.id, Some(NumberOrString::Number(7)));
            }
            other => panic!("expected synthesized discover error, got {other:?}"),
        }

        // Tighter per-call response limits are enforced.
        let mut tight = StreamableHttpResponseLimits::default();
        tight.max_json_response_size = 16;
        let err = client
            .post_message_with_response_limits(
                Arc::from(format!("{base}/ok_json")),
                req_msg,
                None,
                None,
                HashMap::new(),
                tight,
            )
            .await
            .unwrap_err();
        assert!(matches!(err, StreamableHttpError::Client(HttpError::Limit)));

        server.abort();
    }
}