flymcprust-core 0.1.1

Runtime and transports of FlyMCPRust, a high-performance MCP server SDK for Rust. Use the `flymcprust` crate.
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
//! Multi round-trip requests (MRTR): handlers ask the client for input
//! (elicitation, sampling, roots) by returning an `InputRequiredResult`; the
//! client retries the original request with the answers.
//!
//! The SDK runs handlers in *replay* style: every round runs the handler from
//! the start. [`Ctx::elicit`] (and its siblings) returns the answer when the
//! client already sent it, in this round or an earlier one; otherwise it
//! records the request and fails with an internal "input required" error that
//! the runtime turns into the `InputRequiredResult`. Code before an input call
//! therefore runs once per round, so it should be free of side effects (or
//! idempotent).
//!
//! Answers from earlier rounds travel in `requestState`, which the client
//! must echo back. The state is HMAC-SHA256 signed and bound to the method,
//! the target (tool or prompt name, resource URI), a digest of the arguments
//! and an expiry, so a client cannot forge answers, replay them on another
//! request, or use them after the expiry. Answers the client sends in this
//! round's `inputResponses` are client input like the arguments themselves.

use std::collections::{BTreeMap, BTreeSet};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use hmac::{Hmac, KeyInit as _, Mac as _};
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use sha2::{Digest as _, Sha256};

use crate::context::Ctx;
use crate::error::McpError;
use crate::spec::{self, methods};
use crate::tool::{ToolError, schema_for};

type HmacSha256 = Hmac<Sha256>;

/// Minimum length of a `requestState` signing key.
pub const MIN_REQUEST_STATE_KEY_BYTES: usize = 32;

/// Version of the `requestState` payload format.
const STATE_VERSION: u8 = 1;

/// Domain separation for `requestState` signatures: a token signed for one
/// purpose (such as a legacy session) is never valid for another.
const SIGNATURE_CONTEXT: &[u8] = b"flymcprust/requestState/v1\0";

/// Signs and verifies `requestState`.
pub(crate) struct StateCodec {
    key: Vec<u8>,
    ttl: Duration,
}

impl std::fmt::Debug for StateCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StateCodec")
            .field("ttl", &self.ttl)
            .finish_non_exhaustive()
    }
}

/// The signed content of `requestState`.
#[derive(Serialize, Deserialize)]
struct Payload {
    v: u8,
    /// Method of the original request.
    m: String,
    /// Tool or prompt name, or resource URI.
    t: String,
    /// Digest of the arguments.
    a: String,
    /// Expiry (seconds since the Unix epoch).
    e: u64,
    /// Rounds completed so far.
    n: u32,
    /// Answers collected in earlier rounds.
    r: BTreeMap<String, Value>,
    /// Digest of the authenticated principal (OAuth), if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    p: Option<String>,
}

impl StateCodec {
    pub(crate) fn new(key: Vec<u8>, ttl: Duration) -> Self {
        Self { key, ttl }
    }

    fn mac(&self, context: &[u8], data: &[u8]) -> Option<HmacSha256> {
        let mut mac = HmacSha256::new_from_slice(&self.key).ok()?;
        mac.update(context);
        mac.update(data);
        Some(mac)
    }

    /// Serializes and signs a payload for one purpose (`context`). The token
    /// is URL-safe base64 plus a dot: visible ASCII, usable in HTTP headers.
    pub(crate) fn seal_for<T: Serialize>(&self, context: &[u8], payload: &T) -> Option<String> {
        let json = serde_json::to_vec(payload).ok()?;
        let body = URL_SAFE_NO_PAD.encode(json);
        let tag = self.mac(context, body.as_bytes())?.finalize().into_bytes();
        Some(format!("{body}.{}", URL_SAFE_NO_PAD.encode(tag)))
    }

    /// Verifies a token signed with [`seal_for`](Self::seal_for) for the
    /// same purpose (in constant time) before decoding it.
    pub(crate) fn open_for<T: DeserializeOwned>(&self, context: &[u8], token: &str) -> Option<T> {
        let (body, tag) = token.rsplit_once('.')?;
        let tag = URL_SAFE_NO_PAD.decode(tag).ok()?;
        self.mac(context, body.as_bytes())?
            .verify_slice(&tag)
            .ok()?;
        let json = URL_SAFE_NO_PAD.decode(body).ok()?;
        serde_json::from_slice(&json).ok()
    }

