rmcp 1.5.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
use std::collections::BTreeMap;
#[cfg(any(feature = "server", feature = "macros"))]
use std::marker::PhantomData;

#[cfg(any(feature = "server", feature = "macros"))]
use pastey::paste;
use serde::{Deserialize, Serialize};

use super::JsonObject;
pub type ExperimentalCapabilities = BTreeMap<String, JsonObject>;

/// MCP extension capabilities map.
///
/// Keys are extension identifiers in the format `{vendor-prefix}/{extension-name}`
/// (e.g., `io.modelcontextprotocol/ui`, `io.modelcontextprotocol/oauth-client-credentials`).
/// Values are per-extension settings objects. An empty object indicates support with no settings.
///
/// # Example
///
/// ```rust
/// use rmcp::model::ExtensionCapabilities;
/// use serde_json::json;
///
/// let mut extensions = ExtensionCapabilities::new();
/// extensions.insert(
///     "io.modelcontextprotocol/ui".to_string(),
///     serde_json::from_value(json!({
///         "mimeTypes": ["text/html;profile=mcp-app"]
///     })).unwrap()
/// );
/// ```
pub type ExtensionCapabilities = BTreeMap<String, JsonObject>;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct PromptsCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct ResourcesCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscribe: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct ToolsCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct RootsCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

/// Task capabilities shared by client and server.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct TasksCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requests: Option<TaskRequestsCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list: Option<JsonObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel: Option<JsonObject>,
}

/// Request types that support task-augmented execution.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct TaskRequestsCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<SamplingTaskCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elicitation: Option<ElicitationTaskCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsTaskCapability>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct SamplingTaskCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_message: Option<JsonObject>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct ElicitationTaskCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create: Option<JsonObject>,
}

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct ToolsTaskCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call: Option<JsonObject>,
}

impl TasksCapability {
    /// Default client tasks capability with sampling and elicitation support.
    pub fn client_default() -> Self {
        Self {
            list: Some(JsonObject::new()),
            cancel: Some(JsonObject::new()),
            requests: Some(TaskRequestsCapability {
                sampling: Some(SamplingTaskCapability {
                    create_message: Some(JsonObject::new()),
                }),
                elicitation: Some(ElicitationTaskCapability {
                    create: Some(JsonObject::new()),
                }),
                tools: None,
            }),
        }
    }

    /// Default server tasks capability with tools/call support.
    pub fn server_default() -> Self {
        Self {
            list: Some(JsonObject::new()),
            cancel: Some(JsonObject::new()),
            requests: Some(TaskRequestsCapability {
                sampling: None,
                elicitation: None,
                tools: Some(ToolsTaskCapability {
                    call: Some(JsonObject::new()),
                }),
            }),
        }
    }

    pub fn supports_list(&self) -> bool {
        self.list.is_some()
    }

    pub fn supports_cancel(&self) -> bool {
        self.cancel.is_some()
    }

    pub fn supports_tools_call(&self) -> bool {
        self.requests
            .as_ref()
            .and_then(|r| r.tools.as_ref())
            .and_then(|t| t.call.as_ref())
            .is_some()
    }

    pub fn supports_sampling_create_message(&self) -> bool {
        self.requests
            .as_ref()
            .and_then(|r| r.sampling.as_ref())
            .and_then(|s| s.create_message.as_ref())
            .is_some()
    }

    pub fn supports_elicitation_create(&self) -> bool {
        self.requests
            .as_ref()
            .and_then(|r| r.elicitation.as_ref())
            .and_then(|e| e.create.as_ref())
            .is_some()
    }
}

/// Capability for handling elicitation requests from servers.
/// Elicitation allows servers to request interactive input from users during tool execution.
/// This capability indicates that a client can handle elicitation requests and present
/// appropriate UI to users for collecting the requested information.
///
/// Capability for form mode elicitation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct FormElicitationCapability {
    /// Whether the client supports JSON Schema validation for elicitation responses.
    /// When true, the client will validate user input against the requested_schema
    /// before sending the response back to the server.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema_validation: Option<bool>,
}

/// Capability for URL mode elicitation.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct UrlElicitationCapability {}

