Skip to main content

adk_tool/mcp/
elicitation.rs

1//! MCP Elicitation lifecycle support.
2//!
3//! This module provides the [`ElicitationHandler`] trait for handling MCP elicitation
4//! requests from servers, an [`AutoDeclineElicitationHandler`] that declines all
5//! requests, and the internal [`AdkClientHandler`] bridge to rmcp's `ClientHandler`.
6
7// Sampling remains available only as a compatibility feature. rmcp marks the
8// protocol surface deprecated under SEP-2577, so deprecation warnings are
9// intentionally contained in this bridge while existing users migrate.
10#![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/// Trait for handling MCP elicitation requests from servers.
30///
31/// Implement this trait to provide custom elicitation behavior when
32/// an MCP server requests additional information during tool execution.
33///
34/// # Example
35///
36/// ```rust,ignore
37/// use adk_tool::ElicitationHandler;
38/// use rmcp::model::{ElicitResult, ElicitationAction, ElicitationSchema};
39///
40/// struct MyHandler;
41///
42/// #[async_trait::async_trait]
43/// impl ElicitationHandler for MyHandler {
44///     async fn handle_form_elicitation(
45///         &self,
46///         message: &str,
47///         schema: &ElicitationSchema,
48///         metadata: Option<&serde_json::Value>,
49///     ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>> {
50///         println!("Server asks: {message}");
51///         Ok(ElicitResult::new(ElicitationAction::Accept))
52///     }
53///
54///     async fn handle_url_elicitation(
55///         &self,
56///         message: &str,
57///         url: &str,
58///         elicitation_id: &str,
59///         metadata: Option<&serde_json::Value>,
60///     ) -> Result<ElicitResult, Box<dyn std::error::Error + Send + Sync>> {
61///         println!("Server asks to visit: {url}");
62///         Ok(ElicitResult::new(ElicitationAction::Accept))
63///     }
64/// }
65/// ```
66#[async_trait::async_trait]
67pub trait ElicitationHandler: Send + Sync {
68    /// Handle a form-based elicitation request.
69    ///
70    /// The server sends a human-readable message and a typed schema describing
71    /// the data it needs. Return `Accept` with content matching the schema,
72    /// `Decline` to refuse, or `Cancel` to abort the operation.
73    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    /// Handle a URL-based elicitation request.
81    ///
82    /// The server sends a URL for the user to visit and interact with externally.
83    /// The `elicitation_id` uniquely identifies this request for the completion
84    /// notification flow.
85    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/// Default handler that declines all elicitation requests.
95///
96/// Used when no custom handler is configured, preserving backward-compatible
97/// behavior identical to rmcp's `()` ClientHandler default.
98#[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/// The run and tool call in flight when a server asked (spec 3.1 §10 T1).
124///
125/// A toolset registers one per in-flight tool call, and the connection's
126/// [`AdkClientHandler`] answers an elicitation inside it, so a handler reads the scope
127/// with [`ElicitationScope::current`] and can show the request as a prompt of that
128/// session or park it as an approval of that run.
129///
130/// # Example
131///
132/// ```rust
133/// use adk_tool::mcp::ElicitationScope;
134///
135/// let scope = ElicitationScope::new("app", "alice", "s1");
136/// assert_eq!(scope.session_id, "s1");
137/// assert!(ElicitationScope::current().is_none());
138/// ```
139#[derive(Clone, Debug, Default)]
140pub struct ElicitationScope {
141    /// The application of the session.
142    pub app_name: String,
143    /// The user of the session.
144    pub user_id: String,
145    /// The session the tool call belongs to.
146    pub session_id: String,
147    /// The invocation of the tool call.
148    pub invocation_id: String,
149    /// The agent that made the tool call.
150    pub agent_name: String,
151    /// The function call id, when the call has one.
152    pub function_call_id: Option<String>,
153    /// The durable run id, when the run is durable.
154    pub run_id: Option<String>,
155    /// The acting agent and the subject it acts for.
156    pub acting: Option<adk_core::ActingContext>,
157    /// The run's audit trail, when it records one.
158    pub audit: Option<adk_core::audit_log::AuditTrail>,
159}
160
161tokio::task_local! {
162    static CURRENT_ELICITATION_SCOPE: ElicitationScope;
163}
164
165impl ElicitationScope {
166    /// A scope of `session_id` of `user_id` in `app_name`, with no call details.
167    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    /// The scope of the tool call `ctx` executes.
181    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    /// Whether both scopes name the same session and call.
197    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    /// The scope the elicitation being answered belongs to, if any.
206    pub fn current() -> Option<Self> {
207        CURRENT_ELICITATION_SCOPE.try_with(Clone::clone).ok()
208    }
209
210    /// Runs `future` with this scope as [`current`](Self::current).
211    pub async fn within<F: Future>(self, future: F) -> F::Output {
212        CURRENT_ELICITATION_SCOPE.scope(self, future).await
213    }
214}
215
216/// The scopes a connection's elicitations resolve against, mirroring `SamplingScopes`
217/// (`mcp-sampling`; spec 3.1 §10 T1).
218///
219/// A toolset [`enter`](Self::enter)s the scope of each tool call it makes; a request that
220/// arrives while none is in flight resolves to the [fallback](Self::set_fallback).
221///
222/// # Example
223///
224/// ```rust
225/// use std::sync::Arc;
226/// use adk_tool::mcp::{ElicitationScope, ElicitationScopes};
227///
228/// let scopes = Arc::new(ElicitationScopes::default());
229/// assert!(scopes.resolve().is_none());
230/// let guard = scopes.enter(ElicitationScope::new("app", "alice", "s1"));
231/// assert_eq!(scopes.resolve().map(|scope| scope.session_id), Some("s1".to_string()));
232/// drop(guard);
233/// assert!(scopes.resolve().is_none());
234/// ```
235#[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 awaiting their `tools/call` response, which a legacy `elicitation/create`
241    /// belongs to (spec 3.2 §10 T2).
242    calls: std::sync::Mutex<Vec<(u64, ParkedMcpCall)>>,
243}
244
245impl ElicitationScopes {
246    /// Sets the scope used when no registered call is in flight.
247    pub fn set_fallback(&self, scope: Option<ElicitationScope>) {
248        *self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = scope;
249    }
250
251    /// The scope used when no registered call is in flight.
252    pub fn fallback(&self) -> Option<ElicitationScope> {
253        self.fallback.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()
254    }
255
256    /// Registers `scope` until the returned guard is dropped.
257    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    /// The scope an elicitation arriving now belongs to.
264    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    /// Registers `call` as awaiting its response until the returned guard is dropped.
282    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    /// The call a legacy elicitation arriving now belongs to: the latest one registered.
289    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
295/// Unregisters a call registered with [`ElicitationScopes::enter_call`] when dropped.
296pub(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/// Unregisters an [`ElicitationScope`] when dropped.
312#[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/// Internal bridge between ADK's [`ElicitationHandler`] and rmcp's `ClientHandler`.
329///
330/// Wraps an `Arc<dyn ElicitationHandler>` and implements rmcp's `ClientHandler` trait,
331/// advertising elicitation capabilities and delegating requests to the handler.
332///
333/// When the `mcp-sampling` feature is enabled, also accepts an optional
334/// `Arc<dyn SamplingHandler>` to handle `sampling/createMessage` requests.
335#[derive(Clone)]
336pub struct AdkClientHandler {
337    handler: Arc<dyn ElicitationHandler>,
338    resource_notification_handler: Option<Arc<dyn ResourceNotificationHandler>>,
339    tasks: bool,
340    /// Declares the MCP Apps extension (spec 3.3 §6.1 `genui-apps`).
341    #[cfg(feature = "mcp-apps")]
342    apps: bool,
343    /// `notifications/tools/list_changed` received on this connection; a
344    /// toolset compares it against its cached `tools/list` result.
345    tool_list_changes: Arc<AtomicU64>,
346    /// Scopes elicitations resolve against; a toolset swaps in its own on connect.
347    elicitation_scopes: Arc<std::sync::RwLock<Arc<ElicitationScopes>>>,
348    #[cfg(feature = "mcp-sampling")]
349    sampling_handler: Option<Arc<dyn crate::sampling::SamplingHandler>>,
350    /// Scopes sampling requests count against; a toolset swaps in its own on connect.
351    #[cfg(feature = "mcp-sampling")]
352    sampling_scopes: Arc<std::sync::RwLock<Arc<crate::sampling::SamplingScopes>>>,
353}
354
355impl AdkClientHandler {
356    /// Create a new `AdkClientHandler` with the given elicitation handler.
357    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    /// Attributes elicitations that arrive outside any run's tool call to `scope`.
374    ///
375    /// Requests that arrive while a run's [`McpToolset`](crate::McpToolset) tool call is
376    /// in flight belong to that call instead (spec 3.1 §10 T1).
377    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    /// Makes this connection's elicitations resolve against `scopes`, keeping this
387    /// handler's fallback scope when `scopes` has none.
388    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(&current, &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    /// Declare the SEP-2663 tasks extension during the handshake.
405    ///
406    /// A server decides per call whether to answer `tools/call` with a task, but
407    /// it must not return one to a client that did not declare the extension.
408    /// Without this, [`McpToolset::with_task_support`](crate::mcp::McpToolset::with_task_support)
409    /// configures a path no server will ever take.
410    pub fn with_tasks(mut self) -> Self {
411        self.tasks = true;
412        self
413    }
414
415    /// Declares the MCP Apps extension, [`MCP_APPS_EXTENSION_ID`](super::MCP_APPS_EXTENSION_ID)
416    /// with the MIME type [`MCP_APP_MIME_TYPE`](super::MCP_APP_MIME_TYPE), during the handshake
417    /// (spec 3.3 §6.1 `genui-apps`), so a server may give its tools apps a host shows.
418    ///
419    /// # Example
420    ///
421    /// ```rust
422    /// use adk_tool::mcp::{AdkClientHandler, AutoDeclineElicitationHandler, MCP_APPS_EXTENSION_ID};
423    /// use rmcp::handler::client::ClientHandler;
424    /// use std::sync::Arc;
425    ///
426    /// let handler = AdkClientHandler::new(Arc::new(AutoDeclineElicitationHandler)).with_apps();
427    /// let extensions = handler.get_info().capabilities.extensions.unwrap();
428    /// assert_eq!(
429    ///     extensions[MCP_APPS_EXTENSION_ID]["mimeTypes"],
430    ///     serde_json::json!(["text/html;profile=mcp-app"])
431    /// );
432    /// ```
433    #[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        // The handler answers inside the scope of the tool call in flight, so it knows
441        // which run and session asked (spec 3.1 §10 T1).
442        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    /// Fulfil stateless MRTR requests through the same policy used for legacy
508    /// server-initiated elicitation. Sampling and roots are intentionally not
509    /// accepted here: both are deprecated in the 2026-07-28 lifecycle.
510    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    /// Set the handler for resource update and resource-list notifications.
535    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    /// Set a sampling handler for `sampling/createMessage` requests.
544    ///
545    /// When configured, the handler advertises sampling capability and
546    /// delegates incoming sampling requests to the provided handler.
547    #[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    /// Meters sampling requests that arrive outside any run's tool call against `scope`.
557    ///
558    /// Requests that arrive while a run's [`McpToolset`](crate::McpToolset) tool call is
559    /// in flight count against that run instead. See
560    /// [sampling metering](crate::sampling#metering).
561    #[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    /// Makes this connection's sampling requests resolve against `scopes`, keeping this
573    /// handler's fallback scope when `scopes` has none.
574    #[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(&current, &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        // The capability builder is typestate, so each `enable_*` returns a
596        // different type and the optional ones cannot be chained conditionally.
597        #[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        // Convert rmcp SamplingMessages → our SamplingMessages
655        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                // Extract text from the first content item
664                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        // The request counts against the run whose tool call is in flight, if any, and the
690        // handler learns that call's scope as an elicitation handler does (spec 3.1 §10 T1).
691        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                // Convert our SamplingResponse → rmcp CreateMessageResult
703                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                // A model error can echo the sampled prompt, so only its content-free part
713                // is logged.
714                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        // A server before 2026-07-28 asks while one of the toolset's calls awaits its
738        // response; the handler sees that call's parked form (spec 3.2 §10 T2).
739        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, &params.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}