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
//! Types used by the MCP protocol
//!
//! See the [specification](https://github.com/modelcontextprotocol/specification) for details

use crate::SDK_NAME;
use crate::types::notification::Notification;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt::Display;

#[cfg(feature = "server")]
use crate::{
    app::handler::{FromHandlerParams, HandlerParams},
    app::options::McpOptions,
    error::Error,
};

#[cfg(feature = "server")]
pub use request::FromRequest;

#[cfg(feature = "http-server")]
use {crate::auth::DefaultClaims, volga::headers::HeaderMap};

pub use capabilities::{
    ClientCapabilities, CompletionsCapability, ElicitationCapability, ElicitationFormCapability,
    ElicitationUrlCapability, LoggingCapability, PromptsCapability, ResourcesCapability,
    RootsCapability, SamplingCapability, SamplingContextCapability, SamplingToolsCapability,
    ServerCapabilities, ToolsCapability,
};
pub use completion::{Argument, CompleteRequestParams, CompleteResult, Completion};
pub use content::{
    AudioContent, Content, EmbeddedResource, ImageContent, ResourceLink, TextContent, ToolResult,
    ToolUse,
};
pub use cursor::{Cursor, Page, Pagination};
pub use helpers::{Json, Meta, PropertyType};
pub use reference::Reference;
pub use request::{Request, RequestId, RequestParamsMeta};
pub use response::{ErrorDetails, IntoResponse, Response};

#[cfg(feature = "tasks")]
pub use capabilities::{
    ClientTaskRequestsCapability, ClientTasksCapability, ElicitationCreateTaskCapability,
    ElicitationTaskCapability, SamplingCreateMessageTaskCapability, SamplingTaskCapability,
    ServerTaskRequestsCapability, ServerTasksCapability, TaskCancellationCapability,
    TaskListCapability, ToolsCallTaskCapability, ToolsTaskCapability,
};

pub use tool::{
    CallToolRequestParams, CallToolResponse, ListToolsRequestParams, ListToolsResult, Tool,
    ToolAnnotations, ToolSchema,
};

#[cfg(feature = "server")]
pub use tool::ToolHandler;

pub use elicitation::{
    ElicitRequestFormParams, ElicitRequestParams, ElicitRequestUrlParams, ElicitResult,
    ElicitationAction, ElicitationCompleteParams, ElicitationMode, UrlElicitationRequiredError,
};
pub use prompt::{
    GetPromptRequestParams, GetPromptResult, ListPromptsRequestParams, ListPromptsResult, Prompt,
    PromptArgument, PromptMessage,
};
pub use resource::{
    BlobResourceContents, ListResourceTemplatesRequestParams, ListResourceTemplatesResult,
    ListResourcesRequestParams, ListResourcesResult, ReadResourceRequestParams, ReadResourceResult,
    Resource, ResourceContents, ResourceTemplate, SubscribeRequestParams, TextResourceContents,
    UnsubscribeRequestParams, Uri,
};
pub use sampling::{
    CreateMessageRequestParams, CreateMessageResult, SamplingMessage, StopReason, ToolChoice,
    ToolChoiceMode,
};
pub use schema::{
    BooleanSchema, NumberSchema, Schema, StringFormat, StringSchema, TitledMultiSelectEnumSchema,
    TitledSingleSelectEnumSchema, UntitledMultiSelectEnumSchema, UntitledSingleSelectEnumSchema,
};

pub use icon::{Icon, IconSize, IconTheme};

#[cfg(feature = "tasks")]
pub use task::{
    CancelTaskRequestParams, CreateTaskResult, GetTaskPayloadRequestParams, GetTaskRequestParams,
    ListTasksRequestParams, ListTasksResult, RelatedTaskMetadata, Task, TaskMetadata, TaskPayload,
    TaskStatus,
};

#[cfg(feature = "server")]
pub use prompt::PromptHandler;

pub use progress::ProgressToken;
pub use root::Root;

