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
//! Multi Round-Trip Request (MRTR) wire types (MCP 2026-07-28).
//!
//! A server processing `tools/call` / `prompts/get` / `resources/read` may
//! reply with [`InputRequiredResult`] to request additional input before
//! completing. The kind of input is the [`InputRequest`] union: elicitation
//! (first-class), plus the deprecated-on-arrival sampling and roots kinds the
//! spec re-homed here when it removed their capability-driven server->client
//! requests.
//!
//! # `requestState`: sealed, not merely signed
//!
//! MRTR is stateless -- all cross-round progress travels through the client, which
//! echoes the opaque `requestState` blob back on each retry. How that blob is
//! protected is therefore a design decision, not a detail. neva **seals** it with
//! ChaCha20-Poly1305 (AEAD) rather than **signing** it (HMAC).
//!
//! A signed state is tamper-*evident*: the client cannot alter it undetected, but
//! it can **read** it. That suffices while the state carries only what the client
//! already knows -- the answers it supplied itself. It stops sufficing the moment
//! the server puts its *own* data in there, which is precisely what
//! `Context::memo` does: a memoized value is
//! server-computed -- an upstream API response, a quoted price, a record looked up
//! under the caller's identity, a downstream token -- and it is written into the
//! state so the next round replays it instead of recomputing it. Signing alone
//! would publish every such value to the client, and to anything that logs a
//! request body in between.
//!
//! Nothing is traded away for that confidentiality: the AEAD tag authenticates the
//! payload exactly as an HMAC would, and the `v1.{kid}` header is bound in as
//! associated data so no segment can be transplanted between blobs. The payload
//! additionally carries a TTL, a binding to the originating request, and a binding
//! to the authenticated principal.
//!
//! Two practical consequences:
//! * `ctx.memo` is safe to use for values the client must not see.
//! * The shared secret set via
//!   `App::with_request_state_secret`
//!   (rotated via
//!   `App::with_request_state_keys`)
//!   upholds confidentiality, not just integrity -- treat it as a secret.
//!
//! # Side effects across rounds are the framework's problem
//!
//! Re-run + replay means a handler executes from the top on *every* round, so
//! anything with a side effect between rounds is at risk of running more than
//! once. The protocol itself says nothing about this -- it is left to each
//! implementation, and an SDK may reasonably hand the problem to the application
//! author. neva does not:
//!
//! * `Context::memo` -- compute once, replay the value on
//!   later rounds (sealed into `requestState`, hence the section above).
//! * `Context::once` -- run an effect at most once across
//!   the whole chain.
//! * `Context::on_commit` -- defer an effect until the
//!   handler actually reaches its final result, so an abandoned or failed chain
//!   never applies it.
//! * `RequestStateStore` -- close the one gap the
//!   sealed state structurally cannot: the final round mints no new state, so a
//!   lost HTTP response would otherwise re-run the handler and its commits on
//!   retry. The store caches the committed final response and replays it verbatim.
//!   It is on by default (in-process); a multi-instance deployment supplies a
//!   shared implementation.
//!
//! Together these make an MRTR handler safe to write in the obvious way -- charge
//! the card, send the receipt -- without hand-rolling idempotency keys per tool.
//! See `docs/specs/2026-05-30-mrtr-design.md` for the full design.

// The encrypted `requestState` codec is server-only: the client treats
// `requestState` as opaque and never encodes/decodes it.
#[cfg(feature = "server")]
pub(crate) mod state;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use crate::types::elicitation::ElicitRequestParams;
use crate::types::root::ListRootsRequestParams;
use crate::types::sampling::CreateMessageRequestParams;
use crate::types::{IntoResponse, RequestId, Response};

