turbomcp-types 3.6.0

Core types for TurboMCP - the foundation of the MCP SDK
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
//! Result types for MCP operations.
//!
//! This module provides ergonomic result types for the three core MCP operations:
//! - `ToolResult` - Results from tool invocations
//! - `ResourceResult` - Results from resource reads
//! - `PromptResult` - Results from prompt retrieval

use serde::{Deserialize, Serialize};
use serde_json::Value;

#[cfg(not(feature = "std"))]
use alloc::{collections::BTreeMap as HashMap, string::String, vec, vec::Vec};
#[cfg(feature = "std")]
use std::collections::HashMap;

use crate::content::{
    BlobResourceContents, Content, Message, ResourceContents, Role, TextResourceContents,
};

/// Return `value` only if it may legally occupy `structuredContent`.
///
/// Every MCP schema version this SDK speaks types the field as
/// `{ [key: string]: unknown }`, so a scalar or an array there is invalid and
/// strict clients reject the whole result. Callers pair this with a text block
/// that carries the value regardless of its JSON shape.
///
/// # Example
///
/// ```
/// use turbomcp_types::structured_content_if_object;
///
/// assert!(structured_content_if_object(serde_json::json!({"a": 1})).is_some());
/// assert!(structured_content_if_object(serde_json::json!([1, 2])).is_none());
/// ```
#[must_use]
pub fn structured_content_if_object(value: Value) -> Option<Value> {
    value.is_object().then_some(value)
}

/// The `_meta` map carried by every MCP result type.
///
/// Aliased because the underlying map differs by target — `std::collections::HashMap`
/// with `std`, `alloc::collections::BTreeMap` without — so callers that build a
/// `_meta` map can name one type and stay portable.
pub type MetaMap = HashMap<String, Value>;

/// Result from calling a tool.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ToolResult {
    /// Content blocks in the result
    pub content: Vec<Content>,
    /// Whether this result represents an error
    #[serde(rename = "isError", skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
    /// Structured content conforming to the tool's output schema
    #[serde(rename = "structuredContent", skip_serializing_if = "Option::is_none")]
    pub structured_content: Option<Value>,
    /// Extension metadata
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, Value>>,
}

impl ToolResult {
    /// Create a text result.
    #[must_use]
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            content: vec![Content::text(text)],
            ..Default::default()
        }
    }

    /// Create an error result.
    #[must_use]
    pub fn error(text: impl Into<String>) -> Self {
        Self {
            content: vec![Content::text(text)],
            is_error: Some(true),
            ..Default::default()
        }
    }

    /// Create a JSON result with structured content.
    ///
    /// The value is always rendered into a text block. It additionally
    /// populates `structuredContent` when it serializes to a JSON **object** —
    /// see [`structured_content_if_object`] for why arrays and scalars cannot
    /// go there.
    pub fn json<T: Serialize>(value: &T) -> Result<Self, serde_json::Error> {
        let structured = serde_json::to_value(value)?;
        let text = serde_json::to_string_pretty(&structured)?;
        Ok(Self {
            content: vec![Content::text(text)],
            structured_content: structured_content_if_object(structured),
            ..Default::default()
        })
    }

    /// Create an empty result (no content).
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Check if this result represents an error.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.is_error.unwrap_or(false)
    }

    /// Add structured content to the result.
    ///
    /// `structuredContent` is typed `{ [key: string]: unknown }` in every MCP
    /// revision this SDK speaks, so a non-object value is dropped rather than
    /// written — an array or scalar there makes the whole result invalid, and
    /// strict clients reject it. This matches [`Self::json`] and the `Json<T>`
    /// handler wrapper, which apply the same guard.
    ///
    /// Use [`Self::with_content`] to carry a non-object payload as text.
    #[must_use]
    pub fn with_structured<T: Serialize>(mut self, value: &T) -> Self {
        self.structured_content = serde_json::to_value(value)
            .ok()
            .and_then(structured_content_if_object);
        self
    }

    /// Add additional content to the result.
    #[must_use]
    pub fn with_content(mut self, content: Content) -> Self {
        self.content.push(content);
        self
    }

    /// Add image content to the result.
    #[must_use]
    pub fn with_image(self, data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        self.with_content(Content::image(data, mime_type))
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: HashMap<String, Value>) -> Self {
        self.meta = Some(meta);
        self
    }

    /// Get the first text content if present.
    #[must_use]
    pub fn first_text(&self) -> Option<&str> {
        self.content.first().and_then(|c| c.as_text())
    }
}

/// Result from reading a resource.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct ResourceResult {
    /// Resource contents
    pub contents: Vec<ResourceContents>,
    /// Extension metadata
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, Value>>,
}

impl ResourceResult {
    /// Create a text resource result.
    #[must_use]
    pub fn text(uri: impl Into<String>, content: impl Into<String>) -> Self {
        Self {
            contents: vec![ResourceContents::Text(TextResourceContents {
                uri: uri.into(),
                mime_type: Some("text/plain".into()),
                text: content.into(),
                meta: None,
            })],
            ..Default::default()
        }
    }

    /// Override the MIME type on every entry of this result.
    ///
    /// The constructors guess (`text/plain` for text, `application/octet-stream`
    /// for blobs) because they only see the body. A `#[resource]` that declares
    /// `mime_type = "application/json"` advertises that in `resources/list`, so
    /// the read must agree — otherwise the catalogue and the content describe
    /// the resource differently and a client that trusts the listing
    /// mis-parses the body.
    #[must_use]
    pub fn with_mime_type(mut self, mime_type: impl Into<String>) -> Self {
        let mime_type = mime_type.into();
        for entry in &mut self.contents {
            match entry {
                ResourceContents::Text(text) => text.mime_type = Some(mime_type.clone()),
                ResourceContents::Blob(blob) => blob.mime_type = Some(mime_type.clone()),
            }
        }
        self
    }