    fn seal(&self, payload: &Payload) -> Result<String, McpError> {
        self.seal_for(SIGNATURE_CONTEXT, payload)
            .ok_or_else(McpError::internal)
    }

    fn open(&self, token: &str, round: &RoundKey<'_>) -> Result<Payload, McpError> {
        let digest = round.args_digest();
        let invalid = || McpError::invalid_params("Invalid or expired requestState");
        let payload: Payload = self
            .open_for(SIGNATURE_CONTEXT, token)
            .ok_or_else(invalid)?;
        if payload.v != STATE_VERSION
            || payload.m != round.method
            || payload.t != round.target
            || payload.a != digest
            || payload.p.as_deref() != round.principal
            || payload.e < now_secs()
        {
            return Err(invalid());
        }
        Ok(payload)
    }
}

pub(crate) fn now_secs() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs())
}

/// What identifies the original request across rounds. Digests are only
/// computed when MRTR is actually used.
pub(crate) struct RoundKey<'a> {
    pub(crate) method: &'static str,
    pub(crate) target: &'a str,
    pub(crate) arguments: Args<'a>,
    /// Digest of the authenticated principal: a state issued to one user is
    /// useless to another.
    pub(crate) principal: Option<&'a str>,
}

/// The arguments of the original request.
#[derive(Clone, Copy)]
pub(crate) enum Args<'a> {
    None,
    /// Raw JSON (`tools/call`).
    Raw(&'a str),
    /// String arguments (`prompts/get`).
    Map(&'a BTreeMap<String, String>),
}

impl RoundKey<'_> {
    /// Digest of the arguments, insensitive to whitespace and key order.
    fn args_digest(&self) -> String {
        let canonical = match self.arguments {
            Args::None => Vec::new(),
            Args::Raw(raw) => serde_json::from_str::<Value>(raw)
                .ok()
                .and_then(|mut v| {
                    v.sort_all_objects();
                    serde_json::to_vec(&v).ok()
                })
                .unwrap_or_default(),
            Args::Map(map) => serde_json::to_vec(map).unwrap_or_default(),
        };
        URL_SAFE_NO_PAD.encode(Sha256::digest(&canonical))
    }
}

/// MRTR data of one round, carried by [`Ctx`].
#[derive(Debug, Default)]
pub(crate) struct Round {
    /// Rounds completed before this one.
    number: u32,
    /// Answers from earlier rounds (from `requestState`) and from this
    /// round's `inputResponses`.
    responses: BTreeMap<String, Value>,
    /// Requests issued in this round that have no answer yet.
    pending: Mutex<Vec<(String, Value)>>,
    /// Answers the handler read; only these are carried to the next round,
    /// so unrequested data is never signed into `requestState`.
    used: Mutex<BTreeSet<String>>,
}

impl Round {
    /// Collects the answers of a request, verifying its `requestState`.
    pub(crate) fn start(
        codec: &StateCodec,
        key: &RoundKey<'_>,
        input_responses: Option<Value>,
        request_state: Option<&str>,
    ) -> Result<Self, McpError> {
        let (number, mut responses) = match request_state {
            Some(token) => {
                let payload = codec.open(token, key)?;
                (payload.n, payload.r)
            }
            None => (0, BTreeMap::new()),
        };
        match input_responses {
            None | Some(Value::Null) => {}
            Some(Value::Object(map)) => {
                for (k, v) in map {
                    responses.entry(k).or_insert(v);
                }
            }
            Some(_) => {
                return Err(McpError::invalid_params(
                    "`inputResponses` must be an object",
                ));
            }
        }
        Ok(Self {
            number,
            responses,
            pending: Mutex::new(Vec::new()),
            used: Mutex::new(BTreeSet::new()),
        })
    }