/// A result indicating the server needs more input before it can complete the
/// request. Recognized for `tools/call`, `prompts/get`, `resources/read`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InputRequiredResult {
    /// Discriminator, always `"input_required"`.
    #[serde(rename = "resultType")]
    pub result_type: InputRequiredTag,

    /// Server-assigned-key -> elicitation request the client must fulfil.
    ///
    /// `None` is **reserved** for a future async/streaming semantic where the
    /// server is making progress on its own and the client should simply retry
    /// with the echoed [`Self::request_state`] (no new inputs to gather). That
    /// path is not implemented yet; today this is always `Some(..)`. Because the
    /// field is already `Option`, adding that behavior later is non-breaking.
    #[serde(rename = "inputRequests", skip_serializing_if = "Option::is_none")]
    pub input_requests: Option<InputRequests>,

    /// Opaque, server-meaningful state the client echoes back verbatim.
    #[serde(rename = "requestState", skip_serializing_if = "Option::is_none")]
    pub request_state: Option<String>,
}

/// Map of server-assigned key -> the input request envelope the client must
/// fulfil.
pub type InputRequests = HashMap<String, InputRequest>;

/// Map of key (matching an [`InputRequests`] key) -> the client's raw result.
///
/// The value stays a [`serde_json::Value`] because the result *type* depends on
/// the kind of input that was requested ([`ElicitResult`](crate::types::elicitation::ElicitResult),
/// [`CreateMessageResult`](crate::types::sampling::CreateMessageResult),
/// [`ListRootsResult`](crate::types::root::ListRootsResult)). Each server-side
/// helper deserializes its own type out of the replay log, exactly like
/// `ctx.memo` does.
pub type InputResponses = HashMap<String, serde_json::Value>;

/// One `{ method, params }` input-request envelope -- the kind of input the
/// server is asking the client for.
///
/// The spec did not delete sampling and roots when the capability-driven
/// server->client requests went away: it re-homed them here, as MRTR input
/// request kinds, keyed by `method`. Elicitation stays first-class; the other
/// two arrive **already deprecated** (see the variant docs), matching the
/// spec's own 12-month lifecycle for roots/sampling/logging.
///
/// Intentionally *not* [`crate::types::Request`]: the wire shape is exactly
/// `{ method, params }` (the per-key id is the map key), whereas `Request`
/// has required `jsonrpc`/`id` fields -- emitting it would add non-spec fields
/// and deserializing a conformant peer's bare `{method,params}` would fail.
/// Deserialization is hand-written rather than derived (see the `impl` below):
/// the adjacent tag would make `params` mandatory, and a conforming peer may
/// omit it for a kind that needs none.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "method", content = "params")]
pub enum InputRequest {
    /// `elicitation/create` -- ask the end user for structured input.
    #[serde(rename = "elicitation/create")]
    Elicitation(ElicitRequestParams),

    /// `sampling/createMessage` -- ask the client's LLM for a completion.
    ///
    /// **Deprecated on arrival.** The ability returns re-homed onto MRTR, but
    /// it stays on the spec's deprecation path; prefer designing tools that do
    /// not need the client's model.
    #[serde(rename = "sampling/createMessage")]
    #[deprecated(
        note = "sampling is deprecated in MCP 2026-07-28; it returns as an MRTR input-request kind only for migration"
    )]
    Sampling(Box<CreateMessageRequestParams>),

    /// `roots/list` -- ask the client which filesystem roots it exposes.
    ///
    /// **Deprecated on arrival**, same as [`Self::Sampling`].
    #[serde(rename = "roots/list")]
    #[deprecated(
        note = "roots are deprecated in MCP 2026-07-28; they return as an MRTR input-request kind only for migration"
    )]
    Roots(Box<ListRootsRequestParams>),
}

impl<'de> Deserialize<'de> for InputRequest {
    /// Decodes a `{ method, params }` envelope, dispatching on `method`.
    ///
    /// `params` is optional on the wire: `roots/list` takes none, so a
    /// conforming peer may send a bare `{"method": "roots/list"}` (or an
    /// explicit `null`). An absent value is read as an empty object rather
    /// than as "use the default", so each kind's own params type still decides
    /// what is acceptable -- `roots/list` decodes (every field is optional)
    /// while a paramless `elicitation/create` or `sampling/createMessage`
    /// fails with that type's own error, as it should.
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        use crate::types::{elicitation, root, sampling};
        use serde::de::Error as DeError;

        #[derive(Deserialize)]
        struct Envelope {
            method: String,
            #[serde(default)]
            params: Option<serde_json::Value>,
        }

