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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Any Text, Image, Audio, Video content utilities

use crate::error::{Error, ErrorCode};
use crate::shared;
use bytes::Bytes;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

use crate::types::helpers::{deserialize_base64_as_bytes, serialize_bytes_as_base64};
use crate::types::{
    Annotations, CallToolRequestParams, CallToolResponse, Icon, Resource, ResourceContents, Uri,
};

const CHUNK_SIZE: usize = 8192;

/// Represents the content of the response.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema/) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Content {
    /// Audio content
    #[serde(rename = "audio")]
    Audio(AudioContent),

    /// Image content
    #[serde(rename = "image")]
    Image(ImageContent),

    /// Text content
    #[serde(rename = "text")]
    Text(TextContent),

    /// Resource link
    #[serde(rename = "resource_link")]
    ResourceLink(ResourceLink),

    /// Embedded resource
    #[serde(rename = "resource")]
    Resource(EmbeddedResource),

    /// Tool use content
    #[serde(rename = "tool_use")]
    ToolUse(ToolUse),

    /// Tool result content
    #[serde(rename = "tool_result")]
    ToolResult(ToolResult),

    /// Empty content
    #[serde(rename = "empty")]
    Empty(EmptyContent),
}

/// Represents an empty content object.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct EmptyContent;

/// Text provided to or from an LLM.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextContent {
    /// The text content of the message.
    pub text: String,

    /// Optional annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// Audio provided to or from an LLM.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioContent {
    /// Raw audio data.
    ///
    /// **Note:** will be serialized as a base64-encoded string
    #[serde(
        serialize_with = "serialize_bytes_as_base64",
        deserialize_with = "deserialize_base64_as_bytes"
    )]
    pub data: Bytes,

    /// The MIME type of the audio content, e.g. "audio/mpeg" or "audio/wav".
    #[serde(rename = "mimeType")]
    pub mime: String,

    /// Optional annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// An image provided to or from an LLM.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ImageContent {
    /// Raw image data.
    ///
    /// **Note:** will be serialized as a base64-encoded string
    #[serde(
        serialize_with = "serialize_bytes_as_base64",
        deserialize_with = "deserialize_base64_as_bytes"
    )]
    pub data: Bytes,

    /// The MIME type of the audio content, e.g. "image/jpg" or "image/png".
    #[serde(rename = "mimeType")]
    pub mime: String,

    /// Optional annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// A resource that the server is capable of reading, included in a prompt or tool call result.
///
/// **Note:** resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceLink {
    /// The URI of this resource.
    pub uri: Uri,

    /// Intended for programmatic or logical use  
    /// but used as a display name in past specs or fallback (if a title isn't present).
    pub name: String,

    /// The resource size in bytes, if known
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<usize>,

    /// The MIME type of the resource. If known.
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime: Option<String>,

    /// Intended for UI and end-user contexts - optimized to be human-readable and easily understood,
    /// even by those unfamiliar with domain-specific terminology.
    ///
    /// If not provided, the name should be used for display (except for Tool,
    /// where `annotations.title` should be given precedence over using `name`, if present).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// A description of what this resource represents.
    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub descr: Option<String>,

    /// Optional annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// 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>>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// The contents of a resource, embedded into a prompt or tool call result.
///
/// It is up to the client how best to render embedded resources for the benefit
/// of the LLM and/or the user.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmbeddedResource {
    /// The resource content of the message.
    pub resource: ResourceContents,

    /// Optional annotations for the client.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// Represents a request from the assistant to call a tool.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolUse {
    /// A unique identifier for this tool use.
    ///
    /// This ID is used to match tool results to their corresponding tool uses.
    pub id: String,

    /// The name of the tool to call.
    pub name: String,

    /// The arguments to pass to the tool, conforming to the tool's input schema.
    pub input: Option<HashMap<String, Value>>,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