/// Elicitation allows servers to request interactive input from users during tool execution.
/// This capability indicates that a client can handle elicitation requests and present
/// appropriate UI to users for collecting the requested information.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct ElicitationCapability {
    /// Whether client supports form-based elicitation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub form: Option<FormElicitationCapability>,
    /// Whether client supports URL-based elicitation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<UrlElicitationCapability>,
}

/// Sampling capability with optional sub-capabilities (SEP-1577).
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
pub struct SamplingCapability {
    /// Support for `tools` and `toolChoice` parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<JsonObject>,
    /// Support for `includeContext` (soft-deprecated)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<JsonObject>,
}

///
/// # Builder
/// ```rust
/// # use rmcp::model::ClientCapabilities;
/// let cap = ClientCapabilities::builder()
///     .enable_experimental()
///     .enable_roots()
///     .enable_roots_list_changed()
///     .build();
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct ClientCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experimental: Option<ExperimentalCapabilities>,
    /// Optional MCP extensions that the client supports (SEP-1724).
    /// Keys are extension identifiers (e.g., `"io.modelcontextprotocol/ui"`),
    /// values are per-extension settings objects. An empty object indicates
    /// support with no settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<ExtensionCapabilities>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub roots: Option<RootsCapabilities>,
    /// Capability for LLM sampling requests (SEP-1577)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<SamplingCapability>,
    /// Capability to handle elicitation requests from servers for interactive user input
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elicitation: Option<ElicitationCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tasks: Option<TasksCapability>,
}

///
/// ## Builder
/// ```rust
/// # use rmcp::model::ServerCapabilities;
/// let cap = ServerCapabilities::builder()
///     .enable_logging()
///     .enable_experimental()
///     .enable_prompts()
///     .enable_resources()
///     .enable_tools()
///     .enable_tool_list_changed()
///     .build();
/// ```
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct ServerCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experimental: Option<ExperimentalCapabilities>,
    /// Optional MCP extensions that the server supports (SEP-1724).
    /// Keys are extension identifiers (e.g., `"io.modelcontextprotocol/apps"`),
    /// values are per-extension settings objects. An empty object indicates
    /// support with no settings.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub extensions: Option<ExtensionCapabilities>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logging: Option<JsonObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completions: Option<JsonObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompts: Option<PromptsCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourcesCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tasks: Option<TasksCapability>,
}