        let envelope = Envelope::deserialize(deserializer)?;
        let params = envelope
            .params
            .filter(|params| !params.is_null())
            .unwrap_or_else(|| serde_json::Value::Object(Default::default()));

        fn parse<T: serde::de::DeserializeOwned, E: DeError>(
            value: serde_json::Value,
        ) -> Result<T, E> {
            serde_json::from_value(value).map_err(E::custom)
        }

        #[allow(deprecated)]
        match envelope.method.as_str() {
            elicitation::commands::CREATE => parse(params).map(Self::Elicitation),
            sampling::commands::CREATE => parse(params).map(Self::Sampling),
            root::commands::LIST => parse(params).map(Self::Roots),
            unknown => Err(D::Error::custom(format!(
                "unknown MRTR input request method `{unknown}`"
            ))),
        }
    }
}

impl InputRequest {
    /// The JSON-RPC method name this envelope carries.
    pub fn method(&self) -> &'static str {
        #[allow(deprecated)]
        match self {
            Self::Elicitation(_) => crate::types::elicitation::commands::CREATE,
            Self::Sampling(_) => crate::types::sampling::commands::CREATE,
            Self::Roots(_) => crate::types::root::commands::LIST,
        }
    }
}

/// Per-request client capability flags relevant to MRTR.
///
/// The server gates each input-request kind on the matching flag: asking for an
/// input the client never declared is a server bug, and is reported as such
/// rather than stalling the round-trip.
///
/// # Wire shape
///
/// This is the `io.modelcontextprotocol/clientCapabilities` value of a request's
/// `_meta`, which the spec types as `ClientCapabilities`: each capability is an
/// **optional object** whose mere presence declares support. The flags here are
/// therefore serialized as empty objects and deserialized from any object; a
/// bare boolean is also accepted on the way in, since earlier neva clients wrote
/// one.
///
/// `elicitation` is the one capability with sub-capabilities the server acts on
/// -- see [`ElicitationModes`].
///
/// # Examples
/// ```
/// use neva::types::mrtr::ClientMrtrCapabilities;
///
/// // Spec shape: presence of the object is the declaration.
/// let caps: ClientMrtrCapabilities = serde_json::from_value(serde_json::json!({
///     "elicitation": { "form": {} },
///     "roots": {}
/// }))?;
/// let modes = caps.elicitation.expect("elicitation declared");
/// assert!(modes.form);
/// assert!(!modes.url);
/// assert!(caps.roots);
/// assert!(!caps.sampling);
///
/// assert_eq!(
///     serde_json::to_value(caps)?,
///     serde_json::json!({ "elicitation": { "form": {} }, "roots": {} })
/// );
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct ClientMrtrCapabilities {
    /// Which `elicitation/create` modes the client can fulfil, or `None` when it
    /// declared no elicitation support at all.
    #[serde(
        default,
        deserialize_with = "de_elicitation",
        skip_serializing_if = "Option::is_none"
    )]
    pub elicitation: Option<ElicitationModes>,

    /// Whether the client can fulfil `sampling/createMessage` input requests.
    ///
    /// A **deprecated** request kind -- see [`InputRequest::Sampling`].
    #[serde(
        default,
        deserialize_with = "de_declared",
        serialize_with = "ser_declared",
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub sampling: bool,

    /// Whether the client can fulfil `roots/list` input requests.
    ///
    /// A **deprecated** request kind -- see [`InputRequest::Roots`].
    #[serde(
        default,
        deserialize_with = "de_declared",
        serialize_with = "ser_declared",
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub roots: bool,
}

