Skip to main content

rmcp/service/
server.rs

1// Sampling/Roots/Logging are SEP-2577-deprecated; internal references are expected.
2#![expect(deprecated)]
3#[cfg(feature = "elicitation")]
4use std::collections::HashSet;
5use std::{borrow::Cow, sync::Arc};
6
7use thiserror::Error;
8#[cfg(feature = "elicitation")]
9use url::Url;
10
11use super::*;
12#[cfg(feature = "elicitation")]
13use crate::model::{ElicitRequest, ElicitRequestParams, ElicitResult, ElicitationAction};
14use crate::{
15    model::{
16        CancelledNotification, CancelledNotificationParam, ClientJsonRpcMessage,
17        ClientNotification, ClientRequest, ClientResult, CreateMessageRequest,
18        CreateMessageRequestParams, CreateMessageResult, EmptyResult, ErrorData,
19        InitializeRequestParams, ListRootsRequest, ListRootsResult, LoggingMessageNotification,
20        LoggingMessageNotificationParam, ProgressNotification, ProgressNotificationParam,
21        PromptListChangedNotification, ProtocolVersion, ResourceListChangedNotification,
22        ResourceUpdatedNotification, ResourceUpdatedNotificationParam, ServerConfig,
23        ServerNotification, ServerRequest, ServerResult, SubscriptionFilter,
24        SubscriptionsAcknowledgedNotification, SubscriptionsAcknowledgedNotificationParams,
25        ToolListChangedNotification,
26    },
27    transport::DynamicTransportError,
28};
29
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
31#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
32pub struct RoleServer;
33
34impl ServiceRole for RoleServer {
35    type Req = ServerRequest;
36    type Resp = ServerResult;
37    type Not = ServerNotification;
38    type PeerReq = ClientRequest;
39    type PeerResp = ClientResult;
40    type PeerNot = ClientNotification;
41    type Info = ServerConfig;
42    type PeerInfo = InitializeRequestParams;
43
44    type InitializeError = ServerInitializeError;
45    const IS_CLIENT: bool = false;
46
47    fn peer_cancelled_params(notification: &Self::PeerNot) -> Option<&CancelledNotificationParam> {
48        match notification {
49            ClientNotification::CancelledNotification(notification) => Some(&notification.params),
50            _ => None,
51        }
52    }
53
54    fn enforce_outbound_request(peer: &Peer<Self>) -> Result<(), ServiceError> {
55        // Same order as `RequestContext::protocol_version`: the version the
56        // current request names wins. Outside a handler, fall back to the version
57        // an inline session (e.g. discover on stdio) opened on, since it never
58        // stores peer info, then to peer info.
59        let version = originating_protocol_version()
60            .or_else(|| peer.inline_protocol_version().cloned())
61            .or_else(|| peer.peer_info().map(|info| info.protocol_version.clone()));
62        if version.is_some_and(|version| version >= ProtocolVersion::V_2026_07_28) {
63            return Err(ServiceError::McpError(ErrorData::invalid_request(
64                "server-to-client requests are not allowed on protocol 2026-07-28 or later; return InputRequiredResult instead",
65                None,
66            )));
67        }
68        Ok(())
69    }
70}
71
72/// It represents the error that may occur when serving the server.
73///
74/// if you want to handle the error, you can use `serve_server_with_ct` or `serve_server` with `Result<RunningService<RoleServer, S>, ServerError>`
75#[derive(Error, Debug)]
76#[non_exhaustive]
77pub enum ServerInitializeError {
78    #[error("expect initialized request, but received: {0:?}")]
79    ExpectedInitializeRequest(Option<ClientJsonRpcMessage>),
80
81    #[error("connection closed: {0}")]
82    ConnectionClosed(String),
83
84    #[error("unexpected initialize result: {0:?}")]
85    UnexpectedInitializeResponse(ServerResult),
86
87    #[error("initialize failed: {0}")]
88    InitializeFailed(ErrorData),
89
90    #[error("Send message error {error}, when {context}")]
91    TransportError {
92        error: DynamicTransportError,
93        context: Cow<'static, str>,
94    },
95
96    #[error("Cancelled")]
97    Cancelled,
98}
99
100impl ServerInitializeError {
101    pub fn transport<T: Transport<RoleServer> + 'static>(
102        error: T::Error,
103        context: impl Into<Cow<'static, str>>,
104    ) -> Self {
105        Self::TransportError {
106            error: DynamicTransportError::new::<T, _>(error),
107            context: context.into(),
108        }
109    }
110}
111pub type ClientSink = Peer<RoleServer>;
112
113/// Failure to send a notification through a [`SubscriptionSink`].
114#[derive(Debug, Error)]
115#[non_exhaustive]
116pub enum SubscriptionSendError {
117    #[error("subscription is no longer active")]
118    SubscriptionClosed,
119    #[error("notification is not allowed on a subscription stream: {0}")]
120    UnsupportedNotification(&'static str),
121    #[error("notification was not accepted for this subscription: {0}")]
122    NotificationNotAccepted(&'static str),
123    #[error(transparent)]
124    Service(#[from] ServiceError),
125}
126
127/// A server-side notification sink scoped to one `subscriptions/listen` request.
128///
129/// The sink applies the accepted filter and adds the subscription request ID to
130/// every notification it sends.
131#[derive(Debug, Clone)]
132pub struct SubscriptionSink {
133    peer: Peer<RoleServer>,
134    id: RequestId,
135    accepted: Arc<SubscriptionFilter>,
136    active: CancellationToken,
137}
138
139impl SubscriptionSink {
140    fn new(
141        peer: Peer<RoleServer>,
142        id: RequestId,
143        accepted: Arc<SubscriptionFilter>,
144        active: CancellationToken,
145    ) -> Self {
146        Self {
147            peer,
148            id,
149            accepted,
150            active,
151        }
152    }
153
154    /// Return the JSON-RPC ID of the originating listen request.
155    pub fn id(&self) -> &RequestId {
156        &self.id
157    }
158
159    /// Return the filter accepted for this subscription.
160    pub fn accepted(&self) -> &SubscriptionFilter {
161        self.accepted.as_ref()
162    }
163
164    /// Send an allowed change notification with subscription metadata attached.
165    ///
166    /// # Errors
167    ///
168    /// Returns [`SubscriptionSendError::SubscriptionClosed`] after the request
169    /// ends, a filter error for disallowed notifications, or a transport error.
170    pub async fn send(
171        &self,
172        mut notification: ServerNotification,
173    ) -> Result<(), SubscriptionSendError> {
174        if self.active.is_cancelled() {
175            return Err(SubscriptionSendError::SubscriptionClosed);
176        }
177        match &notification {
178            ServerNotification::ToolListChangedNotification(_) => {
179                if self.accepted.tools_list_changed != Some(true) {
180                    return Err(SubscriptionSendError::NotificationNotAccepted(
181                        "notifications/tools/list_changed",
182                    ));
183                }
184            }
185            ServerNotification::PromptListChangedNotification(_) => {
186                if self.accepted.prompts_list_changed != Some(true) {
187                    return Err(SubscriptionSendError::NotificationNotAccepted(
188                        "notifications/prompts/list_changed",
189                    ));
190                }
191            }
192            ServerNotification::ResourceListChangedNotification(_) => {
193                if self.accepted.resources_list_changed != Some(true) {
194                    return Err(SubscriptionSendError::NotificationNotAccepted(
195                        "notifications/resources/list_changed",
196                    ));
197                }
198            }
199            ServerNotification::ResourceUpdatedNotification(update) => {
200                let accepted = self
201                    .accepted
202                    .resource_subscriptions
203                    .as_ref()
204                    .is_some_and(|uris| uris.contains(&update.params.uri));
205                if !accepted {
206                    return Err(SubscriptionSendError::NotificationNotAccepted(
207                        "notifications/resources/updated",
208                    ));
209                }
210            }
211            ServerNotification::SubscriptionsAcknowledgedNotification(_) => {
212                return Err(SubscriptionSendError::UnsupportedNotification(
213                    "notifications/subscriptions/acknowledged",
214                ));
215            }
216            ServerNotification::CancelledNotification(_) => {
217                return Err(SubscriptionSendError::UnsupportedNotification(
218                    "notifications/cancelled",
219                ));
220            }
221            ServerNotification::ProgressNotification(_) => {
222                return Err(SubscriptionSendError::UnsupportedNotification(
223                    "notifications/progress",
224                ));
225            }
226            ServerNotification::LoggingMessageNotification(_) => {
227                return Err(SubscriptionSendError::UnsupportedNotification(
228                    "notifications/message",
229                ));
230            }
231            // SEP-2663 task status notifications are not yet routable through
232            // `subscriptions/listen`: `SubscriptionFilter` has no `taskIds`
233            // field yet (the upstream conformance check for this flow is also
234            // still skipped, pending the subscriptions/listen rewrite).
235            // Clients currently observe task state by polling `tasks/get`.
236            ServerNotification::TaskStatusNotification(_) => {
237                return Err(SubscriptionSendError::UnsupportedNotification(
238                    "notifications/tasks",
239                ));
240            }
241            ServerNotification::CustomNotification(_) => {
242                return Err(SubscriptionSendError::UnsupportedNotification(
243                    "custom notification",
244                ));
245            }
246        }
247
248        notification
249            .get_meta_mut()
250            .set_subscription_id(self.id.clone());
251        self.peer.send_notification(notification).await?;
252        Ok(())
253    }
254
255    /// Send `notifications/tools/list_changed`.
256    ///
257    /// # Errors
258    ///
259    /// See [`Self::send`].
260    pub async fn notify_tool_list_changed(&self) -> Result<(), SubscriptionSendError> {
261        self.send(ServerNotification::ToolListChangedNotification(
262            ToolListChangedNotification {
263                method: Default::default(),
264                extensions: Default::default(),
265            },
266        ))
267        .await
268    }
269
270    /// Send `notifications/prompts/list_changed`.
271    ///
272    /// # Errors
273    ///
274    /// See [`Self::send`].
275    pub async fn notify_prompt_list_changed(&self) -> Result<(), SubscriptionSendError> {
276        self.send(ServerNotification::PromptListChangedNotification(
277            PromptListChangedNotification {
278                method: Default::default(),
279                extensions: Default::default(),
280            },
281        ))
282        .await
283    }
284
285    /// Send `notifications/resources/list_changed`.
286    ///
287    /// # Errors
288    ///
289    /// See [`Self::send`].
290    pub async fn notify_resource_list_changed(&self) -> Result<(), SubscriptionSendError> {
291        self.send(ServerNotification::ResourceListChangedNotification(
292            ResourceListChangedNotification {
293                method: Default::default(),
294                extensions: Default::default(),
295            },
296        ))
297        .await
298    }
299
300    /// Send `notifications/resources/updated` for an accepted URI.
301    ///
302    /// # Errors
303    ///
304    /// See [`Self::send`].
305    pub async fn notify_resource_updated(
306        &self,
307        uri: impl Into<String>,
308    ) -> Result<(), SubscriptionSendError> {
309        self.send(ServerNotification::ResourceUpdatedNotification(
310            ResourceUpdatedNotification::new(ResourceUpdatedNotificationParam::new(uri)),
311        ))
312        .await
313    }
314}
315
316/// Context for one established server-side notification subscription.
317///
318/// The acknowledgment has already been sent before this context is handed to
319/// [`ServerHandler::listen`](crate::ServerHandler::listen).
320#[derive(Debug)]
321pub struct SubscriptionContext {
322    request: RequestContext<RoleServer>,
323    requested: SubscriptionFilter,
324    accepted: Arc<SubscriptionFilter>,
325    sink: SubscriptionSink,
326    _active_guard: DropGuard,
327}
328
329impl SubscriptionContext {
330    pub(crate) async fn establish(
331        request: RequestContext<RoleServer>,
332        requested: SubscriptionFilter,
333        accepted: SubscriptionFilter,
334    ) -> Result<Self, ErrorData> {
335        let active = request.ct.child_token();
336        let accepted = Arc::new(accepted);
337        let sink = SubscriptionSink::new(
338            request.peer.clone(),
339            request.id.clone(),
340            accepted.clone(),
341            active.clone(),
342        );
343        let mut acknowledgment = SubscriptionsAcknowledgedNotification::new(
344            SubscriptionsAcknowledgedNotificationParams::new(accepted.as_ref().clone()),
345        );
346        let mut meta = NotificationMetaObject::new();
347        meta.set_subscription_id(request.id.clone());
348        acknowledgment.extensions.insert(meta);
349        request
350            .peer
351            .send_notification(ServerNotification::SubscriptionsAcknowledgedNotification(
352                acknowledgment,
353            ))
354            .await
355            .map_err(|error| {
356                ErrorData::internal_error(
357                    format!("failed to acknowledge subscription: {error}"),
358                    None,
359                )
360            })?;
361        Ok(Self {
362            request,
363            requested,
364            accepted,
365            sink,
366            _active_guard: active.drop_guard(),
367        })
368    }
369
370    /// Return the filter requested by the client.
371    pub fn requested(&self) -> &SubscriptionFilter {
372        &self.requested
373    }
374
375    /// Return the subset accepted by the server.
376    pub fn accepted(&self) -> &SubscriptionFilter {
377        self.accepted.as_ref()
378    }
379
380    /// Return a cloneable, filter-enforcing notification sink.
381    pub fn sink(&self) -> &SubscriptionSink {
382        &self.sink
383    }
384
385    /// Wait until the subscription request is cancelled.
386    pub async fn cancelled(&self) {
387        self.request.ct.cancelled().await;
388    }
389
390    /// Access the underlying request context.
391    pub fn request_context(&self) -> &RequestContext<RoleServer> {
392        &self.request
393    }
394}
395
396impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
397    fn serve_with_ct<T, E, A>(
398        self,
399        transport: T,
400        ct: CancellationToken,
401    ) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError>>
402    + MaybeSendFuture
403    where
404        T: IntoTransport<RoleServer, E, A>,
405        E: std::error::Error + Send + Sync + 'static,
406        Self: Sized,
407    {
408        serve_server_with_ct(self, transport, ct)
409    }
410}
411
412pub async fn serve_server<S, T, E, A>(
413    service: S,
414    transport: T,
415) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
416where
417    S: Service<RoleServer>,
418    T: IntoTransport<RoleServer, E, A>,
419    E: std::error::Error + Send + Sync + 'static,
420{
421    serve_server_with_ct(service, transport, CancellationToken::new()).await
422}
423
424/// Helper function to get the next message from the stream
425async fn expect_next_message<T>(
426    transport: &mut T,
427    context: &str,
428) -> Result<ClientJsonRpcMessage, ServerInitializeError>
429where
430    T: Transport<RoleServer>,
431{
432    transport
433        .receive()
434        .await
435        .ok_or_else(|| ServerInitializeError::ConnectionClosed(context.to_string()))
436}
437
438pub async fn serve_server_with_ct<S, T, E, A>(
439    service: S,
440    transport: T,
441    ct: CancellationToken,
442) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
443where
444    S: Service<RoleServer>,
445    T: IntoTransport<RoleServer, E, A>,
446    E: std::error::Error + Send + Sync + 'static,
447{
448    tokio::select! {
449        result = serve_server_with_ct_inner(service, transport.into_transport(), ct.clone()) => { result }
450        _ = ct.cancelled() => {
451            Err(ServerInitializeError::Cancelled)
452        }
453    }
454}
455
456/// Echoes the client-requested version if the server can serve it over the
457/// `initialize` handshake; otherwise returns a legacy version the server does
458/// support.
459///
460/// `server_supported` comes from [`Service::supported_protocol_versions`], so a
461/// server that narrows that list is never made to answer `initialize` with a
462/// version it cannot serve. [`ProtocolVersion::NO_INITIALIZE`] replaced the
463/// handshake with per-request metadata, so a client naming that revision or
464/// later is answered with the server's newest handshake version instead.
465///
466/// `preferred_fallback` is a *preference*, not a guarantee: it is honored only
467/// when it has an `initialize` handshake of its own. A server that pins itself
468/// past [`ProtocolVersion::NO_INITIALIZE`] still has to answer the handshake
469/// with something, so the newest handshake version in `server_supported` is
470/// substituted.
471///
472/// # Errors
473///
474/// Returns [`ErrorCode::UNSUPPORTED_PROTOCOL_VERSION`] when the server supports
475/// no version that still has an `initialize` handshake.
476///
477/// [`ErrorCode::UNSUPPORTED_PROTOCOL_VERSION`]: crate::model::ErrorCode::UNSUPPORTED_PROTOCOL_VERSION
478pub(crate) fn negotiate_protocol_version(
479    client_requested: &ProtocolVersion,
480    preferred_fallback: ProtocolVersion,
481    server_supported: &[ProtocolVersion],
482) -> Result<ProtocolVersion, ErrorData> {
483    if client_requested.has_initialize() && server_supported.contains(client_requested) {
484        return Ok(client_requested.clone());
485    }
486    let fallback = if preferred_fallback.has_initialize() {
487        Some(preferred_fallback)
488    } else {
489        newest_version_with_initialize(server_supported)
490    };
491    let Some(negotiated) = fallback else {
492        tracing::warn!(
493            client_requested = %client_requested,
494            "server supports no protocol version with an initialize handshake; rejecting"
495        );
496        return Err(ErrorData::unsupported_protocol_version(
497            client_requested.clone(),
498            server_supported,
499        ));
500    };
501    // Falling back is the designed answer for a pinned client, and stateless
502    // HTTP re-runs it on every request, so this is not a warning.
503    tracing::debug!(
504        client_requested = %client_requested,
505        negotiated = %negotiated,
506        "client requested a protocol version unavailable over initialize; falling back to a supported version"
507    );
508    Ok(negotiated)
509}
510
511/// The newest of `versions` that still has an `initialize` handshake.
512fn newest_version_with_initialize(versions: &[ProtocolVersion]) -> Option<ProtocolVersion> {
513    versions
514        .iter()
515        .filter(|version| version.has_initialize())
516        .max_by(|left, right| left.as_str().cmp(right.as_str()))
517        .cloned()
518}
519
520fn missing_request_metadata_error(missing: &[&str]) -> ErrorData {
521    ErrorData::invalid_params(
522        format!(
523            "request _meta is missing or has malformed required fields: {}",
524            missing.join(", ")
525        ),
526        None,
527    )
528}
529
530/// Sends `error` as the response to the `initialize` request and reports it as
531/// the reason the handshake failed.
532async fn report_initialize_failure<T>(
533    transport: &mut T,
534    error: ErrorData,
535    id: RequestId,
536) -> ServerInitializeError
537where
538    T: Transport<RoleServer> + 'static,
539{
540    match transport
541        .send(ServerJsonRpcMessage::error(error.clone(), Some(id)))
542        .await
543    {
544        Ok(()) => ServerInitializeError::InitializeFailed(error),
545        Err(send_error) => {
546            ServerInitializeError::transport::<T>(send_error, "sending error response")
547        }
548    }
549}
550
551async fn serve_server_with_ct_inner<S, T>(
552    service: S,
553    transport: T,
554    ct: CancellationToken,
555) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
556where
557    S: Service<RoleServer>,
558    T: Transport<RoleServer> + 'static,
559{
560    let mut transport = transport.into_transport();
561    let id_provider = <Arc<AtomicU32RequestIdProvider>>::default();
562
563    let (peer, peer_rx) = Peer::new(id_provider.clone(), None);
564
565    // Select the lifecycle only after an initialize request or the first valid
566    // non-discover request with complete inline metadata. A discover request is
567    // a bootstrap probe: respond to it, but remain open to either lifecycle.
568    // The MCP spec also permits ping before initialize.
569    // See: https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#initialization
570    let (initialize_request, id) = loop {
571        let msg = expect_next_message(&mut transport, "initialize request").await?;
572        match msg {
573            ClientJsonRpcMessage::Request(req)
574                if matches!(req.request, ClientRequest::PingRequest(_)) =>
575            {
576                transport
577                    .send(ServerJsonRpcMessage::response(
578                        ServerResult::EmptyResult(EmptyResult {}),
579                        req.id,
580                    ))
581                    .await
582                    .map_err(|error| {
583                        ServerInitializeError::transport::<T>(
584                            error,
585                            "sending pre-init ping response",
586                        )
587                    })?;
588            }
589            ClientJsonRpcMessage::Request(req) => {
590                let id = req.id;
591                let mut request = match req.request {
592                    ClientRequest::InitializeRequest(request) => break (request, id),
593                    request => request,
594                };
595                let missing_metadata = request
596                    .get_meta()
597                    .missing_required_keys(&ProtocolVersion::V_2026_07_28);
598                let requested_version = match request.get_meta().protocol_version() {
599                    Some(version) if missing_metadata.is_empty() => version,
600                    _ => {
601                        transport
602                            .send(ServerJsonRpcMessage::error(
603                                missing_request_metadata_error(&missing_metadata),
604                                Some(id),
605                            ))
606                            .await
607                            .map_err(|error| {
608                                ServerInitializeError::transport::<T>(
609                                    error,
610                                    "sending pre-init metadata error response",
611                                )
612                            })?;
613                        continue;
614                    }
615                };
616
617                if matches!(request, ClientRequest::DiscoverRequest(_)) {
618                    // No lifecycle exists yet, so the handler gets a peer that
619                    // cannot reach the client.
620                    let (bootstrap_peer, _) = Peer::new(id_provider.clone(), None);
621                    let context = RequestContext {
622                        ct: ct.child_token(),
623                        id: id.clone(),
624                        meta: std::mem::take(request.get_meta_mut()),
625                        extensions: std::mem::take(request.extensions_mut()),
626                        peer: bootstrap_peer,
627                    };
628                    let response = match service.handle_request(request, context).await {
629                        Ok(result) => ServerJsonRpcMessage::response(result, id),
630                        Err(error) => ServerJsonRpcMessage::error(error, Some(id)),
631                    };
632                    transport.send(response).await.map_err(|error| {
633                        ServerInitializeError::transport::<T>(
634                            error,
635                            "sending bootstrap request response",
636                        )
637                    })?;
638                    continue;
639                }
640
641                let supported_versions = service.supported_protocol_versions();
642                if !supported_versions.contains(&requested_version) {
643                    transport
644                        .send(ServerJsonRpcMessage::error(
645                            ErrorData::unsupported_protocol_version(
646                                requested_version,
647                                &supported_versions,
648                            ),
649                            Some(id),
650                        ))
651                        .await
652                        .map_err(|error| {
653                            ServerInitializeError::transport::<T>(
654                                error,
655                                "sending unsupported inline version response",
656                            )
657                        })?;
658                    continue;
659                }
660                peer.set_inline_protocol_version(requested_version);
661                // Dispatch the request from inside the service loop rather than
662                // inline: its handler may send notifications through `peer`, which
663                // only complete once the loop drains `peer_rx`.
664                return Ok(serve_inner(
665                    service,
666                    transport,
667                    peer,
668                    peer_rx,
669                    VecDeque::from([ClientJsonRpcMessage::request(request, id)]),
670                    ct,
671                ));
672            }
673            other => {
674                return Err(ServerInitializeError::ExpectedInitializeRequest(Some(
675                    other,
676                )));
677            }
678        }
679    };
680    let requested_protocol_version = initialize_request.params.protocol_version.clone();
681    let mut negotiated_peer_info = initialize_request.params.clone();
682    peer.set_peer_info(negotiated_peer_info.clone());
683    let request = ClientRequest::InitializeRequest(initialize_request);
684    let context = RequestContext {
685        ct: ct.child_token(),
686        id: id.clone(),
687        meta: request.get_meta().clone(),
688        extensions: request.extensions().clone(),
689        peer: peer.clone(),
690    };
691    // Send initialize response
692    let mut init_response = match service.handle_request(request, context).await {
693        Ok(ServerResult::InitializeResult(init_response)) => init_response,
694        Ok(result) => {
695            return Err(ServerInitializeError::UnexpectedInitializeResponse(result));
696        }
697        Err(e) => return Err(report_initialize_failure(&mut transport, e, id).await),
698    };
699    init_response.protocol_version = match negotiate_protocol_version(
700        &requested_protocol_version,
701        init_response.protocol_version,
702        &service.supported_protocol_versions(),
703    ) {
704        Ok(version) => version,
705        Err(e) => return Err(report_initialize_failure(&mut transport, e, id).await),
706    };
707    // Update peer_info so context.protocol_version() reflects the negotiated
708    // version in all subsequent request handlers.
709    negotiated_peer_info.protocol_version = init_response.protocol_version.clone();
710    peer.set_peer_info(negotiated_peer_info);
711    transport
712        .send(ServerJsonRpcMessage::response(
713            ServerResult::InitializeResult(init_response),
714            id,
715        ))
716        .await
717        .map_err(|error| {
718            ServerInitializeError::transport::<T>(error, "sending initialize response")
719        })?;
720
721    // Enter the main service loop immediately after sending InitializeResult.
722    // The initialized notification will be handled as a regular notification by serve_inner.
723    // This matches the TypeScript SDK behavior: no init gate, no waiting for initialized.
724    // Streamable HTTP has no ordering guarantee between POSTs, and the MCP spec uses
725    // SHOULD NOT (not MUST NOT) for pre-initialized messages, so any request arriving
726    // before initialized is processed normally.
727    Ok(serve_inner(
728        service,
729        transport,
730        peer,
731        peer_rx,
732        VecDeque::new(),
733        ct,
734    ))
735}
736
737macro_rules! method {
738    ($(#[$meta:meta])* peer_req $method:ident $Req:ident() => $Resp: ident ) => {
739        $(#[$meta])*
740        pub async fn $method(&self) -> Result<$Resp, ServiceError> {
741            let result = self
742                .send_request(ServerRequest::$Req($Req {
743                    method: Default::default(),
744                    extensions: Default::default(),
745                }))
746                .await?;
747            match result {
748                ClientResult::$Resp(result) => Ok(result),
749                _ => Err(ServiceError::UnexpectedResponse),
750            }
751        }
752    };
753    ($(#[$meta:meta])* peer_req $method:ident $Req:ident($Param: ident) => $Resp: ident ) => {
754        $(#[$meta])*
755        pub async fn $method(&self, params: $Param) -> Result<$Resp, ServiceError> {
756            let result = self
757                .send_request(ServerRequest::$Req($Req {
758                    method: Default::default(),
759                    params,
760                    extensions: Default::default(),
761                }))
762                .await?;
763            match result {
764                ClientResult::$Resp(result) => Ok(result),
765                _ => Err(ServiceError::UnexpectedResponse),
766            }
767        }
768    };
769    ($(#[$meta:meta])* peer_req $method:ident $Req:ident($Param: ident)) => {
770        $(#[$meta])*
771        pub fn $method(
772            &self,
773            params: $Param,
774        ) -> impl Future<Output = Result<(), ServiceError>> + Send + '_ {
775            async move {
776                let result = self
777                    .send_request(ServerRequest::$Req($Req {
778                        method: Default::default(),
779                        params,
780                    }))
781                    .await?;
782                match result {
783                    ClientResult::EmptyResult(_) => Ok(()),
784                    _ => Err(ServiceError::UnexpectedResponse),
785                }
786            }
787        }
788    };
789
790    ($(#[$meta:meta])* peer_not $method:ident $Not:ident($Param: ident)) => {
791        $(#[$meta])*
792        pub async fn $method(&self, params: $Param) -> Result<(), ServiceError> {
793            self.send_notification(ServerNotification::$Not($Not {
794                method: Default::default(),
795                params,
796                extensions: Default::default(),
797            }))
798            .await?;
799            Ok(())
800        }
801    };
802    ($(#[$meta:meta])* peer_not $method:ident $Not:ident) => {
803        $(#[$meta])*
804        pub async fn $method(&self) -> Result<(), ServiceError> {
805            self.send_notification(ServerNotification::$Not($Not {
806                method: Default::default(),
807                extensions: Default::default(),
808            }))
809            .await?;
810            Ok(())
811        }
812    };
813
814    // Timeout-only variants (base method should be created separately with peer_req)
815    ($(#[$meta:meta])* peer_req_with_timeout $method_with_timeout:ident $Req:ident() => $Resp: ident) => {
816        $(#[$meta])*
817        pub async fn $method_with_timeout(
818            &self,
819            timeout: Option<std::time::Duration>,
820        ) -> Result<$Resp, ServiceError> {
821            let request = ServerRequest::$Req($Req {
822                method: Default::default(),
823                extensions: Default::default(),
824            });
825            let options = crate::service::PeerRequestOptions {
826                timeout,
827                meta: None,
828                reset_timeout_on_progress: false,
829                max_total_timeout: None,
830            };
831            let result = self
832                .send_request_with_option(request, options)
833                .await?
834                .await_response()
835                .await?;
836            match result {
837                ClientResult::$Resp(result) => Ok(result),
838                _ => Err(ServiceError::UnexpectedResponse),
839            }
840        }
841    };
842
843    ($(#[$meta:meta])* peer_req_with_timeout $method_with_timeout:ident $Req:ident($Param: ident) => $Resp: ident) => {
844        $(#[$meta])*
845        pub async fn $method_with_timeout(
846            &self,
847            params: $Param,
848            timeout: Option<std::time::Duration>,
849        ) -> Result<$Resp, ServiceError> {
850            let request = ServerRequest::$Req($Req {
851                method: Default::default(),
852                params,
853                extensions: Default::default(),
854            });
855            let options = crate::service::PeerRequestOptions {
856                timeout,
857                meta: None,
858                reset_timeout_on_progress: false,
859                max_total_timeout: None,
860            };
861            let result = self
862                .send_request_with_option(request, options)
863                .await?
864                .await_response()
865                .await?;
866            match result {
867                ClientResult::$Resp(result) => Ok(result),
868                _ => Err(ServiceError::UnexpectedResponse),
869            }
870        }
871    };
872}
873
874impl Peer<RoleServer> {
875    /// Check if the client supports sampling tools capability.
876    pub fn supports_sampling_tools(&self) -> bool {
877        if let Some(client_info) = self.peer_info() {
878            client_info
879                .capabilities
880                .sampling
881                .as_ref()
882                .and_then(|s| s.tools.as_ref())
883                .is_some()
884        } else {
885            false
886        }
887    }
888
889    /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
890    /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
891    #[deprecated(
892        since = "1.8.0",
893        note = "Sampling is deprecated by SEP-2577 and will be removed in a future release. See https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577"
894    )]
895    pub async fn create_message(
896        &self,
897        params: CreateMessageRequestParams,
898    ) -> Result<CreateMessageResult, ServiceError> {
899        // MUST throw error when tools/toolChoice provided without capability
900        if (params.tools.is_some() || params.tool_choice.is_some())
901            && !self.supports_sampling_tools()
902        {
903            return Err(ServiceError::McpError(ErrorData::invalid_params(
904                "tools or toolChoice provided but client does not support sampling tools capability",
905                None,
906            )));
907        }
908        // Validate message structure
909        params
910            .validate()
911            .map_err(|e| ServiceError::McpError(ErrorData::invalid_params(e, None)))?;
912        let result = self
913            .send_request(ServerRequest::CreateMessageRequest(CreateMessageRequest {
914                method: Default::default(),
915                params,
916                extensions: Default::default(),
917            }))
918            .await?;
919        match result {
920            ClientResult::CreateMessageResult(result) => Ok(*result),
921            _ => Err(ServiceError::UnexpectedResponse),
922        }
923    }
924    method!(
925        /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
926        /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
927        #[deprecated(
928            since = "1.8.0",
929            note = "Roots is deprecated by SEP-2577 and will be removed in a future release. See https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577"
930        )]
931        peer_req list_roots ListRootsRequest() => ListRootsResult
932    );
933    #[cfg(feature = "elicitation")]
934    method!(
935        /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
936        /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
937        peer_req create_elicitation ElicitRequest(ElicitRequestParams) => ElicitResult
938    );
939    #[cfg(feature = "elicitation")]
940    method!(
941        /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
942        /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
943        peer_req_with_timeout create_elicitation_with_timeout ElicitRequest(ElicitRequestParams) => ElicitResult
944    );
945
946    method!(peer_not notify_cancelled CancelledNotification(CancelledNotificationParam));
947    method!(peer_not notify_progress ProgressNotification(ProgressNotificationParam));
948    method!(
949        #[deprecated(
950            since = "1.8.0",
951            note = "Logging is deprecated by SEP-2577 and will be removed in a future release. See https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577"
952        )]
953        peer_not notify_logging_message LoggingMessageNotification(LoggingMessageNotificationParam)
954    );
955    method!(peer_not notify_resource_updated ResourceUpdatedNotification(ResourceUpdatedNotificationParam));
956    method!(peer_not notify_resource_list_changed ResourceListChangedNotification);
957    method!(peer_not notify_tool_list_changed ToolListChangedNotification);
958    method!(peer_not notify_prompt_list_changed PromptListChangedNotification);
959}
960
961// =============================================================================
962// ELICITATION CONVENIENCE METHODS
963// These methods are specific to server role and provide typed elicitation functionality
964// =============================================================================
965
966/// Errors that can occur during typed elicitation operations
967#[cfg(feature = "elicitation")]
968#[derive(Error, Debug)]
969#[non_exhaustive]
970pub enum ElicitationError {
971    /// The elicitation request failed at the service level
972    #[error("Service error: {0}")]
973    Service(#[from] ServiceError),
974
975    /// User explicitly declined to provide the requested information
976    /// This indicates a conscious decision by the user to reject the request
977    /// (e.g., clicked "Reject", "Decline", "No", etc.)
978    #[error("User explicitly declined the request")]
979    UserDeclined,
980
981    /// User dismissed the request without making an explicit choice
982    /// This indicates the user cancelled without explicitly declining
983    /// (e.g., closed dialog, clicked outside, pressed Escape, etc.)
984    #[error("User cancelled/dismissed the request")]
985    UserCancelled,
986
987    /// The response data could not be parsed into the requested type
988    #[error("Failed to parse response data: {error}\nReceived data: {data}")]
989    ParseError {
990        error: serde_json::Error,
991        data: serde_json::Value,
992    },
993
994    /// No response content was provided by the user
995    #[error("No response content provided")]
996    NoContent,
997
998    /// Client does not support elicitation capability
999    #[error("Client does not support elicitation - capability not declared during initialization")]
1000    CapabilityNotSupported,
1001}
1002
1003/// Marker trait to ensure that elicitation types generate object-type JSON schemas.
1004///
1005/// This trait provides compile-time safety to ensure that types used with
1006/// `elicit<T>()` methods will generate JSON schemas of type "object", which
1007/// aligns with MCP client expectations for structured data input.
1008///
1009/// # Type Safety Rationale
1010///
1011/// MCP clients typically expect JSON objects for elicitation schemas to
1012/// provide structured forms and validation. This trait prevents common
1013/// mistakes like:
1014///
1015/// ```compile_fail
1016/// // These would not compile due to missing ElicitationSafe bound:
1017/// let name: String = server.elicit("Enter name").await?;        // Primitive
1018/// let items: Vec<i32> = server.elicit("Enter items").await?;    // Array
1019/// ```
1020#[cfg(feature = "elicitation")]
1021pub trait ElicitationSafe: schemars::JsonSchema {}
1022
1023/// Macro to mark types as safe for elicitation by verifying they generate object schemas.
1024///
1025/// This macro automatically implements the `ElicitationSafe` trait for struct types
1026/// that should be used with `elicit<T>()` methods.
1027///
1028/// # Example
1029///
1030/// ```rust
1031/// use rmcp::elicit_safe;
1032/// use schemars::JsonSchema;
1033/// use serde::{Deserialize, Serialize};
1034///
1035/// #[derive(Serialize, Deserialize, JsonSchema)]
1036/// struct UserProfile {
1037///     name: String,
1038///     email: String,
1039/// }
1040///
1041/// elicit_safe!(UserProfile);
1042///
1043/// // Now safe to use in async context:
1044/// // let profile: UserProfile = server.elicit("Enter profile").await?;
1045/// ```
1046#[cfg(feature = "elicitation")]
1047#[macro_export]
1048macro_rules! elicit_safe {
1049    ($($t:ty),* $(,)?) => {
1050        $(
1051            impl $crate::service::ElicitationSafe for $t {}
1052        )*
1053    };
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1057#[non_exhaustive]
1058pub enum ElicitationMode {
1059    Form,
1060    Url,
1061}
1062
1063#[cfg(feature = "elicitation")]
1064impl Peer<RoleServer> {
1065    /// Check if the client supports elicitation capability
1066    ///
1067    /// Returns true if the client declared elicitation capability during initialization,
1068    /// false otherwise. According to MCP 2025-06-18 specification, clients that support
1069    /// elicitation MUST declare the capability during initialization.
1070    pub fn supported_elicitation_modes(&self) -> HashSet<ElicitationMode> {
1071        if let Some(client_info) = self.peer_info() {
1072            if let Some(elicit_capability) = &client_info.capabilities.elicitation {
1073                let mut modes = HashSet::new();
1074                // Backward compatibility: if neither form nor url is specified, assume form
1075                if elicit_capability.form.is_none() && elicit_capability.url.is_none() {
1076                    modes.insert(ElicitationMode::Form);
1077                } else {
1078                    if elicit_capability.form.is_some() {
1079                        modes.insert(ElicitationMode::Form);
1080                    }
1081                    if elicit_capability.url.is_some() {
1082                        modes.insert(ElicitationMode::Url);
1083                    }
1084                }
1085                modes
1086            } else {
1087                HashSet::new()
1088            }
1089        } else {
1090            HashSet::new()
1091        }
1092    }
1093
1094    /// Request typed data from the user with automatic schema generation.
1095    ///
1096    /// This method automatically generates the JSON schema from the Rust type using `schemars`,
1097    /// eliminating the need to manually create schemas. The response is automatically parsed
1098    /// into the requested type.
1099    ///
1100    /// **Requires the `elicitation` feature to be enabled.**
1101    ///
1102    /// # Type Requirements
1103    /// The type `T` must implement:
1104    /// - `schemars::JsonSchema` - for automatic schema generation
1105    /// - `serde::Deserialize` - for parsing the response
1106    ///
1107    /// # Arguments
1108    /// * `message` - The prompt message for the user
1109    ///
1110    /// # Returns
1111    /// * `Ok(Some(data))` if user provided valid data that matches type T
1112    /// * `Err(ElicitationError::UserDeclined)` if user explicitly declined the request
1113    /// * `Err(ElicitationError::UserCancelled)` if user cancelled/dismissed the request
1114    /// * `Err(ElicitationError::ParseError { .. })` if response data couldn't be parsed into type T
1115    /// * `Err(ElicitationError::NoContent)` if no response content was provided
1116    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
1117    ///
1118    /// # Example
1119    ///
1120    /// Add to your `Cargo.toml`:
1121    /// ```toml
1122    /// [dependencies]
1123    /// rmcp = { version = "0.3", features = ["elicitation"] }
1124    /// serde = { version = "1.0", features = ["derive"] }
1125    /// schemars = "1.0"
1126    /// ```
1127    ///
1128    /// ```rust,no_run
1129    /// # use rmcp::*;
1130    /// # use rmcp::service::ElicitationError;
1131    /// # use serde::{Deserialize, Serialize};
1132    /// # use schemars::JsonSchema;
1133    /// #
1134    /// #[derive(Debug, Serialize, Deserialize, JsonSchema)]
1135    /// struct UserProfile {
1136    ///     #[schemars(description = "Full name")]
1137    ///     name: String,
1138    ///     #[schemars(description = "Email address")]
1139    ///     email: String,
1140    ///     #[schemars(description = "Age")]
1141    ///     age: u8,
1142    /// }
1143    ///
1144    /// // Mark as safe for elicitation (generates object schema)
1145    /// rmcp::elicit_safe!(UserProfile);
1146    ///
1147    /// # async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
1148    /// match peer.elicit::<UserProfile>("Please enter your profile information").await {
1149    ///     Ok(Some(profile)) => {
1150    ///         println!("Name: {}, Email: {}, Age: {}", profile.name, profile.email, profile.age);
1151    ///     }
1152    ///     Ok(None) => {
1153    ///         println!("User provided no content");
1154    ///     }
1155    ///     Err(ElicitationError::UserDeclined) => {
1156    ///         println!("User explicitly declined to provide information");
1157    ///         // Handle explicit decline - perhaps offer alternatives
1158    ///     }
1159    ///     Err(ElicitationError::UserCancelled) => {
1160    ///         println!("User cancelled the request");
1161    ///         // Handle cancellation - perhaps prompt again later
1162    ///     }
1163    ///     Err(ElicitationError::ParseError { error, data }) => {
1164    ///         println!("Failed to parse response: {}\nData: {}", error, data);
1165    ///     }
1166    ///     Err(e) => return Err(e.into()),
1167    /// }
1168    /// # Ok(())
1169    /// # }
1170    /// ```
1171    ///
1172    /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
1173    /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
1174    #[cfg(all(feature = "schemars", feature = "elicitation"))]
1175    pub async fn elicit<T>(&self, message: impl Into<String>) -> Result<Option<T>, ElicitationError>
1176    where
1177        T: ElicitationSafe + for<'de> serde::Deserialize<'de>,
1178    {
1179        self.elicit_with_timeout(message, None).await
1180    }
1181
1182    /// Request typed data from the user with custom timeout.
1183    ///
1184    /// Same as `elicit()` but allows specifying a custom timeout for the request.
1185    /// If the user doesn't respond within the timeout, the request will be cancelled.
1186    ///
1187    /// # Arguments
1188    /// * `message` - The prompt message for the user
1189    /// * `timeout` - Optional timeout duration. If None, uses default timeout behavior
1190    ///
1191    /// # Returns
1192    /// Same as `elicit()` but may also return `ServiceError::Timeout` if timeout expires
1193    ///
1194    /// # Example
1195    /// ```rust,no_run
1196    /// # use rmcp::*;
1197    /// # use rmcp::service::ElicitationError;
1198    /// # use serde::{Deserialize, Serialize};
1199    /// # use schemars::JsonSchema;
1200    /// # use std::time::Duration;
1201    /// #
1202    /// #[derive(Debug, Serialize, Deserialize, JsonSchema)]
1203    /// struct QuickResponse {
1204    ///     answer: String,
1205    /// }
1206    ///
1207    /// // Mark as safe for elicitation
1208    /// rmcp::elicit_safe!(QuickResponse);
1209    ///
1210    /// # async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
1211    /// // Give user 30 seconds to respond
1212    /// let timeout = Some(Duration::from_secs(30));
1213    /// match peer.elicit_with_timeout::<QuickResponse>(
1214    ///     "Quick question - what's your answer?",
1215    ///     timeout
1216    /// ).await {
1217    ///     Ok(Some(response)) => println!("Got answer: {}", response.answer),
1218    ///     Ok(None) => println!("User provided no content"),
1219    ///     Err(ElicitationError::UserDeclined) => {
1220    ///         println!("User explicitly declined");
1221    ///         // Handle explicit decline
1222    ///     }
1223    ///     Err(ElicitationError::UserCancelled) => {
1224    ///         println!("User cancelled/dismissed");
1225    ///         // Handle cancellation
1226    ///     }
1227    ///     Err(ElicitationError::Service(ServiceError::Timeout { .. })) => {
1228    ///         println!("User didn't respond in time");
1229    ///     }
1230    ///     Err(e) => return Err(e.into()),
1231    /// }
1232    /// # Ok(())
1233    /// # }
1234    /// ```
1235    ///
1236    /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
1237    /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
1238    #[cfg(all(feature = "schemars", feature = "elicitation"))]
1239    pub async fn elicit_with_timeout<T>(
1240        &self,
1241        message: impl Into<String>,
1242        timeout: Option<std::time::Duration>,
1243    ) -> Result<Option<T>, ElicitationError>
1244    where
1245        T: ElicitationSafe + for<'de> serde::Deserialize<'de>,
1246    {
1247        // Reject on 2026-07-28 before the capability check, which would
1248        // otherwise answer `CapabilityNotSupported` first.
1249        RoleServer::enforce_outbound_request(self)?;
1250
1251        // Check if client supports form elicitation capability
1252        if !self
1253            .supported_elicitation_modes()
1254            .contains(&ElicitationMode::Form)
1255        {
1256            return Err(ElicitationError::CapabilityNotSupported);
1257        }
1258
1259        // Generate schema automatically from type
1260        let schema = crate::model::ElicitationSchema::from_type::<T>().map_err(|e| {
1261            ElicitationError::Service(ServiceError::McpError(crate::ErrorData::invalid_params(
1262                format!(
1263                    "Invalid schema for type {}: {}",
1264                    std::any::type_name::<T>(),
1265                    e
1266                ),
1267                None,
1268            )))
1269        })?;
1270
1271        let response = self
1272            .create_elicitation_with_timeout(
1273                ElicitRequestParams::FormElicitationParams {
1274                    meta: None,
1275                    message: message.into(),
1276                    requested_schema: schema,
1277                },
1278                timeout,
1279            )
1280            .await?;
1281
1282        match response.action {
1283            crate::model::ElicitationAction::Accept => {
1284                if let Some(value) = response.content {
1285                    match serde_json::from_value::<T>(value.clone()) {
1286                        Ok(parsed) => Ok(Some(parsed)),
1287                        Err(error) => Err(ElicitationError::ParseError { error, data: value }),
1288                    }
1289                } else {
1290                    Err(ElicitationError::NoContent)
1291                }
1292            }
1293            crate::model::ElicitationAction::Decline => Err(ElicitationError::UserDeclined),
1294            crate::model::ElicitationAction::Cancel => Err(ElicitationError::UserCancelled),
1295        }
1296    }
1297
1298    /// Request the user to visit a URL and confirm completion.
1299    ///
1300    /// This method sends a URL elicitation request to the client, prompting the user
1301    /// to visit the specified URL and confirm completion. It returns the user's action
1302    /// (accept/decline/cancel) without any additional data.
1303    /// **Requires the `elicitation` feature to be enabled.**
1304    ///
1305    /// # Arguments
1306    /// * `message` - The prompt message for the user
1307    /// * `url` - The URL the user is requested to visit
1308    /// * `elicitation_id` - A unique identifier for this elicitation request
1309    /// # Returns
1310    /// * `Ok(action)` indicating the user's response action
1311    /// * `Err(ElicitationError::CapabilityNotSupported)` if client does not support elicitation via URL
1312    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
1313    /// # Example
1314    /// ```rust,no_run
1315    /// # use rmcp::*;
1316    /// # use rmcp::model::ElicitationAction;
1317    /// # use url::Url;
1318    ///
1319    /// async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
1320    /// let elicit_result = peer.elicit_url("Please visit the following URL to complete the action",
1321    ///      Url::parse("https://example.com/complete_action")?, "elicit_123").await?;
1322    ///  match elicit_result {
1323    ///        ElicitationAction::Accept => {
1324    ///        println!("User accepted and confirmed completion");
1325    ///     }
1326    ///     ElicitationAction::Decline => {
1327    ///          println!("User declined the request");
1328    ///     }
1329    ///     ElicitationAction::Cancel => {
1330    ///         println!("User cancelled/dismissed the request");
1331    ///     }
1332    ///     _ => {}
1333    ///  }
1334    ///  Ok(())
1335    /// }
1336    /// ```
1337    ///
1338    /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
1339    /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
1340    #[cfg(feature = "elicitation")]
1341    pub async fn elicit_url(
1342        &self,
1343        message: impl Into<String>,
1344        url: impl Into<Url>,
1345        elicitation_id: impl Into<String>,
1346    ) -> Result<ElicitationAction, ElicitationError> {
1347        self.elicit_url_with_timeout(message, url, elicitation_id, None)
1348            .await
1349    }
1350
1351    /// Request the user to visit a URL and confirm completion.
1352    ///
1353    /// Same as `elicit_url()` but allows specifying a custom timeout for the request.
1354    ///
1355    /// # Arguments
1356    /// * `message` - The prompt message for the user
1357    /// * `url` - The URL the user is requested to visit
1358    /// * `elicitation_id` - A unique identifier for this elicitation request
1359    /// * `timeout` - Optional timeout duration. If None, uses default timeout behavior
1360    /// # Returns
1361    /// * `Ok(action)` indicating the user's response action
1362    /// * `Err(ElicitationError::CapabilityNotSupported)` if client does not support elicitation via URL
1363    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
1364    /// # Example
1365    /// ```rust,no_run
1366    /// # use std::time::Duration;
1367    /// use rmcp::*;
1368    /// # use rmcp::model::ElicitationAction;
1369    /// # use url::Url;
1370    ///
1371    /// async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
1372    /// let elicit_result = peer.elicit_url_with_timeout("Please visit the following URL to complete the action",
1373    ///      Url::parse("https://example.com/complete_action")?,
1374    ///     "elicit_123",
1375    ///     Some(Duration::from_secs(30))).await?;
1376    ///  match elicit_result {
1377    ///        ElicitationAction::Accept => {
1378    ///        println!("User accepted and confirmed completion");
1379    ///     }
1380    ///     ElicitationAction::Decline => {
1381    ///          println!("User declined the request");
1382    ///     }
1383    ///     ElicitationAction::Cancel => {
1384    ///         println!("User cancelled/dismissed the request");
1385    ///     }
1386    ///     _ => {}
1387    ///  }
1388    ///  Ok(())
1389    /// }
1390    /// ```
1391    ///
1392    /// Errors on protocol `2026-07-28` or later, which forbids server-to-client
1393    /// requests; return an [`InputRequiredResult`](crate::model::InputRequiredResult) instead.
1394    #[cfg(feature = "elicitation")]
1395    pub async fn elicit_url_with_timeout(
1396        &self,
1397        message: impl Into<String>,
1398        url: impl Into<Url>,
1399        elicitation_id: impl Into<String>,
1400        timeout: Option<std::time::Duration>,
1401    ) -> Result<ElicitationAction, ElicitationError> {
1402        // Reject on 2026-07-28 before the capability check, which would
1403        // otherwise answer `CapabilityNotSupported` first.
1404        RoleServer::enforce_outbound_request(self)?;
1405
1406        // Check if client supports url elicitation
1407        if !self
1408            .supported_elicitation_modes()
1409            .contains(&ElicitationMode::Url)
1410        {
1411            return Err(ElicitationError::CapabilityNotSupported);
1412        }
1413
1414        let action = self
1415            .create_elicitation_with_timeout(
1416                ElicitRequestParams::UrlElicitationParams {
1417                    meta: None,
1418                    message: message.into(),
1419                    url: url.into().to_string(),
1420                    elicitation_id: elicitation_id.into(),
1421                },
1422                timeout,
1423            )
1424            .await?
1425            .action;
1426        Ok(action)
1427    }
1428}