/// Represents the result of a tool use, provided by the user back to the assistant.
///
/// See the [schema](https://github.com/modelcontextprotocol/specification/blob/main/schema) for details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolResult {
    /// The ID of the tool use this result corresponds to.
    ///
    /// This **MUST** match the ID from a previous [`ToolUse`].
    #[serde(rename = "toolUseId")]
    pub tool_use_id: String,

    /// The unstructured result content of the tool use.
    ///
    /// This has the same format as [`CallToolResponse::content`] and can include text, images, audio, resource links, and embedded resources.
    pub content: Vec<Content>,

    /// An optional JSON object that represents the structured result of the tool call.
    ///
    /// If the tool defined an `outputSchema`, this **SHOULD** conform to that schema.
    #[serde(rename = "structuredContent", skip_serializing_if = "Option::is_none")]
    pub struct_content: Option<Value>,

    /// Whether the tool call was unsuccessful.
    ///
    /// If true, the content typically describes the error that occurred.
    ///
    /// Default: `false`
    #[serde(default, rename = "isError")]
    pub is_error: bool,

    /// Metadata reserved by MCP for protocol-level metadata.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Value>,
}

impl From<&str> for Content {
    #[inline]
    fn from(value: &str) -> Self {
        Self::text(value)
    }
}

impl From<String> for Content {
    #[inline]
    fn from(value: String) -> Self {
        Self::text(value)
    }
}

impl From<Resource> for ResourceLink {
    #[inline]
    fn from(res: Resource) -> Self {
        Self {
            name: res.name,
            uri: res.uri,
            size: res.size,
            mime: res.mime,
            title: res.title,
            descr: res.descr,
            annotations: res.annotations,
            meta: res.meta,
            icons: res.icons,
        }
    }
}

impl From<Resource> for Content {
    #[inline]
    fn from(res: Resource) -> Self {
        Self::ResourceLink(res.into())
    }
}

impl From<Value> for Content {
    #[inline]
    fn from(value: Value) -> Self {
        Self::Text(TextContent::new(value.to_string()))
    }
}

impl From<TextContent> for Content {
    #[inline]
    fn from(value: TextContent) -> Self {
        Self::Text(value)
    }
}

impl TryFrom<Content> for TextContent {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::Text(text) => Ok(text),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl<'a> TryFrom<&'a Content> for &'a TextContent {
    type Error = Error;

