use super::auth::McpAuth;
#[cfg(feature = "http-transport")]
use super::auth::OAuth2Config;
use super::elicitation::ElicitationHandler;
use super::resource_notifications::ResourceNotificationHandler;
#[cfg(feature = "http-transport")]
use adk_core::Url;
use adk_core::{ActingContext, AdkError, CredentialBroker, Result};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
#[cfg(feature = "http-transport")]
use reqwest::header::{HeaderName, HeaderValue};
#[cfg(feature = "http-transport")]
use rmcp::{
model::ClientJsonRpcMessage,
transport::{
common::client_side_sse::BoxedSseResponse,
streamable_http_client::{
StreamableHttpClient, StreamableHttpError, StreamableHttpPostResponse,
},
},
};
#[cfg(feature = "http-transport")]
type HttpResult<T> = std::result::Result<T, StreamableHttpError<reqwest::Error>>;
#[cfg_attr(not(feature = "http-transport"), allow(dead_code))]
#[derive(Clone)]
struct BrokeredAuth {
broker: Arc<dyn CredentialBroker>,
acting: ActingContext,
scopes: Vec<String>,
}
#[cfg(feature = "http-transport")]
impl BrokeredAuth {
async fn bearer_for(&self, resource: &Url, request: &Url) -> Result<String> {
let token = self.broker.token_for(&self.acting, resource, &self.scopes).await?;
Ok(token.authorize_for(request)?.expose().to_string())
}
}
#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct McpHttpClient {
inner: reqwest::Client,
oauth: Option<Arc<OAuth2Config>>,
brokered: Option<(Arc<BrokeredAuth>, Url)>,
}
#[cfg(feature = "http-transport")]
impl McpHttpClient {
async fn authorized<T, F, Fut>(
&self,
uri: Arc<str>,
configured: Option<String>,
send: F,
) -> HttpResult<T>
where
F: Fn(Option<String>) -> Fut,
Fut: Future<Output = HttpResult<T>>,
{
if let Some((brokered, resource)) = &self.brokered {
let request = Url::parse(&uri).map_err(|error| {
StreamableHttpError::UnexpectedServerResponse(
format!("invalid MCP request URL '{uri}': {error}").into(),
)
})?;
let token = brokered.bearer_for(resource, &request).await.map_err(|error| {
StreamableHttpError::UnexpectedServerResponse(
format!("brokered credential is unavailable: {error}").into(),
)
})?;
return send(Some(token)).await;
}
let Some(oauth) = &self.oauth else {
return send(configured).await;
};
let token = oauth_token(oauth).await?;
match send(Some(token.clone())).await {
Err(StreamableHttpError::AuthRequired(_)) => {}
Err(StreamableHttpError::UnexpectedServerResponse(message))
if message.starts_with("HTTP 401 ") => {}
Err(StreamableHttpError::Client(error))
if error.status() == Some(reqwest::StatusCode::UNAUTHORIZED) => {}
result => return result,
}
tracing::debug!("MCP server rejected the OAuth2 access token; fetching a new one");
oauth.discard_token(&token).await;
send(Some(oauth_token(oauth).await?)).await
}
}
#[cfg(feature = "http-transport")]
async fn oauth_token(oauth: &OAuth2Config) -> HttpResult<String> {
oauth.get_or_refresh_token().await.map_err(|error| {
StreamableHttpError::UnexpectedServerResponse(
format!("OAuth2 access token is unavailable: {error}").into(),
)
})
}
#[cfg(feature = "http-transport")]
impl StreamableHttpClient for McpHttpClient {
type Error = reqwest::Error;
fn post_message(
&self,
uri: Arc<str>,
message: ClientJsonRpcMessage,
session_id: Option<Arc<str>>,
auth_header: Option<String>,
custom_headers: HashMap<HeaderName, HeaderValue>,
) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
self.authorized(uri.clone(), auth_header, move |token| {
self.inner.post_message(
uri.clone(),
message.clone(),
session_id.clone(),
token,
custom_headers.clone(),
)
})
}
fn post_message_with_max_sse_event_size(
&self,
uri: Arc<str>,
message: ClientJsonRpcMessage,
session_id: Option<Arc<str>>,
auth_header: Option<String>,
custom_headers: HashMap<HeaderName, HeaderValue>,
max_sse_event_size: usize,
) -> impl Future<Output = HttpResult<StreamableHttpPostResponse>> + Send + '_ {
self.authorized(uri.clone(), auth_header, move |token| {
self.inner.post_message_with_max_sse_event_size(
uri.clone(),
message.clone(),
session_id.clone(),
token,
custom_headers.clone(),
max_sse_event_size,
)
})
}
fn delete_session(
&self,
uri: Arc<str>,
session_id: Arc<str>,
auth_header: Option<String>,
custom_headers: HashMap<HeaderName, HeaderValue>,
) -> impl Future<Output = HttpResult<()>> + Send + '_ {
self.authorized(uri.clone(), auth_header, move |token| {
self.inner.delete_session(
uri.clone(),
session_id.clone(),
token,
custom_headers.clone(),
)
})
}
fn get_stream(
&self,
uri: Arc<str>,
session_id: Option<Arc<str>>,
last_event_id: Option<String>,
auth_header: Option<String>,
custom_headers: HashMap<HeaderName, HeaderValue>,
) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
self.authorized(uri.clone(), auth_header, move |token| {
self.inner.get_stream(
uri.clone(),
session_id.clone(),
last_event_id.clone(),
token,
custom_headers.clone(),
)
})
}
fn get_stream_with_max_sse_event_size(
&self,
uri: Arc<str>,
session_id: Option<Arc<str>>,
last_event_id: Option<String>,
auth_header: Option<String>,
custom_headers: HashMap<HeaderName, HeaderValue>,
max_sse_event_size: usize,
) -> impl Future<Output = HttpResult<BoxedSseResponse>> + Send + '_ {
self.authorized(uri.clone(), auth_header, move |token| {
self.inner.get_stream_with_max_sse_event_size(
uri.clone(),
session_id.clone(),
last_event_id.clone(),
token,
custom_headers.clone(),
max_sse_event_size,
)
})
}
}
#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct HttpConnectionFactory {
builder: McpHttpClientBuilder,
}
#[cfg(feature = "http-transport")]
#[derive(Clone)]
struct HttpElicitationConnectionFactory {
builder: McpHttpClientBuilder,
handler: Arc<dyn ElicitationHandler>,
resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
}
#[cfg(feature = "http-transport")]
impl HttpElicitationConnectionFactory {
async fn connect_once(
&self,
) -> Result<rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>>
{
use rmcp::ServiceExt;
let transport = self.builder.build_transport().await?;
let mut handler = super::elicitation::AdkClientHandler::new(self.handler.clone());
if let Some(resource_handler) = &self.resource_notification_handler {
handler = handler.with_resource_notification_handler(Arc::clone(resource_handler));
}
if self.builder.tasks.as_ref().is_some_and(|config| config.enable_tasks) {
handler = handler.with_tasks();
}
handler
.serve(transport)
.await
.map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
}
}
#[cfg(feature = "http-transport")]
#[async_trait::async_trait]
impl super::ConnectionFactory<super::elicitation::AdkClientHandler>
for HttpElicitationConnectionFactory
{
async fn create_connection(
&self,
) -> std::result::Result<
rmcp::service::RunningService<rmcp::RoleClient, super::elicitation::AdkClientHandler>,
String,
> {
self.connect_once().await.map_err(|error| error.to_string())
}
}
#[cfg(feature = "http-transport")]
impl HttpConnectionFactory {
async fn connect_once(&self) -> Result<rmcp::service::RunningService<rmcp::RoleClient, ()>> {
use rmcp::ServiceExt;
let transport = self.builder.build_transport().await?;
().serve(transport)
.await
.map_err(|error| AdkError::tool(format!("failed to connect to MCP server: {error}")))
}
}
#[cfg(feature = "http-transport")]
#[async_trait::async_trait]
impl super::ConnectionFactory<()> for HttpConnectionFactory {
async fn create_connection(
&self,
) -> std::result::Result<rmcp::service::RunningService<rmcp::RoleClient, ()>, String> {
self.connect_once().await.map_err(|error| error.to_string())
}
}
#[derive(Clone)]
pub struct McpHttpClientBuilder {
endpoint: String,
auth: McpAuth,
timeout: Duration,
headers: HashMap<String, String>,
elicitation_handler: Option<Arc<dyn ElicitationHandler>>,
resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
reinit_on_expired_session: bool,
brokered: Option<Arc<BrokeredAuth>>,
tasks: Option<super::McpTaskConfig>,
}
impl McpHttpClientBuilder {
pub fn new(endpoint: impl Into<String>) -> Self {
Self {
endpoint: endpoint.into(),
auth: McpAuth::None,
timeout: Duration::from_secs(30),
headers: HashMap::new(),
elicitation_handler: None,
resource_notification_handler: None,
reinit_on_expired_session: true,
brokered: None,
tasks: None,
}
}
pub fn with_credential_broker(
mut self,
broker: Arc<dyn CredentialBroker>,
acting: ActingContext,
scopes: Vec<String>,
) -> Self {
self.brokered = Some(Arc::new(BrokeredAuth { broker, acting, scopes }));
self
}
#[cfg(feature = "http-transport")]
async fn check_brokered(&self) -> Result<Option<(Arc<BrokeredAuth>, Url)>> {
let Some(brokered) = &self.brokered else {
return Ok(None);
};
let resource = adk_core::resource_indicator(&self.endpoint)?;
brokered.bearer_for(&resource, &resource).await?;
Ok(Some((Arc::clone(brokered), resource)))
}
pub fn with_auth(mut self, auth: McpAuth) -> Self {
self.auth = auth;
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.insert(key.into(), value.into());
self
}
pub fn reinit_on_expired_session(mut self, enabled: bool) -> Self {
self.reinit_on_expired_session = enabled;
self
}
#[cfg(feature = "http-transport")]
async fn build_transport(
&self,
) -> Result<rmcp::transport::streamable_http_client::StreamableHttpClientTransport<McpHttpClient>>
{
use adk_core::{ErrorCategory, ErrorComponent};
use rmcp::transport::streamable_http_client::{
StreamableHttpClientTransport, StreamableHttpClientTransportConfig,
};
let mut custom_headers = HashMap::new();
for (name, value) in &self.headers {
let name = HeaderName::from_bytes(name.as_bytes()).map_err(|error| {
AdkError::tool(format!("invalid MCP HTTP header '{name}': {error}"))
})?;
let value = HeaderValue::from_str(value).map_err(|error| {
AdkError::tool(format!("invalid value for MCP HTTP header '{name}': {error}"))
})?;
custom_headers.insert(name, value);
}
let brokered = self.check_brokered().await?;
let mut oauth = None;
let token = match &self.auth {
_ if brokered.is_some() => None,
McpAuth::Bearer(token) => Some(token.clone()),
McpAuth::OAuth2(config) => {
config.get_or_refresh_token().await.map_err(|error| {
AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Unauthorized,
"mcp.oauth.token_fetch",
format!("OAuth2 client-credentials authentication failed: {error}"),
)
})?;
oauth = Some(Arc::clone(config));
None
}
McpAuth::ApiKey { header, key } => {
let name = HeaderName::from_bytes(header.as_bytes()).map_err(|error| {
AdkError::tool(format!("invalid MCP API-key header '{header}': {error}"))
})?;
let value = HeaderValue::from_str(key).map_err(|error| {
AdkError::tool(format!("invalid MCP API-key value for '{header}': {error}"))
})?;
custom_headers.insert(name, value);
None
}
McpAuth::None => None,
};
let mut config = StreamableHttpClientTransportConfig::with_uri(self.endpoint.as_str())
.custom_headers(custom_headers)
.reinit_on_expired_session(self.reinit_on_expired_session);
if let Some(token) = token {
config = config.auth_header(token);
}
let inner = reqwest::Client::builder()
.timeout(self.timeout)
.build()
.map_err(|error| AdkError::tool(format!("failed to build MCP HTTP client: {error}")))?;
Ok(StreamableHttpClientTransport::with_client(
McpHttpClient { inner, oauth, brokered },
config,
))
}
pub fn with_elicitation_handler(mut self, handler: Arc<dyn ElicitationHandler>) -> Self {
self.elicitation_handler = Some(handler);
self
}
pub fn with_task_support(mut self, config: super::McpTaskConfig) -> Self {
self.tasks = Some(config);
self
}
pub fn with_resource_notification_handler(
mut self,
handler: Arc<dyn ResourceNotificationHandler>,
) -> Self {
self.resource_notification_handler = Some(handler);
self
}
pub fn endpoint(&self) -> &str {
&self.endpoint
}
pub fn get_timeout(&self) -> Duration {
self.timeout
}
pub fn get_auth(&self) -> &McpAuth {
&self.auth
}
#[cfg(feature = "http-transport")]
pub async fn connect(self) -> Result<super::McpToolset<()>> {
if self.tasks.is_some() {
return Err(AdkError::tool(
"a toolset with task support answers its tasks' input requests; set a handler \
with `with_elicitation_handler` and connect with `connect_with_elicitation`",
));
}
self.check_brokered().await?;
let factory = Arc::new(HttpConnectionFactory { builder: self.clone() });
let client = factory.connect_once().await?;
Ok(super::McpToolset::new(client).with_connection_factory(factory))
}
#[cfg(not(feature = "http-transport"))]
pub async fn connect(self) -> Result<()> {
Err(AdkError::tool(
"HTTP transport requires the 'http-transport' feature. \
Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
))
}
#[cfg(feature = "http-transport")]
pub async fn connect_with_elicitation(
self,
) -> Result<super::McpToolset<super::elicitation::AdkClientHandler>> {
let handler = self.elicitation_handler.clone().ok_or_else(|| {
AdkError::tool(
"connect_with_elicitation requires with_elicitation_handler to be called first",
)
})?;
self.check_brokered().await?;
let resource_notification_handler = self.resource_notification_handler.clone();
let tasks = self.tasks.clone();
let factory = Arc::new(HttpElicitationConnectionFactory {
builder: self,
handler,
resource_notification_handler,
});
let client = factory.connect_once().await?;
let toolset = super::McpToolset::new(client).with_connection_factory(factory);
Ok(match tasks {
Some(config) => toolset.with_task_support(config),
None => toolset,
})
}
#[cfg(not(feature = "http-transport"))]
pub async fn connect_with_elicitation(self) -> Result<()> {
Err(AdkError::tool(
"HTTP transport requires the 'http-transport' feature. \
Add `adk-tool = { features = [\"http-transport\"] }` to your Cargo.toml",
))
}
}
impl std::fmt::Debug for McpHttpClientBuilder {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpHttpClientBuilder")
.field("endpoint", &self.endpoint)
.field("auth", &self.auth)
.field("timeout", &self.timeout)
.field("credential_broker", &self.brokered.as_ref().map(|b| &b.broker))
.field("headers", &self.headers.keys().collect::<Vec<_>>())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_builder_new() {
let builder = McpHttpClientBuilder::new("https://mcp.example.com");
assert_eq!(builder.endpoint(), "https://mcp.example.com");
assert_eq!(builder.get_timeout(), Duration::from_secs(30));
}
#[test]
fn test_builder_with_auth() {
let builder = McpHttpClientBuilder::new("https://mcp.example.com")
.with_auth(McpAuth::bearer("test-token"));
assert!(builder.get_auth().is_configured());
}
#[test]
fn test_builder_timeout() {
let builder =
McpHttpClientBuilder::new("https://mcp.example.com").timeout(Duration::from_secs(60));
assert_eq!(builder.get_timeout(), Duration::from_secs(60));
}
#[test]
fn test_builder_headers() {
let builder =
McpHttpClientBuilder::new("https://mcp.example.com").header("X-Custom", "value");
assert!(builder.headers.contains_key("X-Custom"));
}
}