#[cfg(any(feature = "server", feature = "macros"))]
macro_rules! builder {
    ($Target: ident {$($f: ident: $T: ty),* $(,)?}) => {
        paste! {
            #[derive(Default, Clone, Copy, Debug)]
            #[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
            pub struct [<$Target BuilderState>]<
                $(const [<$f:upper>]: bool = false,)*
            >;
            #[derive(Debug, Default)]
            #[expect(clippy::exhaustive_structs, reason = "intentionally exhaustive")]
            pub struct [<$Target Builder>]<S = [<$Target BuilderState>]> {
                $(pub $f: Option<$T>,)*
                pub state: PhantomData<S>
            }
            impl $Target {
                #[doc = "Create a new [`" $Target "`] builder."]
                pub fn builder() -> [<$Target Builder>] {
                    <[<$Target Builder>]>::default()
                }
            }
            impl<S> [<$Target Builder>]<S> {
                pub fn build(self) -> $Target {
                    $Target {
                        $( $f: self.$f, )*
                    }
                }
            }
            impl<S> From<[<$Target Builder>]<S>> for $Target {
                fn from(builder: [<$Target Builder>]<S>) -> Self {
                    builder.build()
                }
            }
        }
        builder!($Target @toggle $($f: $T,) *);

    };
    ($Target: ident @toggle $f0: ident: $T0: ty, $($f: ident: $T: ty,)*) => {
        builder!($Target @toggle [][$f0: $T0][$($f: $T,)*]);
    };
    ($Target: ident @toggle [$($ff: ident: $Tf: ty,)*][$fn: ident: $TN: ty][$fn_1: ident: $Tn_1: ty, $($ft: ident: $Tt: ty,)*]) => {
        builder!($Target @impl_toggle [$($ff: $Tf,)*][$fn: $TN][$fn_1: $Tn_1, $($ft:$Tt,)*]);
        builder!($Target @toggle [$($ff: $Tf,)* $fn: $TN,][$fn_1: $Tn_1][$($ft:$Tt,)*]);
    };
    ($Target: ident @toggle [$($ff: ident: $Tf: ty,)*][$fn: ident: $TN: ty][]) => {
        builder!($Target @impl_toggle [$($ff: $Tf,)*][$fn: $TN][]);
    };
    ($Target: ident @impl_toggle [$($ff: ident: $Tf: ty,)*][$fn: ident: $TN: ty][$($ft: ident: $Tt: ty,)*]) => {
        paste! {
            impl<
                $(const [<$ff:upper>]: bool,)*
                $(const [<$ft:upper>]: bool,)*
            > [<$Target Builder>]<[<$Target BuilderState>]<
                $([<$ff:upper>],)*
                false,
                $([<$ft:upper>],)*
            >> {
                pub fn [<enable_ $fn>](self) -> [<$Target Builder>]<[<$Target BuilderState>]<
                    $([<$ff:upper>],)*
                    true,
                    $([<$ft:upper>],)*
                >> {
                    [<$Target Builder>] {
                        $( $ff: self.$ff, )*
                        $fn: Some($TN::default()),
                        $( $ft: self.$ft, )*
                        state: PhantomData
                    }
                }
                pub fn [<enable_ $fn _with>](self, $fn: $TN) -> [<$Target Builder>]<[<$Target BuilderState>]<
                    $([<$ff:upper>],)*
                    true,
                    $([<$ft:upper>],)*
                >> {
                    [<$Target Builder>] {
                        $( $ff: self.$ff, )*
                        $fn: Some($fn),
                        $( $ft: self.$ft, )*
                        state: PhantomData
                    }
                }
            }
            // do we really need to disable some thing in builder?
            // impl<
            //     $(const [<$ff:upper>]: bool,)*
            //     $(const [<$ft:upper>]: bool,)*
            // > [<$Target Builder>]<[<$Target BuilderState>]<
            //     $([<$ff:upper>],)*
            //     true,
            //     $([<$ft:upper>],)*
            // >> {
            //     pub fn [<disable_ $fn>](self) -> [<$Target Builder>]<[<$Target BuilderState>]<
            //         $([<$ff:upper>],)*
            //         false,
            //         $([<$ft:upper>],)*
            //     >> {
            //         [<$Target Builder>] {
            //             $( $ff: self.$ff, )*
            //             $fn: None,
            //             $( $ft: self.$ft, )*
            //             state: PhantomData
            //         }
            //     }
            // }
        }
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
builder! {
    ServerCapabilities {
        experimental: ExperimentalCapabilities,
        extensions: ExtensionCapabilities,
        logging: JsonObject,
        completions: JsonObject,
        prompts: PromptsCapability,
        resources: ResourcesCapability,
        tools: ToolsCapability,
        tasks: TasksCapability
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
impl<
    const E: bool,
    const EXT: bool,
    const L: bool,
    const C: bool,
    const P: bool,
    const R: bool,
    const TASKS: bool,
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, R, true, TASKS>>
{
    pub fn enable_tool_list_changed(mut self) -> Self {
        if let Some(c) = self.tools.as_mut() {
            c.list_changed = Some(true);
        }
        self
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
impl<
    const E: bool,
    const EXT: bool,
    const L: bool,
    const C: bool,
    const R: bool,
    const T: bool,
    const TASKS: bool,
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, true, R, T, TASKS>>
{
    pub fn enable_prompts_list_changed(mut self) -> Self {
        if let Some(c) = self.prompts.as_mut() {
            c.list_changed = Some(true);
        }
        self
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
impl<
    const E: bool,
    const EXT: bool,
    const L: bool,
    const C: bool,
    const P: bool,
    const T: bool,
    const TASKS: bool,
> ServerCapabilitiesBuilder<ServerCapabilitiesBuilderState<E, EXT, L, C, P, true, T, TASKS>>
{
    pub fn enable_resources_list_changed(mut self) -> Self {
        if let Some(c) = self.resources.as_mut() {
            c.list_changed = Some(true);
        }
        self
    }

    pub fn enable_resources_subscribe(mut self) -> Self {
        if let Some(c) = self.resources.as_mut() {
            c.subscribe = Some(true);
        }
        self
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
builder! {
    ClientCapabilities{
        experimental: ExperimentalCapabilities,
        extensions: ExtensionCapabilities,
        roots: RootsCapabilities,
        sampling: SamplingCapability,
        elicitation: ElicitationCapability,
        tasks: TasksCapability,
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
impl<const E: bool, const EXT: bool, const S: bool, const EL: bool, const TASKS: bool>
    ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, true, S, EL, TASKS>>
{
    pub fn enable_roots_list_changed(mut self) -> Self {
        if let Some(c) = self.roots.as_mut() {
            c.list_changed = Some(true);
        }
        self
    }
}

#[cfg(any(feature = "server", feature = "macros"))]
impl<const E: bool, const EXT: bool, const R: bool, const EL: bool, const TASKS: bool>
    ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, true, EL, TASKS>>
{
    /// Enable tool calling in sampling requests
    pub fn enable_sampling_tools(mut self) -> Self {
        if let Some(c) = self.sampling.as_mut() {
            c.tools = Some(JsonObject::default());
        }
        self
    }

    /// Enable context inclusion in sampling (soft-deprecated)
    pub fn enable_sampling_context(mut self) -> Self {
        if let Some(c) = self.sampling.as_mut() {
            c.context = Some(JsonObject::default());
        }
        self
    }
}

#[cfg(all(feature = "elicitation", any(feature = "server", feature = "macros")))]
impl<const E: bool, const EXT: bool, const R: bool, const S: bool, const TASKS: bool>
    ClientCapabilitiesBuilder<ClientCapabilitiesBuilderState<E, EXT, R, S, true, TASKS>>
{
    /// Enable JSON Schema validation for elicitation responses in form mode.
    /// When enabled, the client will validate user input against the requested_schema
    /// before sending responses back to the server.
    pub fn enable_elicitation_schema_validation(mut self) -> Self {
        if let Some(c) = self.elicitation.as_mut() {
            c.form = Some(FormElicitationCapability {
                schema_validation: Some(true),
            });
        }
        self
    }
}

#[cfg(test)]
#[cfg(any(feature = "server", feature = "macros"))]
mod test {
    use super::*;
    #[test]
    fn test_builder() {
        let builder = <ServerCapabilitiesBuilder>::default()
            .enable_logging()
            .enable_experimental()
            .enable_prompts()
            .enable_resources()
            .enable_tools()
            .enable_tool_list_changed();
        assert_eq!(builder.logging, Some(JsonObject::default()));
        assert_eq!(builder.prompts, Some(PromptsCapability::default()));
        assert_eq!(builder.resources, Some(ResourcesCapability::default()));
        assert_eq!(
            builder.tools,
            Some(ToolsCapability {
                list_changed: Some(true),
            })
        );
        assert_eq!(
            builder.experimental,
            Some(ExperimentalCapabilities::default())
        );
        let client_builder = <ClientCapabilitiesBuilder>::default()
            .enable_experimental()
            .enable_roots()
            .enable_roots_list_changed()
            .enable_sampling();
        assert_eq!(
            client_builder.experimental,
            Some(ExperimentalCapabilities::default())
        );
        assert_eq!(
            client_builder.roots,
            Some(RootsCapabilities {
                list_changed: Some(true),
            })
        );
    }

    #[test]
    fn test_task_capabilities_deserialization() {
        // Test deserializing from the MCP spec format
        let json = serde_json::json!({
            "list": {},
            "cancel": {},
            "requests": {
                "tools": { "call": {} }
            }
        });

        let tasks: TasksCapability = serde_json::from_value(json).unwrap();
        assert!(tasks.list.is_some());
        assert!(tasks.cancel.is_some());
        assert!(tasks.requests.is_some());
        let requests = tasks.requests.unwrap();
        assert!(requests.tools.is_some());
        assert!(requests.tools.unwrap().call.is_some());
    }

    #[test]
    fn test_tasks_capability_client_default() {
        let tasks = TasksCapability::client_default();

        // Verify structure
        assert!(tasks.supports_list());
        assert!(tasks.supports_cancel());
        assert!(tasks.supports_sampling_create_message());
        assert!(tasks.supports_elicitation_create());
        assert!(!tasks.supports_tools_call());

        // Verify serialization matches expected format
        let json = serde_json::to_value(&tasks).unwrap();
        assert_eq!(json["list"], serde_json::json!({}));
        assert_eq!(json["cancel"], serde_json::json!({}));
        assert_eq!(
            json["requests"]["sampling"]["createMessage"],
            serde_json::json!({})
        );
        assert_eq!(
            json["requests"]["elicitation"]["create"],
            serde_json::json!({})
        );
    }

    #[test]
    fn test_tasks_capability_server_default() {
        let tasks = TasksCapability::server_default();

        // Verify structure
        assert!(tasks.supports_list());
        assert!(tasks.supports_cancel());
        assert!(tasks.supports_tools_call());
        assert!(!tasks.supports_sampling_create_message());
        assert!(!tasks.supports_elicitation_create());

        // Verify serialization matches expected format
        let json = serde_json::to_value(&tasks).unwrap();
        assert_eq!(json["list"], serde_json::json!({}));
        assert_eq!(json["cancel"], serde_json::json!({}));
        assert_eq!(json["requests"]["tools"]["call"], serde_json::json!({}));
    }

    #[test]
    fn test_client_extensions_capability() {
        // Test building ClientCapabilities with extensions (MCP Apps support)
        let mut extensions = ExtensionCapabilities::new();
        extensions.insert(
            "io.modelcontextprotocol/ui".to_string(),
            serde_json::from_value(serde_json::json!({
                "mimeTypes": ["text/html;profile=mcp-app"]
            }))
            .unwrap(),
        );

        let capabilities = ClientCapabilities::builder()
            .enable_extensions_with(extensions)
            .enable_sampling()
            .build();

        // Verify serialization matches MCP Apps spec format
        let json = serde_json::to_value(&capabilities).unwrap();
        assert_eq!(
            json["extensions"]["io.modelcontextprotocol/ui"]["mimeTypes"],
            serde_json::json!(["text/html;profile=mcp-app"])
        );
        assert!(json["sampling"].is_object());
    }

    #[test]
    fn test_server_extensions_capability() {
        // Test building ServerCapabilities with extensions
        let mut extensions = ExtensionCapabilities::new();
        extensions.insert(
            "io.modelcontextprotocol/apps".to_string(),
            serde_json::from_value(serde_json::json!({})).unwrap(),
        );

        let capabilities = ServerCapabilities::builder()
            .enable_extensions_with(extensions)
            .enable_tools()
            .build();

        // Verify serialization
        let json = serde_json::to_value(&capabilities).unwrap();
        assert!(json["extensions"]["io.modelcontextprotocol/apps"].is_object());
        assert!(json["tools"].is_object());
    }

    #[test]
    fn test_extensions_deserialization() {
        // Test deserializing capabilities with extensions from JSON
        let json = serde_json::json!({
            "extensions": {
                "io.modelcontextprotocol/ui": {
                    "mimeTypes": ["text/html;profile=mcp-app"]
                }
            },
            "sampling": {}
        });

        let capabilities: ClientCapabilities = serde_json::from_value(json).unwrap();
        assert!(capabilities.extensions.is_some());
        let extensions = capabilities.extensions.unwrap();
        assert!(extensions.contains_key("io.modelcontextprotocol/ui"));
        let ui_ext = extensions.get("io.modelcontextprotocol/ui").unwrap();
        assert!(ui_ext.contains_key("mimeTypes"));
    }

    #[test]
    fn test_extensions_empty_settings() {
        // Test that empty extension settings work (indicates support with no settings)
        let mut extensions = ExtensionCapabilities::new();
        extensions.insert(
            "io.modelcontextprotocol/oauth-client-credentials".to_string(),
            JsonObject::new(),
        );

        let capabilities = ClientCapabilities::builder()
            .enable_extensions_with(extensions)
            .build();

        let json = serde_json::to_value(&capabilities).unwrap();
        assert_eq!(
            json["extensions"]["io.modelcontextprotocol/oauth-client-credentials"],
            serde_json::json!({})
        );
    }
}