    /// Create a JSON resource result.
    pub fn json<T: Serialize>(
        uri: impl Into<String>,
        value: &T,
    ) -> Result<Self, serde_json::Error> {
        Ok(Self {
            contents: vec![ResourceContents::Text(TextResourceContents {
                uri: uri.into(),
                mime_type: Some("application/json".into()),
                text: serde_json::to_string_pretty(value)?,
                meta: None,
            })],
            ..Default::default()
        })
    }

    /// Create a binary resource result.
    #[must_use]
    pub fn binary(
        uri: impl Into<String>,
        data: impl Into<String>,
        mime_type: impl Into<String>,
    ) -> Self {
        Self {
            contents: vec![ResourceContents::Blob(BlobResourceContents {
                uri: uri.into(),
                mime_type: Some(mime_type.into()),
                blob: data.into(),
                meta: None,
            })],
            ..Default::default()
        }
    }

    /// Create an empty resource result.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Add additional content to the result.
    #[must_use]
    pub fn with_content(mut self, content: ResourceContents) -> Self {
        self.contents.push(content);
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: HashMap<String, Value>) -> Self {
        self.meta = Some(meta);
        self
    }

    /// Get the first content's text if present.
    #[must_use]
    pub fn first_text(&self) -> Option<&str> {
        self.contents.first().and_then(|c| match c {
            ResourceContents::Text(t) => Some(t.text.as_str()),
            ResourceContents::Blob(_) => None,
        })
    }
}

/// Result from getting a prompt.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub struct PromptResult {
    /// Description of this prompt result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Messages in the prompt
    pub messages: Vec<Message>,
    /// Extension metadata
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, Value>>,
}

impl PromptResult {
    /// Create a prompt result with messages.
    #[must_use]
    pub fn new(messages: Vec<Message>) -> Self {
        Self {
            messages,
            ..Default::default()
        }
    }

    /// Create a prompt with a single user message.
    #[must_use]
    pub fn user(text: impl Into<String>) -> Self {
        Self::new(vec![Message::user(text)])
    }

    /// Create a prompt with a single assistant message.
    #[must_use]
    pub fn assistant(text: impl Into<String>) -> Self {
        Self::new(vec![Message::assistant(text)])
    }

    /// Create an empty prompt.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }

    /// Add a description to the prompt.
    #[must_use]
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    /// Add a user message to the prompt.
    #[must_use]
    pub fn add_user(mut self, text: impl Into<String>) -> Self {
        self.messages.push(Message::user(text));
        self
    }

    /// Add an assistant message to the prompt.
    #[must_use]
    pub fn add_assistant(mut self, text: impl Into<String>) -> Self {
        self.messages.push(Message::assistant(text));
        self
    }

    /// Add a message with a specific role.
    #[must_use]
    pub fn add_message(mut self, role: Role, text: impl Into<String>) -> Self {
        self.messages.push(Message::new(role, Content::text(text)));
        self
    }

    /// Set metadata.
    #[must_use]
    pub fn with_meta(mut self, meta: HashMap<String, Value>) -> Self {
        self.meta = Some(meta);
        self
    }

    /// Check if the prompt is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    /// Get the number of messages.
    #[must_use]
    pub fn len(&self) -> usize {
        self.messages.len()
    }
}

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

    #[test]
    fn test_tool_result_text() {
        let result = ToolResult::text("Hello");
        assert!(!result.is_error());
        assert_eq!(result.first_text(), Some("Hello"));
    }

    #[test]
    fn test_tool_result_error() {
        let result = ToolResult::error("Failed");
        assert!(result.is_error());
        assert_eq!(result.first_text(), Some("Failed"));
    }

    #[test]
    fn test_tool_result_json() {
        let data = serde_json::json!({"key": "value"});
        let result = ToolResult::json(&data).unwrap();
        assert!(result.structured_content.is_some());
        assert!(!result.is_error());
    }

    #[test]
    fn test_resource_result_text() {
        let result = ResourceResult::text("file:///test.txt", "content");
        assert_eq!(result.first_text(), Some("content"));
        match &result.contents[0] {
            ResourceContents::Text(t) => assert_eq!(t.uri, "file:///test.txt"),
            _ => panic!("Expected text resource contents"),
        }
    }

    #[test]
    fn test_resource_result_binary() {
        let result = ResourceResult::binary("file:///img.png", "base64data", "image/png");
        match &result.contents[0] {
            ResourceContents::Blob(b) => {
                assert_eq!(b.blob, "base64data");
                assert_eq!(b.mime_type, Some("image/png".into()));
            }
            _ => panic!("Expected blob resource contents"),
        }
    }

    #[test]
    fn test_prompt_result_builder() {
        let result = PromptResult::user("Hello")
            .add_assistant("Hi there")
            .add_user("How are you?")
            .with_description("Greeting");

        assert_eq!(result.len(), 3);
        assert_eq!(result.description, Some("Greeting".into()));
        assert!(result.messages[0].is_user());
        assert!(result.messages[1].is_assistant());
        assert!(result.messages[2].is_user());
    }

    #[test]
    fn test_prompt_result_serde() {
        let result = PromptResult::user("Test").with_description("A test prompt");
        let json = serde_json::to_string(&result).unwrap();
        let parsed: PromptResult = serde_json::from_str(&json).unwrap();
        assert_eq!(result, parsed);
    }
}