use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use futures::{Stream, StreamExt};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: Vec<(String, String)>,
pub body: Option<Vec<u8>>,
}
impl HttpRequest {
pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
Self {
method: method.into(),
url: url.into(),
headers: Vec::new(),
body: None,
}
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = Some(body.into());
self
}
}
pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send>>;
pub type HttpBody = Pin<Box<dyn Stream<Item = Result<Vec<u8>, HttpClientError>> + Send>>;
pub struct HttpResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: HttpBody,
}
impl std::fmt::Debug for HttpResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HttpResponse")
.field("status", &self.status)
.field("headers", &self.headers)
.finish_non_exhaustive()
}
}
impl HttpResponse {
pub fn from_bytes(status: u16, headers: Vec<(String, String)>, body: Vec<u8>) -> Self {
Self {
status,
headers,
body: Box::pin(futures::stream::once(async move { Ok(body) })),
}
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(candidate, _)| candidate.eq_ignore_ascii_case(name))
.map(|(_, value)| value.as_str())
}
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status)
}
pub async fn bytes(self) -> Result<Vec<u8>, HttpClientError> {
self.bytes_limited(DEFAULT_MAX_RESPONSE_BYTES).await
}
pub async fn text(self) -> Result<String, HttpClientError> {
self.text_limited(DEFAULT_MAX_RESPONSE_BYTES).await
}
pub async fn bytes_limited(mut self, limit: usize) -> Result<Vec<u8>, HttpClientError> {
let mut bytes = Vec::new();
while let Some(chunk) = self.body.next().await {
let chunk = chunk?;
if chunk.len() > limit - bytes.len() {
return Err(HttpClientError::BodyTooLarge { limit });
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes)
}
pub async fn text_limited(self, limit: usize) -> Result<String, HttpClientError> {
let bytes = self.bytes_limited(limit).await?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
}
#[async_trait::async_trait]
#[allow(
clippy::double_must_use,
reason = "async_trait annotates generated futures"
)]
pub trait HttpClient: Send + Sync {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError>;
fn sleep(&self, duration: Duration) -> Option<Sleep> {
let _ = duration;
None
}
}
pub type SharedHttpClient = Arc<dyn HttpClient>;
#[derive(Debug)]
#[non_exhaustive]
pub enum HttpClientError {
Required {
option: &'static str,
},
InvalidRequest(String),
Transport {
message: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
BodyTooLarge {
limit: usize,
},
}
impl HttpClientError {
pub fn required(option: &'static str) -> Self {
Self::Required { option }
}
pub fn transport(error: impl std::error::Error + Send + Sync + 'static) -> Self {
Self::Transport {
message: error.to_string(),
source: Some(Box::new(error)),
}
}
pub fn transport_message(message: impl Into<String>) -> Self {
Self::Transport {
message: message.into(),
source: None,
}
}
pub fn code(&self) -> &'static str {
match self {
Self::Required { .. } => "HTTP_CLIENT_REQUIRED",
Self::InvalidRequest(_) => "HTTP_INVALID_REQUEST",
Self::Transport { .. } => "HTTP_TRANSPORT_ERROR",
Self::BodyTooLarge { .. } => "HTTP_BODY_TOO_LARGE",
}
}
pub fn retryable(&self) -> bool {
matches!(self, Self::Transport { .. })
}
pub fn hint(&self) -> Option<String> {
match self {
Self::Required { option } => Some(format!(
"Pass a multicast::outbound::HttpClient in {option}; this target has no default HTTP client"
)),
Self::BodyTooLarge { limit } => Some(format!(
"The response body exceeded {limit} bytes; raise the caller's body limit if the peer is trusted"
)),
_ => None,
}
}
}
impl std::fmt::Display for HttpClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Required { option } => {
write!(f, "an HTTP client is required on this target: set {option}")
}
Self::InvalidRequest(message) => write!(f, "invalid HTTP request: {message}"),
Self::Transport { message, .. } => f.write_str(message),
Self::BodyTooLarge { limit } => {
write!(f, "response body exceeds the {limit}-byte limit")
}
}
}
}
impl std::error::Error for HttpClientError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Transport {
source: Some(source),
..
} => Some(source.as_ref()),
_ => None,
}
}
}
impl From<HttpClientError> for crate::errors::Error {
fn from(error: HttpClientError) -> Self {
crate::errors::Error::Multicast(crate::errors::MulticastError {
message: error.to_string(),
code: error.code().to_string(),
hint: error.hint(),
retryable: error.retryable(),
exit_code: None,
cause: Some(Box::new(error)),
})
}
}
#[cfg(any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Redirects {
#[cfg_attr(not(feature = "openapi"), allow(dead_code))]
Follow,
#[cfg_attr(
not(any(feature = "http", feature = "agent-plugins-mcp")),
allow(dead_code)
)]
Refuse,
}
#[cfg(any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"))]
pub(crate) fn resolve(
client: Option<&SharedHttpClient>,
option: &'static str,
redirects: Redirects,
) -> Result<SharedHttpClient, HttpClientError> {
match client {
Some(client) => Ok(Arc::clone(client)),
None => default_client(option, redirects),
}
}
#[cfg(all(
any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"),
not(target_arch = "wasm32")
))]
fn default_client(
_option: &'static str,
redirects: Redirects,
) -> Result<SharedHttpClient, HttpClientError> {
let client = match redirects {
Redirects::Follow => ReqwestHttpClient::new()?,
Redirects::Refuse => ReqwestHttpClient::without_redirects()?,
};
Ok(Arc::new(client))
}
#[cfg(all(
any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"),
target_arch = "wasm32"
))]
fn default_client(
option: &'static str,
_redirects: Redirects,
) -> Result<SharedHttpClient, HttpClientError> {
Err(HttpClientError::required(option))
}
#[cfg(all(
any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"),
not(target_arch = "wasm32")
))]
pub use reqwest_client::ReqwestHttpClient;
#[cfg(all(
any(feature = "http", feature = "openapi", feature = "agent-plugins-mcp"),
not(target_arch = "wasm32")
))]
mod reqwest_client {
use futures::StreamExt;
use super::{HttpClient, HttpClientError, HttpRequest, HttpResponse, Sleep};
#[derive(Debug, Clone)]
pub struct ReqwestHttpClient {
client: reqwest::Client,
}
impl ReqwestHttpClient {
pub fn new() -> Result<Self, HttpClientError> {
reqwest::Client::builder()
.build()
.map(Self::from_client)
.map_err(HttpClientError::transport)
}
pub fn without_redirects() -> Result<Self, HttpClientError> {
reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.map(Self::from_client)
.map_err(HttpClientError::transport)
}
pub fn from_client(client: reqwest::Client) -> Self {
Self { client }
}
}
#[async_trait::async_trait]
impl HttpClient for ReqwestHttpClient {
async fn send(&self, request: HttpRequest) -> Result<HttpResponse, HttpClientError> {
let method = reqwest::Method::from_bytes(request.method.as_bytes()).map_err(|_| {
HttpClientError::InvalidRequest(format!(
"`{}` is not a valid method",
request.method
))
})?;
let mut headers = reqwest::header::HeaderMap::with_capacity(request.headers.len());
for (name, value) in &request.headers {
let header =
reqwest::header::HeaderName::from_bytes(name.as_bytes()).map_err(|_| {
HttpClientError::InvalidRequest(format!(
"`{name}` is not a valid header name"
))
})?;
let value = reqwest::header::HeaderValue::from_str(value).map_err(|_| {
HttpClientError::InvalidRequest(format!(
"the value for header `{name}` is not valid"
))
})?;
headers.append(header, value);
}
let mut builder = self.client.request(method, &request.url).headers(headers);
if let Some(body) = request.body {
builder = builder.body(body);
}
let response = builder.send().await.map_err(HttpClientError::transport)?;
let status = response.status().as_u16();
let headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_string(),
String::from_utf8_lossy(value.as_bytes()).into_owned(),
)
})
.collect();
let body = response.bytes_stream().map(|chunk| {
chunk
.map(|bytes| bytes.to_vec())
.map_err(HttpClientError::transport)
});
Ok(HttpResponse {
status,
headers,
body: Box::pin(body),
})
}
fn sleep(&self, duration: std::time::Duration) -> Option<Sleep> {
Some(Box::pin(tokio::time::sleep(duration)))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_missing_client_maps_to_a_coded_error_naming_the_option() {
let error =
crate::errors::Error::from(HttpClientError::required("McpRemoteOptions::http_client"));
let crate::errors::Error::Multicast(error) = error else {
panic!("expected a coded error");
};
assert_eq!(error.code, "HTTP_CLIENT_REQUIRED");
assert!(!error.retryable);
assert!(
error
.hint
.as_deref()
.is_some_and(|hint| hint.contains("McpRemoteOptions::http_client")),
"{:?}",
error.hint
);
}
#[test]
fn response_headers_are_matched_case_insensitively() {
let response = HttpResponse::from_bytes(
200,
vec![("Content-Type".to_string(), "text/plain".to_string())],
b"ok".to_vec(),
);
assert_eq!(response.header("content-type"), Some("text/plain"));
assert!(response.is_success());
let text = futures::executor::block_on(response.text()).unwrap();
assert_eq!(text, "ok");
}
#[test]
fn a_long_body_stops_at_the_cap_with_a_coded_error() {
let pulled = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counter = Arc::clone(&pulled);
let endless = futures::stream::repeat_with(move || {
counter.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
Ok(vec![b'x'; 1024])
})
.take(1000);
let response = HttpResponse {
status: 200,
headers: Vec::new(),
body: Box::pin(endless),
};
let error = futures::executor::block_on(response.bytes_limited(10 * 1024)).unwrap_err();
assert_eq!(error.code(), "HTTP_BODY_TOO_LARGE");
assert!(!error.retryable());
assert_eq!(pulled.load(std::sync::atomic::Ordering::SeqCst), 11);
let crate::errors::Error::Multicast(error) = crate::errors::Error::from(error) else {
panic!("expected a coded error");
};
assert_eq!(error.code, "HTTP_BODY_TOO_LARGE");
let exact = HttpResponse::from_bytes(200, Vec::new(), vec![b'y'; 8]);
assert_eq!(
futures::executor::block_on(exact.bytes_limited(8)).unwrap(),
vec![b'y'; 8]
);
}
}