    /// Builds the `InputRequiredResult` for the requests issued this round.
    pub(crate) fn input_required(
        &self,
        codec: &StateCodec,
        key: &RoundKey<'_>,
        meta: Option<&spec::ResultMetaObject>,
    ) -> Result<Value, McpError> {
        let pending =
            std::mem::take(&mut *self.pending.lock().unwrap_or_else(PoisonError::into_inner));
        let expiry = now_secs().saturating_add(codec.ttl.as_secs());
        let state = codec.seal(&Payload {
            v: STATE_VERSION,
            m: key.method.to_owned(),
            t: key.target.to_owned(),
            a: key.args_digest(),
            e: expiry,
            p: key.principal.map(str::to_owned),
            n: self.number.saturating_add(1),
            r: {
                let used = self.used.lock().unwrap_or_else(PoisonError::into_inner);
                self.responses
                    .iter()
                    .filter(|(k, _)| used.contains(k.as_str()))
                    .map(|(k, v)| (k.clone(), v.clone()))
                    .collect()
            },
        })?;
        let mut result = Map::new();
        result.insert("resultType".to_owned(), Value::from("input_required"));
        if !pending.is_empty() {
            result.insert(
                "inputRequests".to_owned(),
                Value::Object(pending.into_iter().collect()),
            );
        }
        result.insert("requestState".to_owned(), Value::from(state));
        if let Some(meta) = meta {
            let meta = serde_json::to_value(meta).map_err(|_| McpError::internal())?;
            result.insert("_meta".to_owned(), meta);
        }
        Ok(Value::Object(result))
    }

    fn response(&self, key: &str) -> Option<&Value> {
        let value = self.responses.get(key)?;
        self.used
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .insert(key.to_owned());
        Some(value)
    }

    fn push(&self, key: &str, request: Value) {
        let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
        if !pending.iter().any(|(k, _)| k == key) {
            pending.push((key.to_owned(), request));
        }
    }
}

/// The outcome of an elicitation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Elicitation<T> {
    /// The user submitted the form.
    Accepted(T),
    /// The user explicitly declined.
    Declined,
    /// The user dismissed the request without choosing.
    Cancelled,
}

#[derive(Deserialize)]
struct ElicitAnswer {
    action: String,
    #[serde(default)]
    content: Option<Value>,
}

/// Which client capability an input request needs.
#[derive(Clone, Copy)]
enum Needs {
    Elicitation,
    Sampling,
    Roots,
}

impl Ctx {
    /// The number of input rounds completed before this attempt: `0` on the
    /// first call, `1` after the client answered once, and so on.
    #[must_use]
    pub fn input_round(&self) -> u32 {
        self.round().map_or(0, |r| r.number)
    }

    /// The client's answer for `key`, decoded as `T`, if it sent one in this
    /// round or an earlier one.
    ///
    /// # Errors
    ///
    /// Returns an invalid-params error (`-32602`) if the answer does not
    /// decode as `T`.
    pub fn input_response<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, ToolError> {
        let Some(value) = self.round().and_then(|r| r.response(key)) else {
            return Ok(None);
        };
        T::deserialize(value)
            .map(Some)
            .map_err(|_| invalid_response(key))
    }

    /// Asks the user for structured input with a form generated from `T`
    /// (a flat struct of strings, numbers, booleans and enums). Declining or
    /// cancelling becomes a [`ToolError::user`]; use
    /// [`elicit_with_action`](Self::elicit_with_action) to handle them.
    ///
    /// `key` identifies the question across rounds and must be unique within
    /// the handler. Several questions can be asked in one round by awaiting
    /// them together (for example with `tokio::join!`).
    ///
    /// # Errors
    ///
    /// Fails with an "input required" error when the answer is not available
    /// yet (propagate it with `?`), `-32021` if the client does not support
    /// form elicitation, and `-32602` if the answer is malformed.
    pub async fn elicit<T: DeserializeOwned + JsonSchema>(
        &self,
        key: &str,
        message: impl Into<String>,
    ) -> Result<T, ToolError> {
        match self.elicit_with_action::<T>(key, message).await? {
            Elicitation::Accepted(value) => Ok(value),
            Elicitation::Declined => Err(ToolError::user(
                "The user declined to provide the requested information.",
            )),
            Elicitation::Cancelled => Err(ToolError::user("The user cancelled the request.")),
        }
    }

