use rmcp::{
service::{ClientInitializeError, RunningService},
transport::{
streamable_http_client::{StreamableHttpClientTransportConfig, StreamableHttpError},
StreamableHttpClientTransport,
},
RoleClient, ServiceExt,
};
use super::{
client::{McpClientHandler, McpClientServices},
elicitation::{McpElicitationService, McpElicitationSupport},
http_client::McpTransportClient,
inflight::McpInFlightCalls,
oauth,
progress::McpProgressRouter,
roots::McpRoots,
};
pub(crate) type BearerConnection = RunningService<RoleClient, McpClientHandler>;
#[derive(Debug, thiserror::Error)]
pub(crate) enum BearerError {
#[error("it refused the secret (401 Unauthorized)")]
Unauthorized,
#[error("{0}")]
Failed(String),
}
pub(crate) async fn connect_bearer(
identity: &str,
url: &url::Url,
pinned: &[std::net::SocketAddr],
secret: &str,
) -> Result<BearerConnection, BearerError> {
let (events, _) = tokio::sync::mpsc::unbounded_channel();
let handler = McpClientHandler::new(
identity,
McpRoots::default(),
McpProgressRouter::new(),
events,
McpClientServices {
elicit: McpElicitationService::new(
identity,
McpInFlightCalls::new(),
McpElicitationSupport::Unavailable,
),
},
);
let client = if url.scheme() == "http" {
let mut builder = crate::reqwest_client_builder()
.pool_max_idle_per_host(0)
.redirect(reqwest::redirect::Policy::none())
.no_proxy();
if let (Some(domain), false) = (url.domain(), pinned.is_empty()) {
builder = builder.resolve_to_addrs(domain, pinned);
}
builder
.build()
.map_err(|error| BearerError::Failed(error.to_string()))?
} else {
oauth::transport_http_client().map_err(|error| BearerError::Failed(format!("{error:#}")))?
};
let client = McpTransportClient::Plain(client);
let config = StreamableHttpClientTransportConfig::with_uri(url.to_string())
.auth_header(secret.to_owned());
let transport = StreamableHttpClientTransport::with_client(client, config);
handler.serve(transport).await.map_err(describe)
}
fn describe(error: ClientInitializeError) -> BearerError {
let ClientInitializeError::TransportError { error, .. } = &error else {
return BearerError::Failed(error.to_string());
};
match error
.error
.downcast_ref::<StreamableHttpError<reqwest::Error>>()
{
Some(StreamableHttpError::AuthRequired(_)) => BearerError::Unauthorized,
Some(other) => BearerError::Failed(other.to_string()),
None => BearerError::Failed(error.error.to_string()),
}
}