rmcp 0.15.0

Rust SDK for Model Context Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
use std::borrow::Cow;
#[cfg(feature = "elicitation")]
use std::collections::HashSet;

use thiserror::Error;
#[cfg(feature = "elicitation")]
use url::Url;

use super::*;
#[cfg(feature = "elicitation")]
use crate::model::{
    CreateElicitationRequest, CreateElicitationRequestParams, CreateElicitationResult,
    ElicitationAction, ElicitationCompletionNotification, ElicitationResponseNotificationParam,
};
use crate::{
    model::{
        CancelledNotification, CancelledNotificationParam, ClientInfo, ClientJsonRpcMessage,
        ClientNotification, ClientRequest, ClientResult, CreateMessageRequest,
        CreateMessageRequestParams, CreateMessageResult, ErrorData, ListRootsRequest,
        ListRootsResult, LoggingMessageNotification, LoggingMessageNotificationParam,
        ProgressNotification, ProgressNotificationParam, PromptListChangedNotification,
        ProtocolVersion, ResourceListChangedNotification, ResourceUpdatedNotification,
        ResourceUpdatedNotificationParam, ServerInfo, ServerNotification, ServerRequest,
        ServerResult, ToolListChangedNotification,
    },
    transport::DynamicTransportError,
};

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RoleServer;

impl ServiceRole for RoleServer {
    type Req = ServerRequest;
    type Resp = ServerResult;
    type Not = ServerNotification;
    type PeerReq = ClientRequest;
    type PeerResp = ClientResult;
    type PeerNot = ClientNotification;
    type Info = ServerInfo;
    type PeerInfo = ClientInfo;

    type InitializeError = ServerInitializeError;
    const IS_CLIENT: bool = false;
}

/// It represents the error that may occur when serving the server.
///
/// if you want to handle the error, you can use `serve_server_with_ct` or `serve_server` with `Result<RunningService<RoleServer, S>, ServerError>`
#[derive(Error, Debug)]
pub enum ServerInitializeError {
    #[error("expect initialized request, but received: {0:?}")]
    ExpectedInitializeRequest(Option<ClientJsonRpcMessage>),

    #[error("expect initialized notification, but received: {0:?}")]
    ExpectedInitializedNotification(Option<ClientJsonRpcMessage>),

    #[error("connection closed: {0}")]
    ConnectionClosed(String),

    #[error("unexpected initialize result: {0:?}")]
    UnexpectedInitializeResponse(ServerResult),

    #[error("initialize failed: {0}")]
    InitializeFailed(ErrorData),

    #[error("unsupported protocol version: {0}")]
    UnsupportedProtocolVersion(ProtocolVersion),

    #[error("Send message error {error}, when {context}")]
    TransportError {
        error: DynamicTransportError,
        context: Cow<'static, str>,
    },

    #[error("Cancelled")]
    Cancelled,
}

impl ServerInitializeError {
    pub fn transport<T: Transport<RoleServer> + 'static>(
        error: T::Error,
        context: impl Into<Cow<'static, str>>,
    ) -> Self {
        Self::TransportError {
            error: DynamicTransportError::new::<T, _>(error),
            context: context.into(),
        }
    }
}
pub type ClientSink = Peer<RoleServer>;

impl<S: Service<RoleServer>> ServiceExt<RoleServer> for S {
    fn serve_with_ct<T, E, A>(
        self,
        transport: T,
        ct: CancellationToken,
    ) -> impl Future<Output = Result<RunningService<RoleServer, Self>, ServerInitializeError>> + Send
    where
        T: IntoTransport<RoleServer, E, A>,
        E: std::error::Error + Send + Sync + 'static,
        Self: Sized,
    {
        serve_server_with_ct(self, transport, ct)
    }
}