/// The `elicitation/create` modes a client declared it can fulfil.
///
/// The spec spells these as sub-capability objects inside `elicitation`, and
/// neither is required -- so a client may declare the capability and say nothing
/// about modes. That is what an all-`false` value means here, and it is read as
/// *unconstrained*: a client that named no modes has not ruled any out, and a
/// server that refused it would refuse every peer that spells its capabilities
/// the shortest legal way. Naming even one mode is the opposite -- it is a list
/// of what the client can do, and a mode missing from it is one the client is
/// saying it cannot answer.
///
/// # Examples
/// ```
/// use neva::types::mrtr::ElicitationModes;
///
/// let stated: ElicitationModes =
///     serde_json::from_value(serde_json::json!({ "form": {} }))?;
/// assert!(stated.form && !stated.url);
///
/// // Declared, modes unstated: nothing is ruled out.
/// let unstated: ElicitationModes = serde_json::from_value(serde_json::json!({}))?;
/// assert!(unstated.unconstrained());
/// # Ok::<(), serde_json::Error>(())
/// ```
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize)]
pub struct ElicitationModes {
    /// Whether the client stated it can answer a `form` elicitation.
    #[serde(
        default,
        deserialize_with = "de_declared",
        serialize_with = "ser_declared",
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub form: bool,

    /// Whether the client stated it can answer a `url` elicitation.
    #[serde(
        default,
        deserialize_with = "de_declared",
        serialize_with = "ser_declared",
        skip_serializing_if = "std::ops::Not::not"
    )]
    pub url: bool,
}

impl ElicitationModes {
    /// Whether the client named no mode at all, and so ruled none out.
    pub fn unconstrained(&self) -> bool {
        !self.form && !self.url
    }

    /// Whether `params` asks for a mode this client can answer.
    pub fn allows(&self, params: &crate::types::elicitation::ElicitRequestParams) -> bool {
        use crate::types::elicitation::ElicitRequestParams;
        self.unconstrained()
            || match params {
                ElicitRequestParams::Form(_) => self.form,
                ElicitRequestParams::Url(_) => self.url,
            }
    }
}

// Only a server tells a client what it should have declared.
#[cfg(feature = "server")]
impl ElicitationModes {
    /// The modes required to answer `params`, as the declaration a client would
    /// have had to send.
    fn requiring(params: &crate::types::elicitation::ElicitRequestParams) -> Self {
        use crate::types::elicitation::ElicitRequestParams;
        match params {
            ElicitRequestParams::Form(_) => Self {
                form: true,
                url: false,
            },
            ElicitRequestParams::Url(_) => Self {
                form: false,
                url: true,
            },
        }
    }
}

/// How the `elicitation` capability may be spelled: the spec's object, whose
/// contents are the modes, or the boolean older neva clients wrote.
#[derive(Deserialize)]
#[serde(untagged)]
enum ElicitationDeclaration {
    Modes(ElicitationModes),
    Flag(bool),
}

/// Reads `elicitation` into the modes it declares, `None` when it declares
/// nothing. A bare `true` becomes a declaration that names no mode -- which is
/// what it always meant.
fn de_elicitation<'de, D>(deserializer: D) -> Result<Option<ElicitationModes>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(
        match Option::<ElicitationDeclaration>::deserialize(deserializer)? {
            Some(ElicitationDeclaration::Modes(modes)) => Some(modes),
            Some(ElicitationDeclaration::Flag(true)) => Some(ElicitationModes::default()),
            Some(ElicitationDeclaration::Flag(false)) | None => None,
        },
    )
}

/// How a single capability may be spelled inside
/// `io.modelcontextprotocol/clientCapabilities`.
#[derive(Deserialize)]
#[serde(untagged)]
enum Declaration {
    /// The spec shape: an object, possibly carrying sub-capabilities. Present
    /// means supported, whatever it contains.
    Object(AnyObject),
    /// What neva's own client wrote before it followed the spec shape.
    Flag(bool),
}

/// Any JSON object, whatever it holds -- the spec declares a capability by the
/// presence of its object, not by anything inside it. Sub-capabilities are
/// accepted and ignored (serde skips unknown fields of a fieldless struct).
#[derive(Deserialize)]
struct AnyObject {}

/// Reads a capability that the spec spells as an optional object, tolerating the
/// boolean older neva clients sent.
fn de_declared<'de, D>(deserializer: D) -> Result<bool, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(match Option::<Declaration>::deserialize(deserializer)? {
        Some(Declaration::Object(_)) => true,
        Some(Declaration::Flag(flag)) => flag,
        None => false,
    })
}

/// Writes a declared capability in the spec shape: an empty object. Only ever
/// called for a `true` flag -- a `false` one is skipped, which is how the spec
/// spells "not supported".
fn ser_declared<S>(_declared: &bool, serializer: S) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use serde::ser::SerializeMap;
    serializer.serialize_map(Some(0))?.end()
}

