1#![cfg_attr(feature = "mcp-sampling", allow(deprecated))]
11
12use std::sync::Arc;
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use futures::FutureExt;
16use rmcp::model::{
17 ElicitRequest, ElicitRequestParams, ElicitResult, ElicitationAction, ElicitationCapability,
18 ElicitationSchema, FormElicitationCapability, InitializeRequestParams, InputRequest,
19 InputRequests, InputResponses, UrlElicitationCapability,
20};
21use rmcp::service::{NotificationContext, RequestContext, RoleClient};
22use serde_json::Value;
23
24use super::parked::{ParkedCallKind, ParkedMcpCall};
25use super::resource_notifications::{
26 ResourceNotificationHandler, dispatch_resource_list_changed, dispatch_resource_updated,
27};
28
29#[async_trait::async_trait]
67pub trait ElicitationHandler: Send + Sync {
68 async fn handle_form_elicitation(
74 &self,
75 message: &str,
76 schema: &ElicitationSchema,
77 metadata: Option<&Value>,
78 ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>>;
79
80 async fn handle_url_elicitation(
86 &self,
87 message: &str,
88 url: &str,
89 elicitation_id: &str,
90 metadata: Option<&Value>,
91 ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>>;
92}
93
94#[derive(Debug, Clone, Copy)]
99pub struct AutoDeclineElicitationHandler;
100
101#[async_trait::async_trait]
102impl ElicitationHandler for AutoDeclineElicitationHandler {
103 async fn handle_form_elicitation(
104 &self,
105 _message: &str,
106 _schema: &ElicitationSchema,
107 _metadata: Option<&Value>,
108 ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>> {
109 Ok(ElicitResult::new(ElicitationAction::Decline))
110 }
111
112 async fn handle_url_elicitation(
113 &self,
114 _message: &str,
115 _url: &str,
116 _elicitation_id: &str,
117 _metadata: Option<&Value>,
118 ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>> {
119 Ok(ElicitResult::new(ElicitationAction::Decline))
120 }
121}
122
123#[derive(Clone, Debug, Default)]
140pub struct ElicitationScope {
141 pub app_name: String,
143 pub user_id: String,
145 pub session_id: String,
147 pub invocation_id: String,
149 pub agent_name: String,
151 pub function_call_id: Option<String>,
153 pub run_id: Option<String>,
155 pub acting: Option<adk_core::ActingContext>,
157 pub audit: Option<adk_core::audit_log::AuditTrail>,
159}
160
161tokio::task_local! {
162 static CURRENT_ELICITATION_SCOPE: ElicitationScope;
163}
164
165impl ElicitationScope {
166 pub fn new(
168 app_name: impl Into<String>,
169 user_id: impl Into<String>,
170 session_id: impl Into<String>,
171 ) -> Self {
172 Self {
173 app_name: app_name.into(),
174 user_id: user_id.into(),
175 session_id: session_id.into(),
176 ..Self::default()
177 }
178 }
179
180 pub fn for_call(ctx: &dyn adk_core::ToolContext) -> Self {
182 let call_id = ctx.function_call_id();
183 Self {
184 app_name: ctx.app_name().to_string(),
185 user_id: ctx.user_id().to_string(),
186 session_id: ctx.session_id().to_string(),
187 invocation_id: ctx.invocation_id().to_string(),
188 agent_name: ctx.agent_name().to_string(),
189 function_call_id: (!call_id.is_empty()).then(|| call_id.to_string()),
190 run_id: ctx.run_config().and_then(|config| config.durable_run_id.clone()),
191 acting: Some(ctx.acting_context()),
192 audit: ctx.run_config().and_then(|config| config.audit.clone()),
193 }
194 }
195
196 pub fn same_as(&self, other: &Self) -> bool {
198 self.app_name == other.app_name
199 && self.user_id == other.user_id
200 && self.session_id == other.session_id
201 && self.invocation_id == other.invocation_id
202 && self.function_call_id == other.function_call_id
203 }
204
205 pub fn current() -> Option<Self> {
207 CURRENT_ELICITATION_SCOPE.try_with(Clone::clone).ok()
208 }
209
210 pub async fn within<F: Future>(self, future: F) -> F::Output {
212 CURRENT_ELICITATION_SCOPE.scope(self, future).await
213 }
214}
215
216#[derive(Debug, Default)]
236pub struct ElicitationScopes {
237 active: std::sync::Mutex<Vec<(u64, ElicitationScope)>>,
238 fallback: std::sync::Mutex<Option<ElicitationScope>>,
239 next_id: AtomicU64,
240 calls: std::sync::Mutex<Vec<(u64, ParkedMcpCall)>>,
243}
244
245impl ElicitationScopes {
246 pub fn set_fallback(&self, scope: Option<ElicitationScope>) {
248 *self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = scope;
249 }
250
251 pub fn fallback(&self) -> Option<ElicitationScope> {
253 self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()
254 }
255
256 pub fn enter(self: &Arc<Self>, scope: ElicitationScope) -> ElicitationScopeGuard {
258 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
259 self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push((id, scope));
260 ElicitationScopeGuard { scopes: Arc::clone(self), id }
261 }
262
263 pub fn resolve(&self) -> Option<ElicitationScope> {
265 let active = self.active.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
266 if let Some((_, latest)) = active.last() {
267 if active.iter().any(|(_, scope)| !scope.same_as(latest)) {
268 tracing::debug!(
269 in_flight = active.len(),
270 "tool calls from several runs are in flight; the elicitation is attributed to the latest"
271 );
272 }
273 return Some(latest.clone());
274 }
275 drop(active);
276 self.fallback()
277 }
278}
279
280impl ElicitationScopes {
281 pub(crate) fn enter_call(self: &Arc<Self>, call: ParkedMcpCall) -> InFlightCall {
283 let id = self.next_id.fetch_add(1, Ordering::Relaxed);
284 self.calls.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).push((id, call));
285 InFlightCall { scopes: Arc::clone(self), id }
286 }
287
288 fn resolve_call(&self) -> Option<ParkedMcpCall> {
290 let calls = self.calls.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
291 calls.last().map(|(_, call)| call.clone())
292 }
293}
294
295pub(crate) struct InFlightCall {
297 scopes: Arc<ElicitationScopes>,
298 id: u64,
299}
300
301impl Drop for InFlightCall {
302 fn drop(&mut self) {
303 self.scopes
304 .calls
305 .lock()
306 .unwrap_or_else(|poisoned| poisoned.into_inner())
307 .retain(|(id, _)| *id != self.id);
308 }
309}
310
311#[derive(Debug)]
313pub struct ElicitationScopeGuard {
314 scopes: Arc<ElicitationScopes>,
315 id: u64,
316}
317
318impl Drop for ElicitationScopeGuard {
319 fn drop(&mut self) {
320 self.scopes
321 .active
322 .lock()
323 .unwrap_or_else(|poisoned| poisoned.into_inner())
324 .retain(|(id, _)| *id != self.id);
325 }
326}
327
328#[derive(Clone)]
336pub struct AdkClientHandler {
337 handler: Arc<dyn ElicitationHandler>,
338 resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
339 tasks: bool,
340 #[cfg(feature = "mcp-apps")]
342 apps: bool,
343 tool_list_changes: Arc<AtomicU64>,
346 elicitation_scopes: Arc<std::sync::RwLock<Arc<ElicitationScopes>>>,
348 #[cfg(feature = "mcp-sampling")]
349 sampling_handler: Option<Arc<dyn crate::sampling::SamplingHandler>>,
350 #[cfg(feature = "mcp-sampling")]
352 sampling_scopes: Arc<std::sync::RwLock<Arc<crate::sampling::SamplingScopes>>>,
353}
354
355impl AdkClientHandler {
356 pub fn new(handler: Arc<dyn ElicitationHandler>) -> Self {
358 Self {
359 handler,
360 resource_notification_handler: None,
361 tasks: false,
362 #[cfg(feature = "mcp-apps")]
363 apps: false,
364 tool_list_changes: Arc::new(AtomicU64::new(0)),
365 elicitation_scopes: Arc::default(),
366 #[cfg(feature = "mcp-sampling")]
367 sampling_handler: None,
368 #[cfg(feature = "mcp-sampling")]
369 sampling_scopes: Arc::default(),
370 }
371 }
372
373 pub fn with_elicitation_scope(self, scope: ElicitationScope) -> Self {
378 self.elicitation_scopes().set_fallback(Some(scope));
379 self
380 }
381
382 pub(crate) fn elicitation_scopes(&self) -> Arc<ElicitationScopes> {
383 Arc::clone(&self.elicitation_scopes.read().unwrap_or_else(|poisoned| poisoned.into_inner()))
384 }
385
386 pub(crate) fn share_elicitation_scopes(&self, scopes: Arc<ElicitationScopes>) {
389 let mut current =
390 self.elicitation_scopes.write().unwrap_or_else(|poisoned| poisoned.into_inner());
391 if Arc::ptr_eq(¤t, &scopes) {
392 return;
393 }
394 if scopes.fallback().is_none() {
395 scopes.set_fallback(current.fallback());
396 }
397 *current = scopes;
398 }
399
400 pub(crate) fn tool_list_changes(&self) -> u64 {
401 self.tool_list_changes.load(Ordering::Acquire)
402 }
403
404 pub fn with_tasks(mut self) -> Self {
411 self.tasks = true;
412 self
413 }
414
415 #[cfg(feature = "mcp-apps")]
434 pub fn with_apps(mut self) -> Self {
435 self.apps = true;
436 self
437 }
438
439 async fn handle_elicitation(&self, request: ElicitRequestParams) -> ElicitResult {
440 let scope = self.elicitation_scopes().resolve();
443 let handled = async {
444 match &request {
445 ElicitRequestParams::FormElicitationParams {
446 message,
447 requested_schema,
448 meta,
449 ..
450 } => {
451 let metadata_value = meta.as_ref().and_then(|m| serde_json::to_value(m).ok());
452 Some(
453 self.handler
454 .handle_form_elicitation(
455 message,
456 requested_schema,
457 metadata_value.as_ref(),
458 )
459 .await,
460 )
461 }
462 ElicitRequestParams::UrlElicitationParams {
463 message,
464 url,
465 elicitation_id,
466 meta,
467 ..
468 } => {
469 let metadata_value = meta.as_ref().and_then(|m| serde_json::to_value(m).ok());
470 Some(
471 self.handler
472 .handle_url_elicitation(
473 message,
474 url,
475 elicitation_id,
476 metadata_value.as_ref(),
477 )
478 .await,
479 )
480 }
481 _ => None,
482 }
483 };
484 let handled = match scope {
485 Some(scope) => futures::future::Either::Left(scope.within(handled)),
486 None => futures::future::Either::Right(handled),
487 };
488 let result = match std::panic::AssertUnwindSafe(handled).catch_unwind().await {
489 Ok(Some(result)) => Ok(result),
490 Ok(None) => return ElicitResult::new(ElicitationAction::Decline),
491 Err(panic) => Err(panic),
492 };
493
494 match result {
495 Ok(Ok(elicitation_result)) => elicitation_result,
496 Ok(Err(error)) => {
497 tracing::warn!(%error, "elicitation handler returned error, declining");
498 ElicitResult::new(ElicitationAction::Decline)
499 }
500 Err(_) => {
501 tracing::warn!("elicitation handler panicked, declining");
502 ElicitResult::new(ElicitationAction::Decline)
503 }
504 }
505 }
506
507 pub(crate) async fn fulfill_input_requests(
511 &self,
512 requests: InputRequests,
513 ) -> Result<InputResponses, String> {
514 let mut responses = InputResponses::new();
515 for (key, request) in requests {
516 let value = match request {
517 InputRequest::Elicitation(request) => {
518 serde_json::to_value(self.handle_elicitation(request.params).await)
519 .map_err(|error| error.to_string())?
520 }
521 InputRequest::CreateMessage(_) => {
522 return Err("MRTR sampling is deprecated and not enabled by ADK".to_string());
523 }
524 InputRequest::ListRoots(_) => {
525 return Err("MRTR roots are deprecated and not enabled by ADK".to_string());
526 }
527 _ => return Err("unsupported MRTR input request".to_string()),
528 };
529 responses.insert(key, value);
530 }
531 Ok(responses)
532 }
533
534 pub fn with_resource_notification_handler(
536 mut self,
537 handler: Arc<dyn ResourceNotificationHandler>,
538 ) -> Self {
539 self.resource_notification_handler = Some(handler);
540 self
541 }
542
543 #[cfg(feature = "mcp-sampling")]
548 pub fn with_sampling_handler(
549 mut self,
550 handler: Arc<dyn crate::sampling::SamplingHandler>,
551 ) -> Self {
552 self.sampling_handler = Some(handler);
553 self
554 }
555
556 #[cfg(feature = "mcp-sampling")]
562 pub fn with_sampling_scope(self, scope: adk_core::ModelCallScope) -> Self {
563 self.sampling_scopes().set_fallback(Some(scope));
564 self
565 }
566
567 #[cfg(feature = "mcp-sampling")]
568 pub(crate) fn sampling_scopes(&self) -> Arc<crate::sampling::SamplingScopes> {
569 Arc::clone(&self.sampling_scopes.read().unwrap_or_else(|poisoned| poisoned.into_inner()))
570 }
571
572 #[cfg(feature = "mcp-sampling")]
575 pub(crate) fn share_sampling_scopes(&self, scopes: Arc<crate::sampling::SamplingScopes>) {
576 let mut current =
577 self.sampling_scopes.write().unwrap_or_else(|poisoned| poisoned.into_inner());
578 if Arc::ptr_eq(¤t, &scopes) {
579 return;
580 }
581 if scopes.fallback().is_none() {
582 scopes.set_fallback(current.fallback());
583 }
584 *current = scopes;
585 }
586}
587
588impl rmcp::handler::client::ClientHandler for AdkClientHandler {
589 fn get_info(&self) -> InitializeRequestParams {
590 let mut info = InitializeRequestParams::default();
591 let elicitation = ElicitationCapability::new()
592 .with_form(FormElicitationCapability::new())
593 .with_url(UrlElicitationCapability::new());
594
595 #[cfg(feature = "mcp-sampling")]
598 {
599 info.capabilities = if self.sampling_handler.is_some() {
600 rmcp::model::ClientCapabilities::builder()
601 .enable_elicitation_with(elicitation)
602 .enable_sampling()
603 .build()
604 } else {
605 rmcp::model::ClientCapabilities::builder()
606 .enable_elicitation_with(elicitation)
607 .build()
608 };
609 }
610
611 #[cfg(not(feature = "mcp-sampling"))]
612 {
613 info.capabilities = rmcp::model::ClientCapabilities::builder()
614 .enable_elicitation_with(elicitation)
615 .build();
616 }
617
618 if self.tasks {
619 info.capabilities
620 .extensions
621 .get_or_insert_with(rmcp::model::ExtensionCapabilities::new)
622 .insert(rmcp::model::TASKS_EXTENSION_ID.to_string(), Default::default());
623 }
624 #[cfg(feature = "mcp-apps")]
625 if self.apps {
626 let mut apps = rmcp::model::JsonObject::new();
627 apps.insert("mimeTypes".to_string(), serde_json::json!([super::MCP_APP_MIME_TYPE]));
628 info.capabilities
629 .extensions
630 .get_or_insert_with(rmcp::model::ExtensionCapabilities::new)
631 .insert(super::MCP_APPS_EXTENSION_ID.to_string(), apps);
632 }
633
634 info
635 }
636
637 #[cfg(feature = "mcp-sampling")]
638 async fn create_message(
639 &self,
640 params: rmcp::model::CreateMessageRequestParams,
641 _context: RequestContext<RoleClient>,
642 ) -> Result<rmcp::model::CreateMessageResult, rmcp::ErrorData> {
643 use crate::sampling::{SamplingContent, SamplingMessage, SamplingRequest};
644 use rmcp::model::{CreateMessageResult, Role, SamplingMessageContentBlock};
645
646 let Some(ref sampling_handler) = self.sampling_handler else {
647 return Err(rmcp::ErrorData::new(
648 rmcp::model::ErrorCode::METHOD_NOT_FOUND,
649 "sampling handler not configured",
650 None,
651 ));
652 };
653
654 let messages: Vec<SamplingMessage> = params
656 .messages
657 .iter()
658 .map(|msg| {
659 let role = match msg.role {
660 Role::User => "user",
661 Role::Assistant => "assistant",
662 };
663 let content = msg
665 .content
666 .first()
667 .and_then(|c| match c {
668 SamplingMessageContentBlock::Text(t) => {
669 Some(SamplingContent::text(t.text.clone()))
670 }
671 SamplingMessageContentBlock::Image(img) => {
672 Some(SamplingContent::image(img.data.clone(), img.mime_type.clone()))
673 }
674 _ => None,
675 })
676 .unwrap_or_else(|| SamplingContent::text(""));
677 SamplingMessage::new(role, content)
678 })
679 .collect();
680
681 let request = SamplingRequest {
682 messages,
683 system_prompt: params.system_prompt.clone(),
684 model_preferences: None,
685 max_tokens: Some(params.max_tokens),
686 temperature: params.temperature.map(|t| t as f64),
687 };
688
689 let handled = sampling_handler.handle_create_message(request);
692 let handled = match self.sampling_scopes().resolve() {
693 Some(scope) => futures::future::Either::Left(scope.within(handled)),
694 None => futures::future::Either::Right(handled),
695 };
696 let handled = match self.elicitation_scopes().resolve() {
697 Some(scope) => futures::future::Either::Left(scope.within(handled)),
698 None => futures::future::Either::Right(handled),
699 };
700 match std::panic::AssertUnwindSafe(handled).catch_unwind().await {
701 Ok(Ok(response)) => {
702 let text = match &response.content {
704 SamplingContent::Text { text } => text.clone(),
705 SamplingContent::Image { .. } => String::new(),
706 };
707 let message = rmcp::model::SamplingMessage::assistant_text(text);
708 Ok(CreateMessageResult::new(message, response.model)
709 .with_stop_reason(response.stop_reason))
710 }
711 Ok(Err(e)) => {
712 tracing::warn!(error = %e.diagnostics(), "sampling handler returned error");
715 Err(rmcp::ErrorData::new(
716 rmcp::model::ErrorCode::INTERNAL_ERROR,
717 format!("sampling handler error: {e}"),
718 None,
719 ))
720 }
721 Err(_panic) => {
722 tracing::warn!("sampling handler panicked");
723 Err(rmcp::ErrorData::new(
724 rmcp::model::ErrorCode::INTERNAL_ERROR,
725 "sampling handler panicked",
726 None,
727 ))
728 }
729 }
730 }
731
732 async fn create_elicitation(
733 &self,
734 request: ElicitRequestParams,
735 context: RequestContext<RoleClient>,
736 ) -> Result<ElicitResult, rmcp::ErrorData> {
737 let legacy = ParkedMcpCall::current()
740 .is_none()
741 .then(|| self.elicitation_scopes().resolve_call())
742 .flatten()
743 .map(|call| {
744 let rounds = call.input_rounds;
745 let question = InputRequest::Elicitation(ElicitRequest::new(request.clone()));
746 call.waiting(
747 ParkedCallKind::Legacy,
748 None,
749 [(context.id.to_string(), question)].into(),
750 rounds,
751 )
752 });
753 Ok(match legacy {
754 Some(call) => call.within(self.handle_elicitation(request)).await,
755 None => self.handle_elicitation(request).await,
756 })
757 }
758
759 async fn on_resource_updated(
760 &self,
761 params: rmcp::model::ResourceUpdatedNotificationParam,
762 _context: NotificationContext<RoleClient>,
763 ) {
764 dispatch_resource_updated(&self.resource_notification_handler, ¶ms.uri).await;
765 }
766
767 async fn on_resource_list_changed(&self, _context: NotificationContext<RoleClient>) {
768 dispatch_resource_list_changed(&self.resource_notification_handler).await;
769 }
770
771 async fn on_tool_list_changed(&self, _context: NotificationContext<RoleClient>) {
772 self.tool_list_changes.fetch_add(1, Ordering::AcqRel);
773 }
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 #[test]
781 fn test_elicitation_handler_is_send_sync() {
782 fn require_send_sync<T: Send + Sync>() {}
783 require_send_sync::<AutoDeclineElicitationHandler>();
784 }
785
786 #[test]
787 fn test_adk_client_handler_is_send_sync() {
788 fn require_send_sync<T: Send + Sync>() {}
789 require_send_sync::<AdkClientHandler>();
790 }
791}