mod capabilities;
pub mod completion;
mod content;
pub mod cursor;
pub mod elicitation;
pub(crate) mod helpers;
mod icon;
pub mod notification;
mod progress;
pub mod prompt;
mod reference;
mod request;
pub mod resource;
mod response;
pub mod root;
pub mod sampling;
mod schema;
#[cfg(feature = "tasks")]
pub mod task;
pub mod tool;

pub(super) const JSONRPC_VERSION: &str = "2.0";

/// Represents a JSON RPC message that could be either [`Request`] or [`Response`] or [`Notification`] or a [`MessageBatch`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Message {
    /// See [`Request`]
    Request(Request),

    /// See [`Response`]
    Response(Response),

    /// See [`Notification`]
    Notification(Notification),

    /// See [`MessageBatch`]
    ///
    /// # Note
    /// This variant **must remain last**. `#[serde(untagged)]` tries variants in
    /// declaration order. A JSON array will always fail to deserialize as the
    /// object-shaped `Request`, `Response`, and `Notification` variants above,
    /// so placing `Batch` last is both safe and correct.
    Batch(MessageBatch),
}

/// Represents a single JSON-RPC message inside a batch.
/// Batches cannot be nested, so [`Message::Batch`] is excluded.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum MessageEnvelope {
    /// See [`Request`]
    Request(Request),

    /// See [`Response`]
    Response(Response),

    /// See [`Notification`]
    Notification(Notification),
}

/// Represents a non-empty JSON-RPC 2.0 batch.
///
/// A batch is a JSON array of [`MessageEnvelope`] items sent in a single
/// transport write. The server processes all requests in parallel and
/// replies with a single batch response array.
///
/// # Invariant
/// A batch must contain at least one item. Constructing or deserializing
/// an empty batch returns an error.
#[derive(Debug, Clone)]
pub struct MessageBatch {
    /// Per-batch correlation identifier. Never sent over the wire.
    ///
    /// Auto-generated as a UUID on construction or deserialization.
    /// Combined with `session_id` in [`MessageBatch::full_id`] to give the
    /// HTTP transport a unique key for routing the response back to the
    /// correct waiting HTTP handler.
    pub(crate) id: RequestId,

    /// MCP session this batch belongs to. Never sent over the wire.
    ///
    /// Set by the HTTP transport layer, same as for [`Request`] and
    /// [`Notification`].
    pub(crate) session_id: Option<uuid::Uuid>,

    /// HTTP headers from the originating request. Never sent over the wire.
    ///
    /// Copied onto each inner [`Request`] in `execute_batch` so that
    /// middleware (e.g. auth checks) sees the original headers.
    #[cfg(feature = "http-server")]
    pub(crate) headers: HeaderMap,

    /// JWT claims decoded from the originating request. Never sent over the wire.
    ///
    /// Copied onto each inner [`Request`] in `execute_batch` so that
    /// role/permission guards work correctly for batched HTTP calls.
    #[cfg(feature = "http-server")]
    pub(crate) claims: Option<Box<DefaultClaims>>,

    items: Vec<MessageEnvelope>,
}

impl MessageBatch {
    /// Constructs a new [`MessageBatch`] with a freshly generated correlation ID.
    ///
    /// # Errors
    /// Returns [`crate::error::Error`] if `items` is empty.
    pub fn new(items: Vec<MessageEnvelope>) -> Result<Self, crate::error::Error> {
        if items.is_empty() {
            return Err(crate::error::Error::new(
                crate::error::ErrorCode::InvalidRequest,
                "batch must not be empty",
            ));
        }
        Ok(Self {
            id: RequestId::Uuid(uuid::Uuid::new_v4()),
            session_id: None,
            #[cfg(feature = "http-server")]
            headers: HeaderMap::with_capacity(8),
            #[cfg(feature = "http-server")]
            claims: None,
            items,
        })
    }

    /// Returns the full correlation key `(session_id/)id`, matching the
    /// pattern used by [`Request`] and [`Notification`].
    pub(crate) fn full_id(&self) -> RequestId {
        let id = self.id.clone();
        if let Some(session_id) = self.session_id {
            id.concat(RequestId::Uuid(session_id))
        } else {
            id
        }
    }