    /// Like [`elicit`](Self::elicit), but returns declined and cancelled
    /// answers instead of failing.
    ///
    /// # Errors
    ///
    /// See [`elicit`](Self::elicit).
    pub async fn elicit_with_action<T: DeserializeOwned + JsonSchema>(
        &self,
        key: &str,
        message: impl Into<String>,
    ) -> Result<Elicitation<T>, ToolError> {
        if let Some(answer) = self.input_response::<ElicitAnswer>(key)? {
            return match answer.action.as_str() {
                "accept" => {
                    let content = answer.content.unwrap_or_else(|| json!({}));
                    T::deserialize(&content)
                        .map(Elicitation::Accepted)
                        .map_err(|_| invalid_response(key))
                }
                "decline" => Ok(Elicitation::Declined),
                "cancel" => Ok(Elicitation::Cancelled),
                _ => Err(invalid_response(key)),
            };
        }
        let schema = elicitation_schema::<T>()?;
        let request = json!({
            "method": methods::ELICITATION_CREATE,
            "params": { "message": message.into(), "requestedSchema": schema },
        });
        Err(self.ask(key, request, Needs::Elicitation))
    }

    /// Like [`elicit_with_action`](Self::elicit_with_action), with a
    /// hand-written `requestedSchema` (for default values, titled enums or
    /// multi-select fields, which a derived schema cannot express). The
    /// accepted content comes back as JSON, for the handler to validate.
    ///
    /// # Errors
    ///
    /// See [`elicit`](Self::elicit).
    pub async fn elicit_with_schema(
        &self,
        key: &str,
        message: impl Into<String>,
        requested_schema: Value,
    ) -> Result<Elicitation<Map<String, Value>>, ToolError> {
        if let Some(answer) = self.input_response::<ElicitAnswer>(key)? {
            return match answer.action.as_str() {
                "accept" => match answer.content.unwrap_or_else(|| json!({})) {
                    Value::Object(content) => Ok(Elicitation::Accepted(content)),
                    _ => Err(invalid_response(key)),
                },
                "decline" => Ok(Elicitation::Declined),
                "cancel" => Ok(Elicitation::Cancelled),
                _ => Err(invalid_response(key)),
            };
        }
        let request = json!({
            "method": methods::ELICITATION_CREATE,
            "params": { "message": message.into(), "requestedSchema": requested_schema },
        });
        Err(self.ask(key, request, Needs::Elicitation))
    }

    /// Asks the client to sample from a language model.
    ///
    /// # Errors
    ///
    /// Fails with an "input required" error when the answer is not available
    /// yet (propagate it with `?`), `-32021` if the client does not support
    /// sampling, and `-32602` if the answer is malformed.
    #[deprecated(note = "Sampling is deprecated as of protocol version 2026-07-28 (SEP-2577).")]
    #[allow(deprecated)]
    pub async fn sample(
        &self,
        key: &str,
        params: spec::CreateMessageRequestParams,
    ) -> Result<spec::CreateMessageResult, ToolError> {
        if let Some(answer) = self.input_response(key)? {
            return Ok(answer);
        }
        let request = json!({ "method": methods::SAMPLING_CREATE_MESSAGE, "params": params });
        Err(self.ask(key, request, Needs::Sampling))
    }

    /// Asks the client for its filesystem roots.
    ///
    /// # Errors
    ///
    /// Fails with an "input required" error when the answer is not available
    /// yet (propagate it with `?`), `-32021` if the client does not support
    /// roots, and `-32602` if the answer is malformed.
    #[deprecated(note = "Roots are deprecated as of protocol version 2026-07-28 (SEP-2577).")]
    #[allow(deprecated)]
    pub async fn list_roots(&self, key: &str) -> Result<spec::ListRootsResult, ToolError> {
        if let Some(answer) = self.input_response(key)? {
            return Ok(answer);
        }
        let request = json!({ "method": methods::ROOTS_LIST, "params": {} });
        Err(self.ask(key, request, Needs::Roots))
    }