#[cfg(feature = "server")]
impl ClientMrtrCapabilities {
    /// Whether the client declared support for the kind `request` asks for.
    ///
    /// An elicitation is judged by its mode as well: a client that named `form`
    /// and nothing else has said it cannot answer a `url` request, and sending
    /// one anyway stalls the round rather than being refused where the server
    /// can still do something about it.
    pub(crate) fn allows(&self, request: &InputRequest) -> bool {
        #[allow(deprecated)]
        match request {
            InputRequest::Elicitation(params) => {
                self.elicitation.is_some_and(|modes| modes.allows(params))
            }
            InputRequest::Sampling(_) => self.sampling,
            InputRequest::Roots(_) => self.roots,
        }
    }

    /// The capability set the server needs for `request`, as the
    /// `requiredCapabilities` payload of a
    /// [`MissingRequiredClientCapability`](crate::error::ErrorCode::MissingRequiredClientCapability)
    /// error -- so the client is told what to declare, not just that something
    /// was missing.
    pub(crate) fn requiring(&self, request: &InputRequest) -> Self {
        #[allow(deprecated)]
        Self {
            // Named down to the mode, so a client told what to declare is told
            // the whole of it -- "elicitation" alone would send it back with
            // the same declaration it already had.
            elicitation: match request {
                InputRequest::Elicitation(params) => Some(ElicitationModes::requiring(params)),
                _ => None,
            },
            sampling: matches!(request, InputRequest::Sampling(_)),
            roots: matches!(request, InputRequest::Roots(_)),
        }
    }
}

/// Unit tag serializing as the constant string `"input_required"`.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum InputRequiredTag {
    /// The only variant.
    #[serde(rename = "input_required")]
    InputRequired,
}

// Server-only: only the server constructs `InputRequiredResult`; the client
// deserializes it from the wire.
#[cfg(feature = "server")]
impl InputRequiredResult {
    /// Builds an `InputRequiredResult` asking for `requests`, of any kinds.
    ///
    /// `inputRequests` is a map rather than a single request precisely so a
    /// round can ask for everything it needs at once: a handler that needs a
    /// name, a completion and the caller's roots costs one round-trip, not
    /// three.
    pub(crate) fn new(
        requests: impl IntoIterator<Item = (String, InputRequest)>,
        state: String,
    ) -> Self {
        Self {
            result_type: InputRequiredTag::InputRequired,
            input_requests: Some(requests.into_iter().collect()),
            request_state: Some(state),
        }
    }
}