    /// Returns the number of items in the batch.
    #[inline]
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Returns `true` if the batch has no items.
    ///
    /// Note: a [`MessageBatch`] can never be empty after successful construction,
    /// but this method is provided for API completeness.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// Returns an iterator over the batch items.
    #[inline]
    pub fn iter(&self) -> impl Iterator<Item = &MessageEnvelope> {
        self.items.iter()
    }

    /// Returns `true` if the batch contains at least one [`MessageEnvelope::Request`].
    ///
    /// Used by the HTTP transport to decide whether a pending response slot
    /// must be allocated: a notification-only batch produces no response.
    #[inline]
    #[cfg(any(feature = "http-server", feature = "http-client"))]
    pub(crate) fn has_requests(&self) -> bool {
        self.items
            .iter()
            .any(|e| matches!(e, MessageEnvelope::Request(_)))
    }

    /// Returns `true` if the batch contains at least one [`MessageEnvelope::Response`]
    /// that carries an error.
    ///
    /// Used by the HTTP transport alongside [`Self::has_requests`] to decide
    /// whether a pending reply slot must be allocated. Batches with error
    /// responses include synthetic `InvalidRequest` errors that the deserializer
    /// injects for malformed items — those require an HTTP reply so the caller
    /// receives the per-item error payloads.
    #[inline]
    #[cfg(feature = "http-server")]
    pub(crate) fn has_error_responses(&self) -> bool {
        self.items
            .iter()
            .any(|e| matches!(e, MessageEnvelope::Response(Response::Err(_))))
    }
}

impl IntoIterator for MessageBatch {
    type Item = MessageEnvelope;
    type IntoIter = std::vec::IntoIter<MessageEnvelope>;

    fn into_iter(self) -> Self::IntoIter {
        self.items.into_iter()
    }
}

impl Serialize for MessageBatch {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // `id` and `session_id` are internal — only the items are sent over the wire.
        self.items.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for MessageBatch {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Parse as raw JSON values first so that a single malformed element
        // does not discard the entire batch (JSON-RPC §6 requires per-item
        // Invalid Request responses, not a top-level failure).
        let raw = Vec::<serde_json::Value>::deserialize(deserializer)?;
        if raw.is_empty() {
            return Err(serde::de::Error::custom(
                "JSON-RPC batch array must not be empty",
            ));
        }

        // Every item either deserializes cleanly or produces an error response.
        // Items without an id use RequestId::Null (JSON-RPC 2.0 §5.1 requires
        // `"id": null` when the id cannot be extracted from a malformed request).
        let items: Vec<MessageEnvelope> = raw
            .into_iter()
            .map(|value| {
                // Extract the id first (while we still own `value`) so that
                // parse failures can produce a typed Invalid Request response.
                let id = value
                    .get("id")
                    .and_then(|v| serde_json::from_value::<RequestId>(v.clone()).ok())
                    .unwrap_or(RequestId::Null);
                match serde_json::from_value::<MessageEnvelope>(value) {
                    Ok(envelope) => envelope,
                    Err(_) => MessageEnvelope::Response(Response::error(
                        id,
                        crate::error::Error::new(
                            crate::error::ErrorCode::InvalidRequest,
                            "Invalid Request",
                        ),
                    )),
                }
            })
            .collect();

        Ok(Self {
            id: RequestId::Uuid(uuid::Uuid::new_v4()),
            session_id: None,
            #[cfg(feature = "http-server")]
            headers: HeaderMap::with_capacity(8),
            #[cfg(feature = "http-server")]
            claims: None,
            items,
        })
    }
}

/// Parameters for an initialization request sent to the server.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeRequestParams {
    /// The version of the Model Context Protocol that the client is to use.
    #[serde(rename = "protocolVersion")]
    pub protocol_ver: String,

    /// The client's capabilities.
    pub capabilities: Option<ClientCapabilities>,

    /// Information about the client implementation.
    #[serde(rename = "clientInfo")]
    pub client_info: Option<Implementation>,
}

