rmcp 2.0.0

Rust SDK for Model Context Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Content types that flow between agents, tools, prompts, and LLMs.
//!
//! The core union is [`ContentBlock`] (text | image | audio | resource_link | resource),
//! matching the MCP 2025-11-25 `ContentBlock` definition. Each variant carries optional
//! [`Annotations`] and `_meta` inline.
//!
//! [`SamplingMessageContentBlock`] extends the union with `tool_use` and `tool_result`
//! variants for sampling messages (SEP-1577).

// ToolUseContent/ToolResultContent are SEP-2577-deprecated; internal references are expected.
#![expect(deprecated)]
use serde::{Deserialize, Serialize};
use serde_json::json;

use super::{Annotations, Meta, resource::ResourceContents};

// ---------------------------------------------------------------------------
// Flat content structs
// ---------------------------------------------------------------------------

/// Text content block (spec `TextContent`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct TextContent {
    /// The text content of the message.
    pub text: String,
    /// Optional protocol-level metadata for this content block.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    /// Optional annotations describing how the client should use this content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
}

impl TextContent {
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            meta: None,
            annotations: None,
        }
    }

    pub fn with_meta(mut self, meta: Meta) -> Self {
        self.meta = Some(meta);
        self
    }

    pub fn with_annotations(mut self, annotations: Annotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

/// Image content with base64-encoded data (spec `ImageContent`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct ImageContent {
    /// The base64-encoded image data.
    pub data: String,
    /// The MIME type of the image (e.g. `image/png`).
    pub mime_type: String,
    /// Optional protocol-level metadata for this content block.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    /// Optional annotations describing how the client should use this content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
}

impl ImageContent {
    pub fn new(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self {
            data: data.into(),
            mime_type: mime_type.into(),
            meta: None,
            annotations: None,
        }
    }

    pub fn with_meta(mut self, meta: Meta) -> Self {
        self.meta = Some(meta);
        self
    }

    pub fn with_annotations(mut self, annotations: Annotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

/// Audio content with base64-encoded data (spec `AudioContent`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct AudioContent {
    /// The base64-encoded audio data.
    pub data: String,
    /// The MIME type of the audio (e.g. `audio/wav`).
    pub mime_type: String,
    /// Optional protocol-level metadata for this content block.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    /// Optional annotations describing how the client should use this content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
}

impl AudioContent {
    pub fn new(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self {
            data: data.into(),
            mime_type: mime_type.into(),
            meta: None,
            annotations: None,
        }
    }

    pub fn with_meta(mut self, meta: Meta) -> Self {
        self.meta = Some(meta);
        self
    }

    pub fn with_annotations(mut self, annotations: Annotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

/// Embedded resource content (spec `EmbeddedResource`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub struct EmbeddedResource {
    /// The embedded resource contents (text or blob).
    pub resource: ResourceContents,
    /// Optional protocol-level metadata for this content block.
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    /// Optional annotations describing how the client should use this content.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
}

impl EmbeddedResource {
    pub fn new(resource: ResourceContents) -> Self {
        Self {
            resource,
            meta: None,
            annotations: None,
        }
    }

    pub fn get_text(&self) -> String {
        match &self.resource {
            ResourceContents::TextResourceContents { text, .. } => text.clone(),
            _ => String::new(),
        }
    }

    pub fn with_meta(mut self, meta: Meta) -> Self {
        self.meta = Some(meta);
        self
    }

    pub fn with_annotations(mut self, annotations: Annotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

/// Tool call request from assistant (SEP-1577).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
#[deprecated(
    since = "2.0.0",
    note = "Sampling is deprecated by SEP-2577 and will be removed in a future release. See https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577"
)]
pub struct ToolUseContent {
    pub id: String,
    pub name: String,
    pub input: super::JsonObject,
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
}

/// Tool execution result in user message (SEP-1577).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
#[deprecated(
    since = "2.0.0",
    note = "Sampling is deprecated by SEP-2577 and will be removed in a future release. See https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577"
)]
pub struct ToolResultContent {
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<Meta>,
    pub tool_use_id: String,
    pub content: Vec<ContentBlock>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub structured_content: Option<super::JsonObject>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
}

impl ToolUseContent {
    pub fn new(id: impl Into<String>, name: impl Into<String>, input: super::JsonObject) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            input,
            meta: None,
        }
    }
}

impl ToolResultContent {
    pub fn new(tool_use_id: impl Into<String>, content: Vec<ContentBlock>) -> Self {
        Self {
            meta: None,
            tool_use_id: tool_use_id.into(),
            content,
            structured_content: None,
            is_error: None,
        }
    }

    pub fn error(tool_use_id: impl Into<String>, content: Vec<ContentBlock>) -> Self {
        Self {
            meta: None,
            tool_use_id: tool_use_id.into(),
            content,
            structured_content: None,
            is_error: Some(true),
        }
    }
}

// ---------------------------------------------------------------------------
// ContentBlock — the unified content union (spec `ContentBlock`)
// ---------------------------------------------------------------------------

/// Unified content block union (spec `ContentBlock`).
///
/// `text | image | audio | resource_link | resource`
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[non_exhaustive]
pub enum ContentBlock {
    Text(TextContent),
    Image(ImageContent),
    Audio(AudioContent),
    Resource(EmbeddedResource),
    ResourceLink(super::resource::Resource),
}