pub async fn serve_server<S, T, E, A>(
    service: S,
    transport: T,
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
where
    S: Service<RoleServer>,
    T: IntoTransport<RoleServer, E, A>,
    E: std::error::Error + Send + Sync + 'static,
{
    serve_server_with_ct(service, transport, CancellationToken::new()).await
}

/// Helper function to get the next message from the stream
async fn expect_next_message<T>(
    transport: &mut T,
    context: &str,
) -> Result<ClientJsonRpcMessage, ServerInitializeError>
where
    T: Transport<RoleServer>,
{
    transport
        .receive()
        .await
        .ok_or_else(|| ServerInitializeError::ConnectionClosed(context.to_string()))
}

/// Helper function to expect a request from the stream
async fn expect_request<T>(
    transport: &mut T,
    context: &str,
) -> Result<(ClientRequest, RequestId), ServerInitializeError>
where
    T: Transport<RoleServer>,
{
    let msg = expect_next_message(transport, context).await?;
    let msg_clone = msg.clone();
    msg.into_request()
        .ok_or(ServerInitializeError::ExpectedInitializeRequest(Some(
            msg_clone,
        )))
}

/// Helper function to expect a notification from the stream
async fn expect_notification<T>(
    transport: &mut T,
    context: &str,
) -> Result<ClientNotification, ServerInitializeError>
where
    T: Transport<RoleServer>,
{
    let msg = expect_next_message(transport, context).await?;
    let msg_clone = msg.clone();
    msg.into_notification()
        .ok_or(ServerInitializeError::ExpectedInitializedNotification(
            Some(msg_clone),
        ))
}

pub async fn serve_server_with_ct<S, T, E, A>(
    service: S,
    transport: T,
    ct: CancellationToken,
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
where
    S: Service<RoleServer>,
    T: IntoTransport<RoleServer, E, A>,
    E: std::error::Error + Send + Sync + 'static,
{
    tokio::select! {
        result = serve_server_with_ct_inner(service, transport.into_transport(), ct.clone()) => { result }
        _ = ct.cancelled() => {
            Err(ServerInitializeError::Cancelled)
        }
    }
}

async fn serve_server_with_ct_inner<S, T>(
    service: S,
    transport: T,
    ct: CancellationToken,
) -> Result<RunningService<RoleServer, S>, ServerInitializeError>
where
    S: Service<RoleServer>,
    T: Transport<RoleServer> + 'static,
{
    let mut transport = transport.into_transport();
    let id_provider = <Arc<AtomicU32RequestIdProvider>>::default();

    // Get initialize request
    let (request, id) = expect_request(&mut transport, "initialized request").await?;

    let ClientRequest::InitializeRequest(peer_info) = &request else {
        return Err(ServerInitializeError::ExpectedInitializeRequest(Some(
            ClientJsonRpcMessage::request(request, id),
        )));
    };
    let (peer, peer_rx) = Peer::new(id_provider, Some(peer_info.params.clone()));
    let context = RequestContext {
        ct: ct.child_token(),
        id: id.clone(),
        meta: request.get_meta().clone(),
        extensions: request.extensions().clone(),
        peer: peer.clone(),
    };
    // Send initialize response
    let init_response = service.handle_request(request.clone(), context).await;
    let mut init_response = match init_response {
        Ok(ServerResult::InitializeResult(init_response)) => init_response,
        Ok(result) => {
            return Err(ServerInitializeError::UnexpectedInitializeResponse(result));
        }
        Err(e) => {
            transport
                .send(ServerJsonRpcMessage::error(e.clone(), id))
                .await
                .map_err(|error| {
                    ServerInitializeError::transport::<T>(error, "sending error response")
                })?;
            return Err(ServerInitializeError::InitializeFailed(e));
        }
    };
    let peer_protocol_version = peer_info.params.protocol_version.clone();
    let protocol_version = match peer_protocol_version
        .partial_cmp(&init_response.protocol_version)
        .ok_or(ServerInitializeError::UnsupportedProtocolVersion(
            peer_protocol_version,
        ))? {
        std::cmp::Ordering::Less => peer_info.params.protocol_version.clone(),
        _ => init_response.protocol_version,
    };
    init_response.protocol_version = protocol_version;
    transport
        .send(ServerJsonRpcMessage::response(
            ServerResult::InitializeResult(init_response),
            id,
        ))
        .await
        .map_err(|error| {
            ServerInitializeError::transport::<T>(error, "sending initialize response")
        })?;

    // Wait for initialize notification
    let notification = expect_notification(&mut transport, "initialize notification").await?;
    let ClientNotification::InitializedNotification(_) = notification else {
        return Err(ServerInitializeError::ExpectedInitializedNotification(
            Some(ClientJsonRpcMessage::notification(notification)),
        ));
    };
    let context = NotificationContext {
        meta: notification.get_meta().clone(),
        extensions: notification.extensions().clone(),
        peer: peer.clone(),
    };
    let _ = service.handle_notification(notification, context).await;
    // Continue processing service
    Ok(serve_inner(service, transport, peer, peer_rx, ct))
}

macro_rules! method {
    (peer_req $method:ident $Req:ident() => $Resp: ident ) => {
        pub async fn $method(&self) -> Result<$Resp, ServiceError> {
            let result = self
                .send_request(ServerRequest::$Req($Req {
                    method: Default::default(),
                    extensions: Default::default(),
                }))
                .await?;
            match result {
                ClientResult::$Resp(result) => Ok(result),
                _ => Err(ServiceError::UnexpectedResponse),
            }
        }
    };
    (peer_req $method:ident $Req:ident($Param: ident) => $Resp: ident ) => {
        pub async fn $method(&self, params: $Param) -> Result<$Resp, ServiceError> {
            let result = self
                .send_request(ServerRequest::$Req($Req {
                    method: Default::default(),
                    params,
                    extensions: Default::default(),
                }))
                .await?;
            match result {
                ClientResult::$Resp(result) => Ok(result),
                _ => Err(ServiceError::UnexpectedResponse),
            }
        }
    };
    (peer_req $method:ident $Req:ident($Param: ident)) => {
        pub fn $method(
            &self,
            params: $Param,
        ) -> impl Future<Output = Result<(), ServiceError>> + Send + '_ {
            async move {
                let result = self
                    .send_request(ServerRequest::$Req($Req {
                        method: Default::default(),
                        params,
                    }))
                    .await?;
                match result {
                    ClientResult::EmptyResult(_) => Ok(()),
                    _ => Err(ServiceError::UnexpectedResponse),
                }
            }
        }
    };

    (peer_not $method:ident $Not:ident($Param: ident)) => {
        pub async fn $method(&self, params: $Param) -> Result<(), ServiceError> {
            self.send_notification(ServerNotification::$Not($Not {
                method: Default::default(),
                params,
                extensions: Default::default(),
            }))
            .await?;
            Ok(())
        }
    };
    (peer_not $method:ident $Not:ident) => {
        pub async fn $method(&self) -> Result<(), ServiceError> {
            self.send_notification(ServerNotification::$Not($Not {
                method: Default::default(),
                extensions: Default::default(),
            }))
            .await?;
            Ok(())
        }
    };

    // Timeout-only variants (base method should be created separately with peer_req)
    (peer_req_with_timeout $method_with_timeout:ident $Req:ident() => $Resp: ident) => {
        pub async fn $method_with_timeout(
            &self,
            timeout: Option<std::time::Duration>,
        ) -> Result<$Resp, ServiceError> {
            let request = ServerRequest::$Req($Req {
                method: Default::default(),
                extensions: Default::default(),
            });
            let options = crate::service::PeerRequestOptions {
                timeout,
                meta: None,
            };
            let result = self
                .send_request_with_option(request, options)
                .await?
                .await_response()
                .await?;
            match result {
                ClientResult::$Resp(result) => Ok(result),
                _ => Err(ServiceError::UnexpectedResponse),
            }
        }
    };

    (peer_req_with_timeout $method_with_timeout:ident $Req:ident($Param: ident) => $Resp: ident) => {
        pub async fn $method_with_timeout(
            &self,
            params: $Param,
            timeout: Option<std::time::Duration>,
        ) -> Result<$Resp, ServiceError> {
            let request = ServerRequest::$Req($Req {
                method: Default::default(),
                params,
                extensions: Default::default(),
            });
            let options = crate::service::PeerRequestOptions {
                timeout,
                meta: None,
            };
            let result = self
                .send_request_with_option(request, options)
                .await?
                .await_response()
                .await?;
            match result {
                ClientResult::$Resp(result) => Ok(result),
                _ => Err(ServiceError::UnexpectedResponse),
            }
        }
    };
}

impl Peer<RoleServer> {
    /// Check if the client supports sampling tools capability.
    pub fn supports_sampling_tools(&self) -> bool {
        if let Some(client_info) = self.peer_info() {
            client_info
                .capabilities
                .sampling
                .as_ref()
                .and_then(|s| s.tools.as_ref())
                .is_some()
        } else {
            false
        }
    }

    pub async fn create_message(
        &self,
        params: CreateMessageRequestParams,
    ) -> Result<CreateMessageResult, ServiceError> {
        // MUST throw error when tools/toolChoice provided without capability
        if (params.tools.is_some() || params.tool_choice.is_some())
            && !self.supports_sampling_tools()
        {
            return Err(ServiceError::McpError(ErrorData::invalid_params(
                "tools or toolChoice provided but client does not support sampling tools capability",
                None,
            )));
        }
        // Validate message structure
        params
            .validate()
            .map_err(|e| ServiceError::McpError(ErrorData::invalid_params(e, None)))?;
        let result = self
            .send_request(ServerRequest::CreateMessageRequest(CreateMessageRequest {
                method: Default::default(),
                params,
                extensions: Default::default(),
            }))
            .await?;
        match result {
            ClientResult::CreateMessageResult(result) => Ok(*result),
            _ => Err(ServiceError::UnexpectedResponse),
        }
    }
    method!(peer_req list_roots ListRootsRequest() => ListRootsResult);
    #[cfg(feature = "elicitation")]
    method!(peer_req create_elicitation CreateElicitationRequest(CreateElicitationRequestParams) => CreateElicitationResult);
    #[cfg(feature = "elicitation")]
    method!(peer_req_with_timeout create_elicitation_with_timeout CreateElicitationRequest(CreateElicitationRequestParams) => CreateElicitationResult);
    #[cfg(feature = "elicitation")]
    method!(peer_not notify_url_elicitation_completed ElicitationCompletionNotification(ElicitationResponseNotificationParam));

    method!(peer_not notify_cancelled CancelledNotification(CancelledNotificationParam));
    method!(peer_not notify_progress ProgressNotification(ProgressNotificationParam));
    method!(peer_not notify_logging_message LoggingMessageNotification(LoggingMessageNotificationParam));
    method!(peer_not notify_resource_updated ResourceUpdatedNotification(ResourceUpdatedNotificationParam));
    method!(peer_not notify_resource_list_changed ResourceListChangedNotification);
    method!(peer_not notify_tool_list_changed ToolListChangedNotification);
    method!(peer_not notify_prompt_list_changed PromptListChangedNotification);
}

// =============================================================================
// ELICITATION CONVENIENCE METHODS
// These methods are specific to server role and provide typed elicitation functionality
// =============================================================================

/// Errors that can occur during typed elicitation operations
#[cfg(feature = "elicitation")]
#[derive(Error, Debug)]
pub enum ElicitationError {
    /// The elicitation request failed at the service level
    #[error("Service error: {0}")]
    Service(#[from] ServiceError),

    /// User explicitly declined to provide the requested information
    /// This indicates a conscious decision by the user to reject the request
    /// (e.g., clicked "Reject", "Decline", "No", etc.)
    #[error("User explicitly declined the request")]
    UserDeclined,

    /// User dismissed the request without making an explicit choice
    /// This indicates the user cancelled without explicitly declining
    /// (e.g., closed dialog, clicked outside, pressed Escape, etc.)
    #[error("User cancelled/dismissed the request")]
    UserCancelled,

    /// The response data could not be parsed into the requested type
    #[error("Failed to parse response data: {error}\nReceived data: {data}")]
    ParseError {
        error: serde_json::Error,
        data: serde_json::Value,
    },

    /// No response content was provided by the user
    #[error("No response content provided")]
    NoContent,

    /// Client does not support elicitation capability
    #[error("Client does not support elicitation - capability not declared during initialization")]
    CapabilityNotSupported,
}

/// Marker trait to ensure that elicitation types generate object-type JSON schemas.
///
/// This trait provides compile-time safety to ensure that types used with
/// `elicit<T>()` methods will generate JSON schemas of type "object", which
/// aligns with MCP client expectations for structured data input.
///
/// # Type Safety Rationale
///
/// MCP clients typically expect JSON objects for elicitation schemas to
/// provide structured forms and validation. This trait prevents common
/// mistakes like:
///
/// ```compile_fail
/// // These would not compile due to missing ElicitationSafe bound:
/// let name: String = server.elicit("Enter name").await?;        // Primitive
/// let items: Vec<i32> = server.elicit("Enter items").await?;    // Array
/// ```
#[cfg(feature = "elicitation")]
pub trait ElicitationSafe: schemars::JsonSchema {}

/// Macro to mark types as safe for elicitation by verifying they generate object schemas.
///
/// This macro automatically implements the `ElicitationSafe` trait for struct types
/// that should be used with `elicit<T>()` methods.
///
/// # Example
///
/// ```rust
/// use rmcp::elicit_safe;
/// use schemars::JsonSchema;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, JsonSchema)]
/// struct UserProfile {
///     name: String,
///     email: String,
/// }
///
/// elicit_safe!(UserProfile);
///
/// // Now safe to use in async context:
/// // let profile: UserProfile = server.elicit("Enter profile").await?;
/// ```
#[cfg(feature = "elicitation")]
#[macro_export]
macro_rules! elicit_safe {
    ($($t:ty),* $(,)?) => {
        $(
            impl $crate::service::ElicitationSafe for $t {}
        )*
    };
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ElicitationMode {
    Form,
    Url,
}

#[cfg(feature = "elicitation")]
impl Peer<RoleServer> {
    /// Check if the client supports elicitation capability
    ///
    /// Returns true if the client declared elicitation capability during initialization,
    /// false otherwise. According to MCP 2025-06-18 specification, clients that support
    /// elicitation MUST declare the capability during initialization.
    pub fn supported_elicitation_modes(&self) -> HashSet<ElicitationMode> {
        if let Some(client_info) = self.peer_info() {
            if let Some(elicit_capability) = &client_info.capabilities.elicitation {
                let mut modes = HashSet::new();
                // Backward compatibility: if neither form nor url is specified, assume form
                if elicit_capability.form.is_none() && elicit_capability.url.is_none() {
                    modes.insert(ElicitationMode::Form);
                } else {
                    if elicit_capability.form.is_some() {
                        modes.insert(ElicitationMode::Form);
                    }
                    if elicit_capability.url.is_some() {
                        modes.insert(ElicitationMode::Url);
                    }
                }
                modes
            } else {
                HashSet::new()
            }
        } else {
            HashSet::new()
        }
    }

    /// Request typed data from the user with automatic schema generation.
    ///
    /// This method automatically generates the JSON schema from the Rust type using `schemars`,
    /// eliminating the need to manually create schemas. The response is automatically parsed
    /// into the requested type.
    ///
    /// **Requires the `elicitation` feature to be enabled.**
    ///
    /// # Type Requirements
    /// The type `T` must implement:
    /// - `schemars::JsonSchema` - for automatic schema generation
    /// - `serde::Deserialize` - for parsing the response
    ///
    /// # Arguments
    /// * `message` - The prompt message for the user
    ///
    /// # Returns
    /// * `Ok(Some(data))` if user provided valid data that matches type T
    /// * `Err(ElicitationError::UserDeclined)` if user explicitly declined the request
    /// * `Err(ElicitationError::UserCancelled)` if user cancelled/dismissed the request
    /// * `Err(ElicitationError::ParseError { .. })` if response data couldn't be parsed into type T
    /// * `Err(ElicitationError::NoContent)` if no response content was provided
    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
    ///
    /// # Example
    ///
    /// Add to your `Cargo.toml`:
    /// ```toml
    /// [dependencies]
    /// rmcp = { version = "0.3", features = ["elicitation"] }
    /// serde = { version = "1.0", features = ["derive"] }
    /// schemars = "1.0"
    /// ```
    ///
    /// ```rust,no_run
    /// # use rmcp::*;
    /// # use rmcp::service::ElicitationError;
    /// # use serde::{Deserialize, Serialize};
    /// # use schemars::JsonSchema;
    /// #
    /// #[derive(Debug, Serialize, Deserialize, JsonSchema)]
    /// struct UserProfile {
    ///     #[schemars(description = "Full name")]
    ///     name: String,
    ///     #[schemars(description = "Email address")]
    ///     email: String,
    ///     #[schemars(description = "Age")]
    ///     age: u8,
    /// }
    ///
    /// // Mark as safe for elicitation (generates object schema)
    /// rmcp::elicit_safe!(UserProfile);
    ///
    /// # async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
    /// match peer.elicit::<UserProfile>("Please enter your profile information").await {
    ///     Ok(Some(profile)) => {
    ///         println!("Name: {}, Email: {}, Age: {}", profile.name, profile.email, profile.age);
    ///     }
    ///     Ok(None) => {
    ///         println!("User provided no content");
    ///     }
    ///     Err(ElicitationError::UserDeclined) => {
    ///         println!("User explicitly declined to provide information");
    ///         // Handle explicit decline - perhaps offer alternatives
    ///     }
    ///     Err(ElicitationError::UserCancelled) => {
    ///         println!("User cancelled the request");
    ///         // Handle cancellation - perhaps prompt again later
    ///     }
    ///     Err(ElicitationError::ParseError { error, data }) => {
    ///         println!("Failed to parse response: {}\nData: {}", error, data);
    ///     }
    ///     Err(e) => return Err(e.into()),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(all(feature = "schemars", feature = "elicitation"))]
    pub async fn elicit<T>(&self, message: impl Into<String>) -> Result<Option<T>, ElicitationError>
    where
        T: ElicitationSafe + for<'de> serde::Deserialize<'de>,
    {
        self.elicit_with_timeout(message, None).await
    }

    /// Request typed data from the user with custom timeout.
    ///
    /// Same as `elicit()` but allows specifying a custom timeout for the request.
    /// If the user doesn't respond within the timeout, the request will be cancelled.
    ///
    /// # Arguments
    /// * `message` - The prompt message for the user
    /// * `timeout` - Optional timeout duration. If None, uses default timeout behavior
    ///
    /// # Returns
    /// Same as `elicit()` but may also return `ServiceError::Timeout` if timeout expires
    ///
    /// # Example
    /// ```rust,no_run
    /// # use rmcp::*;
    /// # use rmcp::service::ElicitationError;
    /// # use serde::{Deserialize, Serialize};
    /// # use schemars::JsonSchema;
    /// # use std::time::Duration;
    /// #
    /// #[derive(Debug, Serialize, Deserialize, JsonSchema)]
    /// struct QuickResponse {
    ///     answer: String,
    /// }
    ///
    /// // Mark as safe for elicitation
    /// rmcp::elicit_safe!(QuickResponse);
    ///
    /// # async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
    /// // Give user 30 seconds to respond
    /// let timeout = Some(Duration::from_secs(30));
    /// match peer.elicit_with_timeout::<QuickResponse>(
    ///     "Quick question - what's your answer?",
    ///     timeout
    /// ).await {
    ///     Ok(Some(response)) => println!("Got answer: {}", response.answer),
    ///     Ok(None) => println!("User provided no content"),
    ///     Err(ElicitationError::UserDeclined) => {
    ///         println!("User explicitly declined");
    ///         // Handle explicit decline
    ///     }
    ///     Err(ElicitationError::UserCancelled) => {
    ///         println!("User cancelled/dismissed");
    ///         // Handle cancellation
    ///     }
    ///     Err(ElicitationError::Service(ServiceError::Timeout { .. })) => {
    ///         println!("User didn't respond in time");
    ///     }
    ///     Err(e) => return Err(e.into()),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(all(feature = "schemars", feature = "elicitation"))]
    pub async fn elicit_with_timeout<T>(
        &self,
        message: impl Into<String>,
        timeout: Option<std::time::Duration>,
    ) -> Result<Option<T>, ElicitationError>
    where
        T: ElicitationSafe + for<'de> serde::Deserialize<'de>,
    {
        // Check if client supports form elicitation capability
        if !self
            .supported_elicitation_modes()
            .contains(&ElicitationMode::Form)
        {
            return Err(ElicitationError::CapabilityNotSupported);
        }

        // Generate schema automatically from type
        let schema = crate::model::ElicitationSchema::from_type::<T>().map_err(|e| {
            ElicitationError::Service(ServiceError::McpError(crate::ErrorData::invalid_params(
                format!(
                    "Invalid schema for type {}: {}",
                    std::any::type_name::<T>(),
                    e
                ),
                None,
            )))
        })?;

        let response = self
            .create_elicitation_with_timeout(
                CreateElicitationRequestParams::FormElicitationParams {
                    meta: None,
                    message: message.into(),
                    requested_schema: schema,
                },
                timeout,
            )
            .await?;

        match response.action {
            crate::model::ElicitationAction::Accept => {
                if let Some(value) = response.content {
                    match serde_json::from_value::<T>(value.clone()) {
                        Ok(parsed) => Ok(Some(parsed)),
                        Err(error) => Err(ElicitationError::ParseError { error, data: value }),
                    }
                } else {
                    Err(ElicitationError::NoContent)
                }
            }
            crate::model::ElicitationAction::Decline => Err(ElicitationError::UserDeclined),
            crate::model::ElicitationAction::Cancel => Err(ElicitationError::UserCancelled),
        }
    }

    /// Request the user to visit a URL and confirm completion.
    ///
    /// This method sends a URL elicitation request to the client, prompting the user
    /// to visit the specified URL and confirm completion. It returns the user's action
    /// (accept/decline/cancel) without any additional data.
    /// **Requires the `elicitation` feature to be enabled.**
    ///
    /// # Arguments
    /// * `message` - The prompt message for the user
    /// * `url` - The URL the user is requested to visit
    /// * `elicitation_id` - A unique identifier for this elicitation request
    /// # Returns
    /// * `Ok(action)` indicating the user's response action
    /// * `Err(ElicitationError::CapabilityNotSupported)` if client does not support elicitation via URL
    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
    /// # Example
    /// ```rust,no_run
    /// # use rmcp::*;
    /// # use rmcp::model::ElicitationAction;
    /// # use url::Url;
    ///
    /// async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
    /// let elicit_result = peer.elicit_url("Please visit the following URL to complete the action",
    ///      Url::parse("https://example.com/complete_action")?, "elicit_123").await?;
    ///  match elicit_result {
    ///        ElicitationAction::Accept => {
    ///        println!("User accepted and confirmed completion");
    ///     }
    ///     ElicitationAction::Decline => {
    ///          println!("User declined the request");
    ///     }
    ///     ElicitationAction::Cancel => {
    ///         println!("User cancelled/dismissed the request");
    ///     }
    ///  }
    ///  Ok(())
    /// }
    /// ```
    #[cfg(feature = "elicitation")]
    pub async fn elicit_url(
        &self,
        message: impl Into<String>,
        url: impl Into<Url>,
        elicitation_id: impl Into<String>,
    ) -> Result<ElicitationAction, ElicitationError> {
        self.elicit_url_with_timeout(message, url, elicitation_id, None)
            .await
    }

    /// Request the user to visit a URL and confirm completion.
    ///
    /// Same as `elicit_url()` but allows specifying a custom timeout for the request.
    ///
    /// # Arguments
    /// * `message` - The prompt message for the user
    /// * `url` - The URL the user is requested to visit
    /// * `elicitation_id` - A unique identifier for this elicitation request
    /// * `timeout` - Optional timeout duration. If None, uses default timeout behavior
    /// # Returns
    /// * `Ok(action)` indicating the user's response action
    /// * `Err(ElicitationError::CapabilityNotSupported)` if client does not support elicitation via URL
    /// * `Err(ElicitationError::Service(_))` if the underlying service call failed
    /// # Example
    /// ```rust,no_run
    /// # use std::time::Duration;
    /// use rmcp::*;
    /// # use rmcp::model::ElicitationAction;
    /// # use url::Url;
    ///
    /// async fn example(peer: Peer<RoleServer>) -> Result<(), Box<dyn std::error::Error>> {
    /// let elicit_result = peer.elicit_url_with_timeout("Please visit the following URL to complete the action",
    ///      Url::parse("https://example.com/complete_action")?,
    ///     "elicit_123",
    ///     Some(Duration::from_secs(30))).await?;
    ///  match elicit_result {
    ///        ElicitationAction::Accept => {
    ///        println!("User accepted and confirmed completion");
    ///     }
    ///     ElicitationAction::Decline => {
    ///          println!("User declined the request");
    ///     }
    ///     ElicitationAction::Cancel => {
    ///         println!("User cancelled/dismissed the request");
    ///     }
    ///  }
    ///  Ok(())
    /// }
    /// ```
    #[cfg(feature = "elicitation")]
    pub async fn elicit_url_with_timeout(
        &self,
        message: impl Into<String>,
        url: impl Into<Url>,
        elicitation_id: impl Into<String>,
        timeout: Option<std::time::Duration>,
    ) -> Result<ElicitationAction, ElicitationError> {
        // Check if client supports url elicitation
        if !self
            .supported_elicitation_modes()
            .contains(&ElicitationMode::Url)
        {
            return Err(ElicitationError::CapabilityNotSupported);
        }

        let action = self
            .create_elicitation_with_timeout(
                CreateElicitationRequestParams::UrlElicitationParams {
                    meta: None,
                    message: message.into(),
                    url: url.into().to_string(),
                    elicitation_id: elicitation_id.into(),
                },
                timeout,
            )
            .await?
            .action;
        Ok(action)
    }
}