/// Result of the initialization request sent to the server.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeResult {
    /// The version of the Model Context Protocol that the server is to use.
    #[serde(rename = "protocolVersion")]
    pub protocol_ver: String,

    /// The server's capabilities.
    pub capabilities: ServerCapabilities,

    /// Information about the server implementation.
    #[serde(rename = "serverInfo")]
    pub server_info: Implementation,

    /// Optional instructions for using the server and its features.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
}

/// Describes the name and version of an MCP implementation.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Implementation {
    /// Name of the implementation.
    pub name: String,

    /// Version of the implementation.
    pub version: String,

    /// Optional set of sized icons that the client can display in a user interface.
    ///
    /// Clients that support rendering icons **MUST** support at least the following MIME types:
    /// - `image/png` - PNG images (safe, universal compatibility)
    /// - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
    ///
    /// Clients that support rendering icons **SHOULD** also support:
    /// - `image/svg+xml` - SVG images (scalable but requires security precautions)
    /// - `image/webp` - WebP images (modern, efficient format)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<Icon>>,
}

/// Represents the type of role in the conversation.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    /// Corresponds to the user in the conversation.
    User,
    /// Corresponds to the AI in the conversation.
    Assistant,
}

/// Represents annotations that can be attached to content.
/// The client can use annotations to inform how objects are used or displayed
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Annotations {
    /// Describes who the intended customer of this object or data is.
    audience: Vec<Role>,

    /// The moment the resource was last modified, as an ISO 8601 formatted string.
    ///
    /// Should be an ISO 8601 formatted string (e.g., **"2025-01-12T15:00:58Z"**).
    ///
    /// **Examples:** last activity timestamp in an open file, timestamp when the resource
    /// was attached, etc.
    #[serde(rename = "lastModified", skip_serializing_if = "Option::is_none")]
    last_modified: Option<DateTime<Utc>>,

    /// Describes how important this data is for operating the server (0 to 1).
    ///
    /// A value of 1 means **most important** and indicates that the data is
    /// effectively required, while 0 means **least important** and indicates that
    /// the data is entirely optional.
    priority: f32,
}

impl Display for Role {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Role::User => write!(f, "user"),
            Role::Assistant => write!(f, "assistant"),
        }
    }
}

impl From<&str> for Role {
    #[inline]
    fn from(role: &str) -> Self {
        match role {
            "user" => Self::User,
            "assistant" => Self::Assistant,
            _ => Self::User,
        }
    }
}

impl From<String> for Role {
    #[inline]
    fn from(role: String) -> Self {
        match role.as_str() {
            "user" => Self::User,
            "assistant" => Self::Assistant,
            _ => Self::User,
        }
    }
}

impl Default for Implementation {
    fn default() -> Self {
        Self {
            name: SDK_NAME.into(),
            version: env!("CARGO_PKG_VERSION").into(),
            icons: None,
        }
    }
}

impl IntoResponse for InitializeResult {
    #[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(feature = "server")]
impl FromHandlerParams for InitializeRequestParams {
    #[inline]
    fn from_params(params: &HandlerParams) -> Result<Self, Error> {
        let req = Request::from_params(params)?;
        Self::from_request(req)
    }
}

impl From<MessageEnvelope> for Message {
    fn from(envelope: MessageEnvelope) -> Self {
        match envelope {
            MessageEnvelope::Request(r) => Message::Request(r),
            MessageEnvelope::Response(r) => Message::Response(r),
            MessageEnvelope::Notification(n) => Message::Notification(n),
        }
    }
}

impl Message {
    /// Returns `true` is the current message is [`Request`]
    #[inline]
    pub fn is_request(&self) -> bool {
        matches!(self, Message::Request(_))
    }

    /// Returns `true` is the current message is [`Response`]
    #[inline]
    pub fn is_response(&self) -> bool {
        matches!(self, Message::Response(_))
    }

    /// Returns `true` is the current message is [`Notification`]
    #[inline]
    pub fn is_notification(&self) -> bool {
        matches!(self, Message::Notification(_))
    }

    /// Returns `true` if this message is a [`MessageBatch`]
    #[inline]
    pub fn is_batch(&self) -> bool {
        matches!(self, Message::Batch(_))
    }