impl ContentBlock {
    pub fn json<S: Serialize>(json: S) -> Result<Self, crate::ErrorData> {
        let json = serde_json::to_string(&json).map_err(|e| {
            crate::ErrorData::internal_error(
                "fail to serialize response to json",
                Some(json!(
                    {"reason": e.to_string()}
                )),
            )
        })?;
        Ok(ContentBlock::text(json))
    }

    pub fn text(text: impl Into<String>) -> Self {
        ContentBlock::Text(TextContent::new(text))
    }

    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        ContentBlock::Image(ImageContent::new(data, mime_type))
    }

    pub fn audio(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        ContentBlock::Audio(AudioContent::new(data, mime_type))
    }

    pub fn resource(resource: ResourceContents) -> Self {
        ContentBlock::Resource(EmbeddedResource::new(resource))
    }

    pub fn embedded_text(uri: impl Into<String>, content: impl Into<String>) -> Self {
        ContentBlock::Resource(EmbeddedResource::new(
            ResourceContents::TextResourceContents {
                uri: uri.into(),
                mime_type: Some("text".to_string()),
                text: content.into(),
                meta: None,
            },
        ))
    }

    pub fn resource_link(resource: super::resource::Resource) -> Self {
        ContentBlock::ResourceLink(resource)
    }

    pub fn as_text(&self) -> Option<&TextContent> {
        match self {
            ContentBlock::Text(text) => Some(text),
            _ => None,
        }
    }

    pub fn as_image(&self) -> Option<&ImageContent> {
        match self {
            ContentBlock::Image(image) => Some(image),
            _ => None,
        }
    }

    pub fn as_resource(&self) -> Option<&EmbeddedResource> {
        match self {
            ContentBlock::Resource(resource) => Some(resource),
            _ => None,
        }
    }

    pub fn as_resource_link(&self) -> Option<&super::resource::Resource> {
        match self {
            ContentBlock::ResourceLink(link) => Some(link),
            _ => None,
        }
    }

    pub fn as_audio(&self) -> Option<&AudioContent> {
        match self {
            ContentBlock::Audio(audio) => Some(audio),
            _ => None,
        }
    }
}

// ---------------------------------------------------------------------------
// JsonContent (unchanged)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonContent<S: Serialize>(S);

// ---------------------------------------------------------------------------
// IntoContents
// ---------------------------------------------------------------------------

/// Types that can be converted into a list of content blocks.
pub trait IntoContents {
    fn into_contents(self) -> Vec<ContentBlock>;
}

impl IntoContents for ContentBlock {
    fn into_contents(self) -> Vec<ContentBlock> {
        vec![self]
    }
}

impl IntoContents for String {
    fn into_contents(self) -> Vec<ContentBlock> {
        vec![ContentBlock::text(self)]
    }
}

impl IntoContents for () {
    fn into_contents(self) -> Vec<ContentBlock> {
        vec![]
    }
}

#[cfg(test)]
mod tests {
    use serde_json;

    use super::*;

    #[test]
    fn test_image_content_serialization() {
        let image = ImageContent::new("base64data", "image/png");
        let json = serde_json::to_string(&image).unwrap();
        assert!(json.contains("mimeType"));
        assert!(!json.contains("mime_type"));
    }

    #[test]
    fn test_audio_content_serialization() {
        let audio = AudioContent::new("base64audiodata", "audio/wav");
        let json = serde_json::to_string(&audio).unwrap();
        assert!(json.contains("mimeType"));
        assert!(!json.contains("mime_type"));
    }

    #[test]
    fn test_audio_content_has_meta() {
        let audio = AudioContent::new("data", "audio/wav").with_meta(Meta::default());
        let json = serde_json::to_value(&audio).unwrap();
        assert!(json.get("_meta").is_some());
    }

    #[test]
    fn test_resource_link_serialization() {
        use super::super::resource::Resource;

        let resource_link = ContentBlock::ResourceLink(Resource {
            uri: "file:///test.txt".to_string(),
            name: "test.txt".to_string(),
            title: None,
            description: Some("A test file".to_string()),
            mime_type: Some("text/plain".to_string()),
            size: Some(100),
            icons: None,
            meta: None,
            annotations: None,
        });

        let json = serde_json::to_string(&resource_link).unwrap();
        assert!(json.contains("\"type\":\"resource_link\""));
        assert!(json.contains("\"uri\":\"file:///test.txt\""));
        assert!(json.contains("\"name\":\"test.txt\""));
    }

    #[test]
    fn test_resource_link_deserialization() {
        let json = r#"{
            "type": "resource_link",
            "uri": "file:///example.txt",
            "name": "example.txt",
            "description": "Example file",
            "mimeType": "text/plain"
        }"#;

        let content: ContentBlock = serde_json::from_str(json).unwrap();

        if let ContentBlock::ResourceLink(resource) = content {
            assert_eq!(resource.uri, "file:///example.txt");
            assert_eq!(resource.name, "example.txt");
            assert_eq!(resource.description, Some("Example file".to_string()));
            assert_eq!(resource.mime_type, Some("text/plain".to_string()));
        } else {
            panic!("Expected ResourceLink variant");
        }
    }

    #[test]
    fn test_content_block_text_with_annotations() {
        let block = ContentBlock::Text(
            TextContent::new("hello").with_annotations(Annotations::default().with_priority(0.8)),
        );
        let json = serde_json::to_value(&block).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "hello");
        assert_eq!(json["annotations"]["priority"], 0.8_f32);
    }
}