    /// Records an input request and returns the error that ends this round.
    fn ask(&self, key: &str, request: Value, needs: Needs) -> ToolError {
        let Some(round) = self.round() else {
            return ToolError::internal(std::io::Error::other(
                "input requests are only available in tools/call, resources/read and prompts/get",
            ));
        };
        #[allow(deprecated)]
        let caps = self.client_capabilities();
        #[allow(deprecated)]
        let (supported, required) = match needs {
            Needs::Elicitation => (
                caps.elicitation
                    .as_ref()
                    .is_some_and(|e| e.form.is_some() || e.url.is_none()),
                spec::ClientCapabilities {
                    elicitation: Some(spec::ClientCapabilitiesElicitation {
                        form: Some(Map::new()),
                        url: None,
                    }),
                    ..spec::ClientCapabilities::default()
                },
            ),
            Needs::Sampling => (
                caps.sampling.is_some(),
                spec::ClientCapabilities {
                    sampling: Some(spec::ClientCapabilitiesSampling::default()),
                    ..spec::ClientCapabilities::default()
                },
            ),
            Needs::Roots => (
                caps.roots.is_some(),
                spec::ClientCapabilities {
                    roots: Some(spec::ClientCapabilitiesRoots::default()),
                    ..spec::ClientCapabilities::default()
                },
            ),
        };
        if !supported {
            static HINT: crate::hints::Once = crate::hints::Once::new();
            crate::hints::warn_once(
                &HINT,
                format_args!(
                    "a client that did not declare the needed capability called a handler \
                     that asks it for input; it received -32021"
                ),
                "check ctx.client_capabilities() before asking if the handler can work \
                 without the answer",
            );
            return ToolError::missing_client_capability(&required);
        }
        round.push(key, request);
        ToolError::input_required()
    }
}

fn invalid_response(key: &str) -> ToolError {
    ToolError::protocol(McpError::invalid_params(format!(
        "Invalid input response for `{}`",
        crate::error::truncate(key)
    )))
}

