1#![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(¬ification.params),
50 _ => None,
51 }
52 }
53
54 fn enforce_outbound_request(peer: &Peer<Self>) -> Result<(), ServiceError> {
55 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#[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#[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#[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 pub fn id(&self) -> &RequestId {
156 &self.id
157 }
158
159 pub fn accepted(&self) -> &SubscriptionFilter {
161 self.accepted.as_ref()
162 }
163
164 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 ¬ification {
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 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 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 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 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 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#[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 pub fn requested(&self) -> &SubscriptionFilter {
372 &self.requested
373 }
374
375 pub fn accepted(&self) -> &SubscriptionFilter {
377 self.accepted.as_ref()
378 }
379
380 pub fn sink(&self) -> &SubscriptionSink {
382 &self.sink
383 }
384
385 pub async fn cancelled(&self) {
387 self.request.ct.cancelled().await;
388 }
389
390 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
424async 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
456pub(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 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
511fn 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
530async 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 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 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 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 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 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 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 ($(#[$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 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 #[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 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 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 #[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 peer_req create_elicitation ElicitRequest(ElicitRequestParams) => ElicitResult
938 );
939 #[cfg(feature = "elicitation")]
940 method!(
941 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#[cfg(feature = "elicitation")]
968#[derive(Error, Debug)]
969#[non_exhaustive]
970pub enum ElicitationError {
971 #[error("Service error: {0}")]
973 Service(#[from] ServiceError),
974
975 #[error("User explicitly declined the request")]
979 UserDeclined,
980
981 #[error("User cancelled/dismissed the request")]
985 UserCancelled,
986
987 #[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 #[error("No response content provided")]
996 NoContent,
997
998 #[error("Client does not support elicitation - capability not declared during initialization")]
1000 CapabilityNotSupported,
1001}
1002
1003#[cfg(feature = "elicitation")]
1021pub trait ElicitationSafe: schemars::JsonSchema {}
1022
1023#[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 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 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 #[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 #[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 RoleServer::enforce_outbound_request(self)?;
1250
1251 if !self
1253 .supported_elicitation_modes()
1254 .contains(&ElicitationMode::Form)
1255 {
1256 return Err(ElicitationError::CapabilityNotSupported);
1257 }
1258
1259 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 #[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 #[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 RoleServer::enforce_outbound_request(self)?;
1405
1406 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}