    /// Returns [`Message`] ID
    #[inline]
    pub fn id(&self) -> RequestId {
        match self {
            Message::Request(req) => req.id(),
            Message::Response(resp) => resp.id().clone(),
            Message::Notification(_) | Message::Batch(_) => RequestId::default(),
        }
    }

    /// Returns the full id (session_id?/message_id)
    pub fn full_id(&self) -> RequestId {
        match self {
            Message::Request(req) => req.full_id(),
            Message::Response(resp) => resp.full_id(),
            Message::Notification(notification) => notification.full_id(),
            Message::Batch(batch) => batch.full_id(),
        }
    }

    /// Returns MCP Session ID
    #[inline]
    pub fn session_id(&self) -> Option<&uuid::Uuid> {
        match self {
            Message::Request(req) => req.session_id.as_ref(),
            Message::Response(resp) => resp.session_id(),
            Message::Notification(notification) => notification.session_id.as_ref(),
            Message::Batch(batch) => batch.session_id.as_ref(),
        }
    }

    /// Sets MCP Session ID
    pub fn set_session_id(mut self, id: uuid::Uuid) -> Self {
        match self {
            Message::Request(ref mut req) => req.session_id = Some(id),
            Message::Notification(ref mut notification) => notification.session_id = Some(id),
            Message::Response(resp) => self = Message::Response(resp.set_session_id(id)),
            Message::Batch(ref mut batch) => batch.session_id = Some(id),
        }
        self
    }

    /// Sets HTTP headers for [`Request`], [`Response`], or [`MessageBatch`] message
    #[cfg(feature = "http-server")]
    pub fn set_headers(mut self, headers: HeaderMap) -> Self {
        match self {
            Message::Request(ref mut req) => req.headers = headers,
            Message::Response(resp) => self = Message::Response(resp.set_headers(headers)),
            Message::Batch(ref mut batch) => batch.headers = headers,
            _ => (),
        }
        self
    }

    /// Sets Authentication and Authorization claims for [`Request`] or [`MessageBatch`] message
    #[cfg(feature = "http-server")]
    pub(crate) fn set_claims(mut self, claims: DefaultClaims) -> Self {
        match self {
            Message::Request(ref mut req) => req.claims = Some(Box::new(claims)),
            Message::Batch(ref mut batch) => batch.claims = Some(Box::new(claims)),
            _ => (),
        }
        self
    }
}

impl Annotations {
    /// Deserializes a new [`Annotations`] from a JSON string
    #[inline]
    pub fn from_json_str(json: &str) -> Self {
        serde_json::from_str(json).expect("Annotations: Incorrect JSON string provided")
    }

    /// Adds audience
    pub fn with_audience<T: Into<Role>>(mut self, role: T) -> Self {
        self.audience.push(role.into());
        self
    }

    /// Sets the priority
    pub fn with_priority(mut self, priority: f32) -> Self {
        self.priority = priority;
        self
    }

    /// Sets the moment the object was last modified
    pub fn with_last_modified(mut self, last_modified: DateTime<Utc>) -> Self {
        self.last_modified = Some(last_modified);
        self
    }
}

impl Implementation {
    /// Specifies icons
    #[inline]
    pub fn with_icons(mut self, icons: impl IntoIterator<Item = Icon>) -> Self {
        self.icons = Some(icons.into_iter().collect());
        self
    }
}

#[cfg(feature = "server")]
impl InitializeResult {
    pub(crate) fn new(options: &McpOptions) -> Self {
        Self {
            protocol_ver: options.protocol_ver().into(),
            capabilities: ServerCapabilities {
                tools: options.tools_capability(),
                resources: options.resources_capability(),
                prompts: options.prompts_capability(),
                logging: Some(LoggingCapability::default()),
                completions: Some(CompletionsCapability::default()),
                #[cfg(feature = "tasks")]
                tasks: options.tasks_capability(),
                experimental: None,
            },
            server_info: options.implementation.clone(),
            instructions: None,
        }
    }
}

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