    #[inline]
    fn try_from(value: &'a Content) -> Result<Self, Self::Error> {
        match value {
            Content::Text(text) => Ok(text),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl From<AudioContent> for Content {
    #[inline]
    fn from(value: AudioContent) -> Self {
        Self::Audio(value)
    }
}

impl TryFrom<Content> for AudioContent {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::Audio(audio) => Ok(audio),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl From<ImageContent> for Content {
    #[inline]
    fn from(value: ImageContent) -> Self {
        Self::Image(value)
    }
}

impl TryFrom<Content> for ImageContent {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::Image(img) => Ok(img),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl From<ResourceLink> for Content {
    #[inline]
    fn from(value: ResourceLink) -> Self {
        Self::ResourceLink(value)
    }
}

impl TryFrom<Content> for ResourceLink {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::ResourceLink(res) => Ok(res),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl From<EmbeddedResource> for Content {
    #[inline]
    fn from(value: EmbeddedResource) -> Self {
        Self::Resource(value)
    }
}

impl TryFrom<Content> for EmbeddedResource {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::Resource(res) => Ok(res),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl From<ToolUse> for Content {
    #[inline]
    fn from(value: ToolUse) -> Self {
        Self::ToolUse(value)
    }
}

impl From<ToolResult> for Content {
    #[inline]
    fn from(value: ToolResult) -> Self {
        Self::ToolResult(value)
    }
}

impl From<ToolUse> for CallToolRequestParams {
    #[inline]
    fn from(value: ToolUse) -> Self {
        Self {
            name: value.name,
            args: value.input,
            meta: None,
            #[cfg(feature = "tasks")]
            task: None,
        }
    }
}

impl TryFrom<Content> for ToolUse {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::ToolUse(tool_use) => Ok(tool_use),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl TryFrom<Content> for ToolResult {
    type Error = Error;

    #[inline]
    fn try_from(value: Content) -> Result<Self, Self::Error> {
        match value {
            Content::ToolResult(tool_result) => Ok(tool_result),
            _ => Err(Error::new(ErrorCode::InternalError, "Invalid content type")),
        }
    }
}

impl Content {
    /// Creates a text [`Content`]
    #[inline]
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text(TextContent::new(text))
    }

    /// Creates a JSON [`Content`]
    #[inline]
    pub fn json<T: Serialize>(json: T) -> Self {
        let json = serde_json::to_value(json).unwrap();
        Self::from(json)
    }

    /// Creates an image [`Content`]
    #[inline]
    pub fn image(data: impl Into<Bytes>) -> Self {
        Self::Image(ImageContent::new(data))
    }

    /// Creates an audio [`Content`]
    #[inline]
    pub fn audio(data: impl Into<Bytes>) -> Self {
        Self::Audio(AudioContent::new(data))
    }

    /// Creates an embedded resource [`Content`]
    #[inline]
    pub fn resource(resource: impl Into<ResourceContents>) -> Self {
        Self::Resource(EmbeddedResource::new(resource))
    }

    /// Creates a resource link [`Content`]
    #[inline]
    pub fn link(resource: impl Into<Resource>) -> Self {
        resource.into().into()
    }

    /// Creates a tool result [`Content`]
    #[inline]
    pub fn tool_result(id: String, resp: CallToolResponse) -> Self {
        Self::ToolResult(ToolResult::new(id, resp))
    }

    /// Creates a tool use [`Content`]
    #[inline]
    pub fn tool_use<N, Args>(name: N, args: Args) -> Self
    where
        N: Into<String>,
        Args: shared::IntoArgs,
    {
        Self::ToolUse(ToolUse::new(name, args))
    }

    /// Creates an empty [`Content`]
    #[inline]
    pub fn empty() -> Self {
        Self::Empty(EmptyContent)
    }

    /// Returns the type of the content.
    #[inline]
    pub fn get_type(&self) -> &str {
        match self {
            Self::Empty(_) => "empty",
            Self::Audio(_) => "audio",
            Self::Image(_) => "image",
            Self::Text(_) => "text",
            Self::ResourceLink(_) => "resource_link",
            Self::Resource(_) => "resource",
            Self::ToolUse(_) => "tool_use",
            Self::ToolResult(_) => "tool_result",
        }
    }

    /// Returns the content as a text content.
    #[inline]
    pub fn as_text(&self) -> Option<&TextContent> {
        match self {
            Self::Text(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as a deserialized struct
    #[inline]
    pub fn as_json<T: DeserializeOwned>(&self) -> Option<T> {
        match self {
            Self::Text(c) => serde_json::from_str(&c.text).ok(),
            _ => None,
        }
    }

    /// Returns the content as an audio content.
    #[inline]
    pub fn as_audio(&self) -> Option<&AudioContent> {
        match self {
            Self::Audio(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as an image.
    #[inline]
    pub fn as_image(&self) -> Option<&ImageContent> {
        match self {
            Self::Image(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as a resource link.
    #[inline]
    pub fn as_link(&self) -> Option<&ResourceLink> {
        match self {
            Self::ResourceLink(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as an embedded resource.
    #[inline]
    pub fn as_resource(&self) -> Option<&EmbeddedResource> {
        match self {
            Self::Resource(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as a tool use request.
    #[inline]
    pub fn as_tool(&self) -> Option<&ToolUse> {
        match self {
            Self::ToolUse(c) => Some(c),
            _ => None,
        }
    }

    /// Returns the content as a tool execution result.
    #[inline]
    pub fn as_result(&self) -> Option<&ToolResult> {
        match self {
            Self::ToolResult(c) => Some(c),
            _ => None,
        }
    }
}

impl TextContent {
    /// Creates a new [`TextContent`]
    #[inline]
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Sets annotations for the client
    pub fn with_annotations<F>(mut self, config: F) -> Self
    where
        F: FnOnce(Annotations) -> Annotations,
    {
        self.annotations = Some(config(Default::default()));
        self
    }
}

impl AudioContent {
    /// Creates a new [`AudioContent`]
    #[inline]
    pub fn new(data: impl Into<Bytes>) -> Self {
        Self {
            data: data.into(),
            mime: "audio/wav".into(),
            annotations: None,
            meta: None,
        }
    }

    /// Sets a mime type for the audio content
    pub fn with_mime(mut self, mime: impl Into<String>) -> Self {
        self.mime = mime.into();
        self
    }

    /// Sets annotations for the client
    pub fn with_annotations<F>(mut self, config: F) -> Self
    where
        F: FnOnce(Annotations) -> Annotations,
    {
        self.annotations = Some(config(Default::default()));
        self
    }

    /// Returns audio data as a slice of bytes
    pub fn as_slice(&self) -> &[u8] {
        &self.data
    }

    /// Turns this [`AudioContent`] into a chunked stream of bytes
    pub fn into_stream(self) -> impl futures_util::Stream<Item = Bytes> {
        futures_util::stream::unfold(self.data, |mut remaining_data| async move {
            if remaining_data.is_empty() {
                return None;
            }
            let chunk_size = remaining_data.len().min(CHUNK_SIZE);
            let chunk = remaining_data.split_to(chunk_size);
            Some((chunk, remaining_data))
        })
    }
}

impl ImageContent {
    /// Creates a new [`ImageContent`]
    #[inline]
    pub fn new(data: impl Into<Bytes>) -> Self {
        Self {
            data: data.into(),
            mime: "image/jpg".into(),
            annotations: None,
            meta: None,
        }
    }

    /// Sets a mime type for the image content
    pub fn with_mime(mut self, mime: impl Into<String>) -> Self {
        self.mime = mime.into();
        self
    }

    /// Sets annotations for the client
    pub fn with_annotations<F>(mut self, config: F) -> Self
    where
        F: FnOnce(Annotations) -> Annotations,
    {
        self.annotations = Some(config(Default::default()));
        self
    }

    /// Returns audio data as a slice of bytes
    pub fn as_slice(&self) -> &[u8] {
        &self.data
    }

    /// Turns this [`ImageContent`] into a chunked stream of bytes
    pub fn into_stream(self) -> impl futures_util::Stream<Item = Bytes> {
        futures_util::stream::unfold(self.data, |mut remaining_data| async move {
            if remaining_data.is_empty() {
                return None;
            }
            let chunk_size = remaining_data.len().min(CHUNK_SIZE);
            let chunk = remaining_data.split_to(chunk_size);
            Some((chunk, remaining_data))
        })
    }
}

impl ResourceLink {
    /// Creates a new [`ResourceLink`] content
    pub fn new(resource: impl Into<Resource>) -> Self {
        Self::from(resource.into())
    }

    /// Sets the [`ResourceLink`] icons
    pub fn with_icons(mut self, icons: impl IntoIterator<Item = Icon>) -> Self {
        self.icons = Some(icons.into_iter().collect());
        self
    }
}

impl EmbeddedResource {
    /// Creates a new [`EmbeddedResource`] content
    #[inline]
    pub fn new(resource: impl Into<ResourceContents>) -> Self {
        Self {
            resource: resource.into(),
            annotations: None,
            meta: None,
        }
    }
}

impl ToolUse {
    /// Creates a new [`ToolUse`] content
    #[inline]
    pub fn new<N, Args>(name: N, args: Args) -> Self
    where
        N: Into<String>,
        Args: shared::IntoArgs,
    {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            name: name.into(),
            input: args.into_args(),
            meta: None,
        }
    }
}

impl ToolResult {
    /// Creates a new [`ToolResult`] content
    #[inline]
    pub fn new(id: String, resp: CallToolResponse) -> Self {
        Self {
            tool_use_id: id,
            content: resp.content,
            struct_content: resp.struct_content,
            is_error: resp.is_error,
            meta: None,
        }
    }

    /// Creates the [`ToolResult`] with error
    #[inline]
    pub fn error(id: String, error: Error) -> Self {
        Self {
            tool_use_id: id,
            content: vec![Content::text(error.to_string())],
            struct_content: None,
            is_error: true,
            meta: None,
        }
    }
}

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

    #[derive(Deserialize)]
    struct Test {
        name: String,
        age: u32,
    }

    #[test]
    fn it_serializes_text_content_to_json() {
        let content = Content::text("hello world");
        let json = serde_json::to_string(&content).unwrap();

        assert_eq!(json, r#"{"type":"text","text":"hello world"}"#);
    }

    #[test]
    fn it_deserializes_text_content_to_json() {
        let json = r#"{"type":"text","text":"hello world"}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        assert_eq!(content.as_text().unwrap().text, "hello world");
    }

    #[test]
    fn it_deserializes_structures_text_content_to_json() {
        let json = r#"{"type":"text","text":"{\"name\":\"John\",\"age\":30}"}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        let user: Test = content.as_json().unwrap();

        assert_eq!(user.name, "John");
        assert_eq!(user.age, 30);
    }

    #[test]
    fn it_serializes_audio_content_to_json() {
        let content = Content::audio("hello world");
        let json = serde_json::to_string(&content).unwrap();

        assert_eq!(
            json,
            r#"{"type":"audio","data":"aGVsbG8gd29ybGQ=","mimeType":"audio/wav"}"#
        );
    }

    #[test]
    fn it_deserializes_audio_content_to_json() {
        let json = r#"{"type":"audio","data":"aGVsbG8gd29ybGQ=","mimeType":"audio/wav"}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        assert_eq!(
            String::from_utf8_lossy(content.as_audio().unwrap().as_slice()),
            "hello world"
        );
        assert_eq!(content.as_audio().unwrap().mime, "audio/wav");
    }

    #[test]
    fn it_serializes_image_content_to_json() {
        let content = Content::image("hello world");
        let json = serde_json::to_string(&content).unwrap();

        assert_eq!(
            json,
            r#"{"type":"image","data":"aGVsbG8gd29ybGQ=","mimeType":"image/jpg"}"#
        );
    }

    #[test]
    fn it_deserializes_image_content_to_json() {
        let json = r#"{"type":"image","data":"aGVsbG8gd29ybGQ=","mimeType":"image/jpg"}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        assert_eq!(
            String::from_utf8_lossy(content.as_image().unwrap().as_slice()),
            "hello world"
        );
        assert_eq!(content.as_image().unwrap().mime, "image/jpg");
    }

    #[test]
    #[cfg(feature = "server")]
    fn it_serializes_resource_content_to_json() {
        let content = Content::resource(
            ResourceContents::new("res://resource")
                .with_text("hello world")
                .with_title("some resource")
                .with_annotations(|a| a.with_audience("user").with_priority(1.0)),
        );

        let json = serde_json::to_string(&content).unwrap();

        assert_eq!(
            json,
            r#"{"type":"resource","resource":{"uri":"res://resource","text":"hello world","title":"some resource","mimeType":"text/plain","annotations":{"audience":["user"],"priority":1.0}}}"#
        );
    }

    #[test]
    #[cfg(feature = "server")]
    fn it_deserializes_resource_content_to_json() {
        use crate::types::Role;

        let json = r#"{"type":"resource","resource":{"uri":"res://resource","text":"hello world","title":"some resource","mimeType":"text/plain","annotations":{"audience":["user"],"priority":1.0}}}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        let res = &content.as_resource().unwrap().resource;

        assert_eq!(res.uri().to_string(), "res://resource");
        assert_eq!(res.mime().unwrap(), "text/plain");
        assert_eq!(res.text().unwrap(), "hello world");
        assert_eq!(res.title().unwrap(), "some resource");
        assert_eq!(res.annotations().unwrap().audience, [Role::User]);
        assert_eq!(res.annotations().unwrap().priority, 1.0);
    }

    #[test]
    #[cfg(feature = "server")]
    fn it_serializes_resource_link_content_to_json() {
        let content = Content::link(
            Resource::new("res://resource", "some resource")
                .with_title("some resource")
                .with_descr("some resource")
                .with_size(2)
                .with_annotations(|a| a.with_audience("user").with_priority(1.0)),
        );

        let json = serde_json::to_string(&content).unwrap();

        assert_eq!(
            json,
            r#"{"type":"resource_link","uri":"res://resource","name":"some resource","size":2,"title":"some resource","description":"some resource","annotations":{"audience":["user"],"priority":1.0}}"#
        );
    }

    #[test]
    #[cfg(feature = "server")]
    fn it_deserializes_resource_link_content_to_json() {
        use crate::types::Role;

        let json = r#"{"type":"resource_link","uri":"res://resource","name":"some resource","size":2,"title":"some resource","description":"some resource","annotations":{"audience":["user"],"priority":1.0}}"#;
        let content = serde_json::from_str::<Content>(json).unwrap();

        let res = content.as_link().unwrap();

        assert_eq!(res.uri.to_string(), "res://resource");
        assert_eq!(res.name, "some resource");
        assert_eq!(res.mime.as_deref(), None);
        assert_eq!(res.title.as_deref(), Some("some resource"));
        assert_eq!(res.annotations.as_ref().unwrap().audience, [Role::User]);
        assert_eq!(res.annotations.as_ref().unwrap().priority, 1.0);
    }

    #[tokio::test]
    async fn it_tests_audio_content_into_stream_single_chunk() {
        // Test data that will be smaller than CHUNK_SIZE
        let test_data = "hello world";
        let audio = AudioContent::new(test_data.as_bytes());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
        }

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
    }

    #[tokio::test]
    async fn it_tests_audio_content_into_stream_multiple_chunks() {
        // Create data larger than CHUNK_SIZE to test chunking
        let test_data = "hello world".repeat(1000); // Much larger than 8192 bytes
        let audio = AudioContent::new(test_data.clone());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();
        let mut chunk_count = 0;

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
            chunk_count += 1;
        }

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
        assert!(
            chunk_count > 1,
            "Should have multiple chunks for large data"
        );
    }

    #[tokio::test]
    async fn it_tests_audio_content_into_stream_empty() {
        let audio = AudioContent::new(Bytes::new());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let result = stream.next().await;

        assert!(result.is_none(), "Empty data should produce no chunks");
    }

    #[tokio::test]
    async fn it_tests_audio_content_into_stream_exact_chunk_size() {
        // Create data exactly CHUNK_SIZE bytes
        let test_data = "a".repeat(CHUNK_SIZE);
        let audio = AudioContent::new(test_data.clone());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();
        let mut chunk_count = 0;

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
            chunk_count += 1;
        }

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
        assert_eq!(
            chunk_count, 1,
            "Exactly CHUNK_SIZE data should produce one chunk"
        );
    }

    #[tokio::test]
    async fn it_tests_image_content_into_stream_single_chunk() {
        let test_data = "hello world";
        let image = ImageContent::new(test_data.as_bytes());

        let stream = image.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
        }

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
    }

    #[tokio::test]
    async fn it_tests_image_content_into_stream_multiple_chunks() {
        let test_data = "hello world".repeat(1000);
        let image = ImageContent::new(test_data.clone());

        let stream = image.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();
        let mut chunk_count = 0;

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
            chunk_count += 1;
        }

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
        assert!(
            chunk_count > 1,
            "Should have multiple chunks for large data"
        );
    }

    #[tokio::test]
    async fn it_tests_stream_chunk_sizes() {
        let test_data = "hello world".repeat(500); // Create data that will span multiple chunks
        let audio = AudioContent::new(test_data.clone());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let mut total_size = 0;
        let mut max_chunk_size = 0;

        while let Some(chunk) = stream.next().await {
            let chunk_size = chunk.len();
            total_size += chunk_size;
            max_chunk_size = max_chunk_size.max(chunk_size);

            // Each chunk should not exceed CHUNK_SIZE
            assert!(
                chunk_size <= CHUNK_SIZE,
                "Chunk size should not exceed CHUNK_SIZE"
            );
        }

        assert_eq!(total_size, test_data.len());
        assert!(max_chunk_size <= CHUNK_SIZE);
    }

    #[tokio::test]
    async fn it_tests_stream_preserves_binary_data() {
        let test_data: Vec<u8> = (0..=255u8).cycle().take(1000).collect();
        let audio = AudioContent::new(test_data.clone());

        let stream = audio.into_stream();
        let mut stream = Box::pin(stream);
        let mut collected_data = Vec::new();

        while let Some(chunk) = stream.next().await {
            collected_data.extend_from_slice(&chunk);
        }

        assert_eq!(collected_data, test_data);
    }

    #[tokio::test]
    async fn it_tests_audio_content_collect_alternative() {
        let test_data = "hello world";
        let audio = AudioContent::new(test_data.as_bytes());

        let stream = audio.into_stream();
        let chunks: Vec<_> = tokio_stream::StreamExt::collect::<Vec<_>>(stream).await;

        let collected_data: Vec<u8> = chunks.into_iter().flatten().collect();

        let result_string = String::from_utf8(collected_data).expect("Should be valid UTF-8");
        assert_eq!(result_string, test_data);
    }

    #[test]
    fn it_tests_audio_content_serialization() {
        let audio = AudioContent::new("hello world");

        let json = serde_json::to_string(&audio).expect("Should serialize");
        let deserialized: AudioContent = serde_json::from_str(&json).expect("Should deserialize");

        assert_eq!(audio.data, deserialized.data);
        assert_eq!(audio.mime, deserialized.mime);
    }

    #[test]
    fn it_tests_image_content_serialization() {
        let audio = ImageContent::new("hello world");

        let json = serde_json::to_string(&audio).expect("Should serialize");
        let deserialized: ImageContent = serde_json::from_str(&json).expect("Should deserialize");

        assert_eq!(audio.data, deserialized.data);
        assert_eq!(audio.mime, deserialized.mime);
    }
}