/// The `requestedSchema` of an elicitation: the JSON Schema of `T`, which
/// must be an object of primitive fields. `Option<X>` fields (`"type":
/// ["x", "null"]`) become plain optional fields.
fn elicitation_schema<T: JsonSchema>() -> Result<Value, ToolError> {
    let mut schema = schema_for::<T>();
    let unsupported = || {
        ToolError::internal(std::io::Error::other(format!(
            "`{}` cannot be used with ctx.elicit\n  = help: use a struct whose fields are strings, \
             numbers, integers, booleans or enums (optionally in Option<..>); forms cannot nest",
            std::any::type_name::<T>()
        )))
    };
    if schema.get("type").and_then(Value::as_str) != Some("object") {
        return Err(unsupported());
    }
    schema.remove("additionalProperties");
    let Some(Value::Object(properties)) = schema.get_mut("properties") else {
        return Err(unsupported());
    };
    for property in properties.values_mut() {
        let Value::Object(property) = property else {
            return Err(unsupported());
        };
        if let Some(Value::Array(types)) = property.get("type") {
            let non_null: Vec<&Value> = types
                .iter()
                .filter(|t| t.as_str() != Some("null"))
                .collect();
            if let [single] = non_null.as_slice() {
                let single = (*single).clone();
                property.insert("type".to_owned(), single);
            }
        }
        let primitive = matches!(
            property.get("type").and_then(Value::as_str),
            Some("string" | "number" | "integer" | "boolean" | "array")
        ) || property.contains_key("enum")
            || property.contains_key("oneOf")
            || property.contains_key("anyOf");
        if !primitive {
            return Err(unsupported());
        }
    }
    Ok(Value::Object(schema))
}

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

    fn codec() -> StateCodec {
        StateCodec::new(vec![7; 32], Duration::from_secs(600))
    }

    fn key(target: &str) -> RoundKey<'_> {
        RoundKey {
            method: "tools/call",
            target,
            arguments: Args::Raw(r#"{"a": 1}"#),
            principal: None,
        }
    }

    fn round_trip(codec: &StateCodec, round: &Round) -> String {
        round.input_required(codec, &key("t"), None).unwrap()["requestState"]
            .as_str()
            .unwrap()
            .to_owned()
    }

    #[test]
    fn state_round_trips_and_accumulates_answers() {
        let codec = codec();
        let first = Round::start(
            &codec,
            &key("t"),
            Some(json!({ "q1": 1, "unread": 0 })),
            None,
        )
        .unwrap();
        // The handler reads `q1` only.
        assert_eq!(first.response("q1"), Some(&json!(1)));
        let token = round_trip(&codec, &first);
        let second =
            Round::start(&codec, &key("t"), Some(json!({ "q2": 2 })), Some(&token)).unwrap();
        assert_eq!(second.number, 1);
        assert_eq!(second.response("q1"), Some(&json!(1)));
        assert_eq!(second.response("q2"), Some(&json!(2)));
        // Unread answers are not carried over.
        assert_eq!(second.response("unread"), None);
    }

    #[test]
    fn tampered_or_rebound_state_is_rejected() {
        let codec = codec();
        let round = Round::start(&codec, &key("t"), None, None).unwrap();
        let token = round_trip(&codec, &round);
        let reject = |token: &str, key: RoundKey<'_>| {
            Round::start(&codec, &key, None, Some(token))
                .unwrap_err()
                .code()
        };
        assert_eq!(reject(&format!("{token}-TAMPERED"), key("t")), -32602);
        assert_eq!(reject("garbage", key("t")), -32602);
        // Another tool, other arguments, or another key.
        assert_eq!(reject(&token, key("other")), -32602);
        let mut other_args = key("t");
        other_args.arguments = Args::Raw(r#"{"a":2}"#);
        assert_eq!(reject(&token, other_args), -32602);
        // Another user.
        let mut other_user = key("t");
        other_user.principal = Some("someone-else");
        assert_eq!(reject(&token, other_user), -32602);
        let other_key = StateCodec::new(vec![8; 32], Duration::from_secs(600));
        assert!(Round::start(&other_key, &key("t"), None, Some(&token)).is_err());
    }

    #[test]
    fn expired_state_is_rejected() {
        let codec = StateCodec::new(vec![7; 32], Duration::ZERO);
        let round = Round::start(&codec, &key("t"), None, None).unwrap();
        let mut payload: Payload = {
            let token = round_trip(&codec, &round);
            let body = token.split('.').next().unwrap();
            serde_json::from_slice(&URL_SAFE_NO_PAD.decode(body).unwrap()).unwrap()
        };
        payload.e = now_secs() - 1;
        let token = codec.seal(&payload).unwrap();
        assert!(Round::start(&codec, &key("t"), None, Some(&token)).is_err());
    }

    #[test]
    fn argument_digest_ignores_whitespace() {
        let digest = |raw| {
            RoundKey {
                method: "tools/call",
                target: "t",
                arguments: Args::Raw(raw),
                principal: None,
            }
            .args_digest()
        };
        assert_eq!(digest(r#"{"a":1}"#), digest(r#"{ "a" : 1 }"#));
        assert_eq!(
            digest(r#"{"a":1,"b":{"y":2,"x":1}}"#),
            digest(r#"{"b":{"x":1,"y":2},"a":1}"#)
        );
        assert_ne!(digest(r#"{"a":1}"#), digest(r#"{"a":2}"#));
    }

    #[test]
    fn invalid_input_responses_are_rejected() {
        let err = Round::start(&codec(), &key("t"), Some(json!(5)), None).unwrap_err();
        assert_eq!(err.code(), -32602);
    }

    #[derive(JsonSchema)]
    #[allow(dead_code)]
    struct Form {
        name: String,
        age: Option<u32>,
        subscribe: bool,
    }

    #[test]
    fn elicitation_schema_is_flat() {
        let schema = elicitation_schema::<Form>().unwrap();
        assert_eq!(
            schema,
            json!({
                "type": "object",
                "properties": {
                    "name": { "type": "string" },
                    "age": { "type": "integer", "minimum": 0 },
                    "subscribe": { "type": "boolean" },
                },
                "required": ["name", "subscribe"],
            })
        );
        #[derive(JsonSchema)]
        #[allow(dead_code)]
        struct Nested {
            inner: Form,
        }
        assert!(elicitation_schema::<Nested>().is_err());
    }
}