impl IntoResponse for InputRequiredResult {
    #[inline]
    fn into_response(self, req_id: RequestId) -> Response {
        match serde_json::to_value(self) {
            Ok(v) => Response::success(req_id, v),
            Err(err) => Response::error(req_id, err.into()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn client_capabilities_read_the_spec_object_shape() {
        // What a spec-conformant client (e.g. MCP Inspector) puts in `_meta`:
        // every capability is an object, sub-capabilities and all.
        let caps: ClientMrtrCapabilities = serde_json::from_value(serde_json::json!({
            "elicitation": { "form": {}, "url": {} },
            "sampling": { "context": {}, "tools": {} },
            "roots": {}
        }))
        .expect("object-shaped capabilities must parse");

        let modes = caps.elicitation.expect("elicitation declared");
        assert!(modes.form && modes.url, "both modes were named");
        assert!(caps.sampling);
        assert!(caps.roots);
    }

    #[test]
    fn client_capabilities_read_the_legacy_boolean_shape() {
        let caps: ClientMrtrCapabilities = serde_json::from_value(serde_json::json!({
            "elicitation": true,
            "sampling": false
        }))
        .expect("boolean-shaped capabilities must still parse");

        let modes = caps.elicitation.expect("elicitation declared");
        assert!(
            modes.unconstrained(),
            "a bare boolean names no mode, and so rules none out"
        );
        assert!(!caps.sampling);
        assert!(!caps.roots);
    }

    #[test]
    fn absent_and_null_client_capabilities_declare_nothing() {
        let empty: ClientMrtrCapabilities =
            serde_json::from_value(serde_json::json!({})).expect("empty object must parse");
        assert!(empty.elicitation.is_none() && !empty.sampling && !empty.roots);

        let nulls: ClientMrtrCapabilities =
            serde_json::from_value(serde_json::json!({ "elicitation": null, "roots": null }))
                .expect("null capabilities must parse");
        assert!(nulls.elicitation.is_none() && !nulls.roots);
    }

    #[test]
    fn client_capabilities_write_the_spec_object_shape() {
        let caps = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes::default()),
            sampling: false,
            roots: true,
        };

        assert_eq!(
            serde_json::to_value(caps).expect("serialize"),
            serde_json::json!({ "elicitation": {}, "roots": {} }),
            "a capability declared without modes writes the bare object"
        );

        let formal = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes {
                form: true,
                url: false,
            }),
            sampling: false,
            roots: false,
        };
        assert_eq!(
            serde_json::to_value(formal).expect("serialize"),
            serde_json::json!({ "elicitation": { "form": {} } }),
            "a named mode survives the round trip to the wire"
        );
    }

    #[test]
    fn client_capabilities_roundtrip() {
        let caps = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes {
                form: true,
                url: true,
            }),
            sampling: true,
            roots: false,
        };
        let back: ClientMrtrCapabilities =
            serde_json::from_value(serde_json::to_value(caps).expect("serialize"))
                .expect("deserialize");

        let modes = back.elicitation.expect("elicitation declared");
        assert!(modes.form && modes.url);
        assert!(back.sampling);
        assert!(!back.roots);
    }

    #[test]
    fn input_required_result_roundtrips_with_tag_and_envelope() {
        // The elicitation params sit flat in `params`, the way the spec's
        // `ElicitRequestFormParams | ElicitRequestURLParams` union spells them
        // -- no variant name wraps them, and a form omits `mode` entirely.
        let json = r#"{
            "resultType": "input_required",
            "inputRequests": {
                "ask_name": {
                    "method": "elicitation/create",
                    "params": {
                        "message": "Your name?",
                        "requestedSchema": { "type": "object", "properties": {}, "required": null }
                    }
                }
            },
            "requestState": "abc.def"
        }"#;
        let parsed: InputRequiredResult = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.request_state.as_deref(), Some("abc.def"));
        assert!(
            parsed
                .input_requests
                .as_ref()
                .expect("requests")
                .contains_key("ask_name")
        );
        let back = serde_json::to_value(&parsed).unwrap();
        assert_eq!(back["resultType"], serde_json::json!("input_required"));
        assert_eq!(
            back["inputRequests"]["ask_name"]["method"],
            serde_json::json!("elicitation/create")
        );
        // Round-tripped flat, and with no `mode: null` invented on the way out.
        let params = &back["inputRequests"]["ask_name"]["params"];
        assert_eq!(params["message"], serde_json::json!("Your name?"));
        assert!(params.get("Form").is_none(), "got: {params}");
        assert!(params.get("mode").is_none(), "got: {params}");
    }

    /// The union must keep the flat `{ method, params }` envelope for every
    /// kind -- the `method` is the discriminator, not a nested tag.
    #[test]
    fn every_input_kind_roundtrips_as_a_method_params_envelope() {
        #[allow(deprecated)]
        let cases = [
            (
                InputRequest::Elicitation(ElicitRequestParams::form("Your name?").into()),
                "elicitation/create",
            ),
            (
                InputRequest::Sampling(Box::default()),
                "sampling/createMessage",
            ),
            (InputRequest::Roots(Box::default()), "roots/list"),
        ];

        for (request, method) in cases {
            assert_eq!(request.method(), method);

            let json = serde_json::to_value(&request).unwrap();
            assert_eq!(json["method"], serde_json::json!(method));
            assert!(
                json.get("params").is_some(),
                "the envelope must carry `params` for {method}: {json}"
            );

            let back: InputRequest = serde_json::from_value(json).unwrap();
            assert_eq!(back.method(), method, "kind must survive the round trip");
        }
    }

    /// A peer's `roots/list` envelope may omit `params` entirely; the
    /// params type is all-optional, so it must still decode.
    #[test]
    fn a_roots_envelope_decodes_with_or_without_params() {
        for json in [
            serde_json::json!({ "method": "roots/list", "params": {} }),
            // A conforming peer may omit the empty object entirely.
            serde_json::json!({ "method": "roots/list" }),
            serde_json::json!({ "method": "roots/list", "params": null }),
        ] {
            let parsed: InputRequest = serde_json::from_value(json.clone())
                .unwrap_or_else(|err| panic!("{json} must decode: {err}"));
            assert_eq!(parsed.method(), "roots/list");
        }
    }

    /// Absent params is *not* a blanket "use the default": a kind whose params
    /// carry required fields still fails, with its own error.
    #[test]
    fn a_paramless_envelope_still_fails_for_kinds_that_need_params() {
        for method in ["elicitation/create", "sampling/createMessage"] {
            let json = serde_json::json!({ "method": method });
            assert!(
                serde_json::from_value::<InputRequest>(json).is_err(),
                "{method} must not decode without params"
            );
        }
    }

    #[test]
    fn an_unknown_input_kind_is_rejected_by_name() {
        let json = serde_json::json!({ "method": "sorcery/summon", "params": {} });
        let err = serde_json::from_value::<InputRequest>(json).unwrap_err();
        assert!(
            err.to_string().contains("sorcery/summon"),
            "the error must name the unknown method, got: {err}"
        );
    }

    // `allows` is the server's gate, so it only exists in server builds.
    #[cfg(feature = "server")]
    #[test]
    fn capabilities_gate_each_kind_independently() {
        #[allow(deprecated)]
        let sampling = InputRequest::Sampling(Box::default());
        let elicitation = InputRequest::Elicitation(ElicitRequestParams::form("m").into());

        let only_elicitation = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes::default()),
            ..Default::default()
        };
        assert!(only_elicitation.allows(&elicitation));
        assert!(
            !only_elicitation.allows(&sampling),
            "a client that only does elicitation must not be asked to sample"
        );

        let all = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes::default()),
            sampling: true,
            roots: true,
        };
        assert!(all.allows(&sampling));
    }

    /// A declared mode is a list of what the client can answer, so a request in
    /// a mode missing from it is refused where the server can still act on it --
    /// rather than sent out to a client with no way to answer, which stalls the
    /// round until it times out.
    #[cfg(feature = "server")]
    #[test]
    fn a_named_elicitation_mode_is_the_only_one_allowed() {
        let form = InputRequest::Elicitation(ElicitRequestParams::form("m").into());
        let url = InputRequest::Elicitation(ElicitRequestParams::url("m", "https://e.io").into());

        let forms_only = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes {
                form: true,
                url: false,
            }),
            ..Default::default()
        };
        assert!(forms_only.allows(&form));
        assert!(
            !forms_only.allows(&url),
            "a client that named only `form` cannot answer a URL request"
        );

        // Naming nothing rules nothing out -- the shortest legal way to declare
        // the capability, and the shape neva's own client writes.
        let unstated = ClientMrtrCapabilities {
            elicitation: Some(ElicitationModes::default()),
            ..Default::default()
        };
        assert!(unstated.allows(&form) && unstated.allows(&url));

        // And what the client is told to declare names the mode, not just the
        // capability it already had.
        let required = forms_only.requiring(&url).elicitation.expect("named");
        assert!(required.url && !required.form);
    }

    /// The flags are additive on the wire: a peer that predates
    /// sampling/roots sends only `elicitation`, and the absent flags must
    /// decode as "not supported" rather than failing.
    #[test]
    fn capabilities_decode_from_an_older_peer() {
        let caps: ClientMrtrCapabilities =
            serde_json::from_value(serde_json::json!({ "elicitation": true })).unwrap();
        assert!(caps.elicitation.is_some());
        assert!(!caps.sampling);
        assert!(!caps.roots);

        // ...and a default set serializes to nothing at all.
        let json = serde_json::to_value(ClientMrtrCapabilities::default()).unwrap();
        assert_eq!(json, serde_json::json!({}));
    }
}