use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use async_trait::async_trait;
use rmcp::RoleServer;
use rmcp::model::{
DetailedTask, ElicitRequestParams, ElicitResult, InputResponses, ProgressNotificationParam,
ProgressToken,
};
use rmcp::service::Peer;
use super::McpCaller;
#[async_trait]
pub trait McpTaskHost: Send + Sync {
async fn get(&self, task_id: &str, caller: &McpCaller) -> Result<DetailedTask>;
async fn update(
&self,
task_id: &str,
caller: &McpCaller,
responses: InputResponses,
) -> Result<()>;
async fn cancel(&self, task_id: &str, caller: &McpCaller) -> Result<()>;
}
#[derive(Clone)]
pub struct McpRequestPeer {
peer: Peer<RoleServer>,
progress_token: Option<ProgressToken>,
sent: Arc<AtomicU64>,
can_elicit: bool,
}
impl std::fmt::Debug for McpRequestPeer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpRequestPeer")
.field("progress", &self.progress_token.is_some())
.field("can_elicit", &self.can_elicit)
.finish_non_exhaustive()
}
}
impl McpRequestPeer {
pub(crate) fn new(
peer: Peer<RoleServer>,
progress_token: Option<ProgressToken>,
can_elicit: bool,
) -> Self {
Self { peer, progress_token, sent: Arc::new(AtomicU64::new(0)), can_elicit }
}
pub fn wants_progress(&self) -> bool {
self.progress_token.is_some()
}
pub async fn progress(&self, message: impl Into<String>) -> bool {
let Some(token) = &self.progress_token else {
return false;
};
let progress = self.sent.fetch_add(1, Ordering::SeqCst) + 1;
let params = ProgressNotificationParam::new(token.clone(), progress as f64)
.with_message(message.into());
self.peer.notify_progress(params).await.is_ok()
}
pub fn can_elicit(&self) -> bool {
self.can_elicit
}
pub async fn elicit(&self, params: ElicitRequestParams) -> Result<ElicitResult> {
if !self.can_elicit {
return Err(AdkError::new(
ErrorComponent::Tool,
ErrorCategory::Unsupported,
"mcp.server.elicitation_unsupported",
"the client declared no form elicitation on this connection",
));
}
self.peer.create_elicitation(params).await.map_err(|error| {
AdkError::unavailable(
ErrorComponent::Tool,
"mcp.server.elicitation_failed",
format!("the client did not answer the elicitation: {error}"),
)
})
}
}