    #[test]
    fn message_envelope_deserializes_request() {
        let json = r#"{"jsonrpc":"2.0","id":1,"method":"ping","params":null}"#;
        let envelope: MessageEnvelope = serde_json::from_str(json).unwrap();
        assert!(matches!(envelope, MessageEnvelope::Request(_)));
    }

    #[test]
    fn message_batch_rejects_empty_vec() {
        let err = MessageBatch::new(vec![]);
        assert!(err.is_err());
    }

    #[test]
    fn message_batch_rejects_empty_json_array() {
        let err: Result<MessageBatch, _> = serde_json::from_str("[]");
        assert!(err.is_err());
    }

    #[test]
    fn message_batch_accepts_non_empty() {
        let json = r#"[{"jsonrpc":"2.0","id":1,"method":"ping","params":null}]"#;
        let batch: MessageBatch = serde_json::from_str(json).unwrap();
        assert_eq!(batch.len(), 1);
    }

    #[test]
    fn message_deserializes_batch() {
        let json = r#"[{"jsonrpc":"2.0","id":1,"method":"ping","params":null}]"#;
        let msg: Message = serde_json::from_str(json).unwrap();
        assert!(matches!(msg, Message::Batch(_)));
    }

    #[test]
    fn message_batch_emits_null_error_for_malformed_item_without_id() {
        // A malformed item with no "id" yields an Invalid Request response with
        // a null id (JSON-RPC 2.0 §5.1).
        let json = r#"[
            {"jsonrpc":"2.0","id":1,"method":"ping","params":null},
            {"not":"valid json-rpc"}
        ]"#;
        let batch: MessageBatch = serde_json::from_str(json).unwrap();
        assert_eq!(batch.len(), 2);
        let mut iter = batch.iter();
        assert!(matches!(iter.next(), Some(MessageEnvelope::Request(_))));
        let second = iter.next().expect("second item should be present");
        let MessageEnvelope::Response(resp) = second else {
            panic!("expected error response for malformed item, got {second:?}");
        };
        assert!(matches!(resp, Response::Err(_)));
        // The id must serialize as JSON null.
        let serialized = serde_json::to_string(resp).unwrap();
        assert!(
            serialized.contains(r#""id":null"#),
            "expected null id, got: {serialized}"
        );
    }

    #[test]
    fn message_batch_produces_error_response_for_malformed_item_with_id() {
        // A malformed item that carries an "id" yields an Invalid Request response
        // with that id preserved.
        let json = r#"[
            {"jsonrpc":"2.0","id":1,"method":"ping","params":null},
            {"jsonrpc":"2.0","id":2,"params":"not-an-object-and-no-method"}
        ]"#;
        let batch: MessageBatch = serde_json::from_str(json).unwrap();
        assert_eq!(batch.len(), 2);
        let mut iter = batch.iter();
        assert!(matches!(iter.next(), Some(MessageEnvelope::Request(_))));
        let second = iter.next().expect("second item should be present");
        let MessageEnvelope::Response(resp) = second else {
            panic!("expected error response for malformed item, got {second:?}");
        };
        assert!(matches!(resp, Response::Err(_)));
        let serialized = serde_json::to_string(resp).unwrap();
        assert!(
            serialized.contains(r#""id":2"#),
            "expected id 2, got: {serialized}"
        );
    }

    #[test]
    fn message_batch_all_malformed_without_ids_produces_null_error_responses() {
        // Even when every item is malformed with no id, the batch deserializes
        // successfully and produces null-id Invalid Request error responses —
        // one per item.
        let json = r#"[{"not":"valid"},{"also":"not valid"}]"#;
        let batch: MessageBatch = serde_json::from_str(json).unwrap();
        assert_eq!(batch.len(), 2);
        for envelope in batch.iter() {
            let MessageEnvelope::Response(resp) = envelope else {
                panic!("expected error response, got {envelope:?}");
            };
            assert!(matches!(resp, Response::Err(_)));
            let serialized = serde_json::to_string(resp).unwrap();
            assert!(
                serialized.contains(r#""id":null"#),
                "expected null id, got: {serialized}"
            );
        }
    }
}