pmcp 2.2.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! Sampling types for MCP protocol.
//!
//! This module contains sampling-related types including message creation,
//! model preferences, token usage, and tool-use extensions (MCP 2025-11-25).

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

use super::content::Role;

/// Model preferences for sampling.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ModelPreferences {
    /// Hints for model selection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hints: Option<Vec<ModelHint>>,
    /// Cost priority (0-1, higher = more important)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cost_priority: Option<f64>,
    /// Speed priority (0-1, higher = more important)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed_priority: Option<f64>,
    /// Intelligence priority (0-1, higher = more important)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intelligence_priority: Option<f64>,
}

impl ModelPreferences {
    /// Create empty model preferences.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the cost priority (0-1, higher = more important).
    pub fn with_cost_priority(mut self, priority: f64) -> Self {
        self.cost_priority = Some(priority);
        self
    }

    /// Set the speed priority (0-1, higher = more important).
    pub fn with_speed_priority(mut self, priority: f64) -> Self {
        self.speed_priority = Some(priority);
        self
    }

    /// Set the intelligence priority (0-1, higher = more important).
    pub fn with_intelligence_priority(mut self, priority: f64) -> Self {
        self.intelligence_priority = Some(priority);
        self
    }

    /// Set model selection hints.
    pub fn with_hints(mut self, hints: Vec<ModelHint>) -> Self {
        self.hints = Some(hints);
        self
    }
}

/// Model hint for sampling.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ModelHint {
    /// Model name/identifier hint
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl ModelHint {
    /// Create a model hint with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: Some(name.into()),
        }
    }
}

/// Tool choice configuration for sampling (MCP 2025-11-25).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ToolChoice {
    /// Tool choice mode
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<ToolChoiceMode>,
}

impl ToolChoice {
    /// Create a tool choice with auto mode (model decides).
    pub fn auto() -> Self {
        Self {
            mode: Some(ToolChoiceMode::Auto),
        }
    }

    /// Create a tool choice with required mode (model must use a tool).
    pub fn required() -> Self {
        Self {
            mode: Some(ToolChoiceMode::Required),
        }
    }

    /// Create a tool choice with none mode (model must not use tools).
    pub fn none() -> Self {
        Self {
            mode: Some(ToolChoiceMode::None),
        }
    }
}

/// Tool choice mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ToolChoiceMode {
    /// Model decides whether to use tools
    Auto,
    /// Model must use a tool
    Required,
    /// Model must not use tools
    None,
}

/// Content in a sampling message or sampling result (MCP 2025-11-25).
///
/// Represents the expanded content type that includes standard content
/// plus tool use and tool result content for multi-turn tool interactions.
/// Used in both `SamplingMessage.content` and `CreateMessageResultWithTools.content`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SamplingMessageContent {
    /// Text content
    #[serde(rename = "text", rename_all = "camelCase")]
    Text {
        /// The text content
        text: String,
        /// Optional metadata
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Map<String, Value>>,
    },
    /// Image content
    #[serde(rename = "image", rename_all = "camelCase")]
    Image {
        /// Base64-encoded image data
        data: String,
        /// Image MIME type
        mime_type: String,
        /// Optional metadata
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Map<String, Value>>,
    },
    /// Audio content
    #[serde(rename = "audio", rename_all = "camelCase")]
    Audio {
        /// Base64-encoded audio data
        data: String,
        /// Audio MIME type
        mime_type: String,
        /// Optional metadata
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Map<String, Value>>,
    },
    /// Tool use content -- model wants to call a tool
    #[serde(rename = "tool_use", rename_all = "camelCase")]
    ToolUse {
        /// Tool name
        name: String,
        /// Tool use ID for correlation
        id: String,
        /// Tool input arguments
        input: Value,
        /// Optional metadata
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Map<String, Value>>,
    },
    /// Tool result content -- result of a tool call
    #[serde(rename = "tool_result", rename_all = "camelCase")]
    ToolResult {
        /// Correlates with `tool_use` id
        tool_use_id: String,
        /// Result content items
        content: Vec<super::content::Content>,
        /// Structured result data
        #[serde(skip_serializing_if = "Option::is_none")]
        structured_content: Option<Value>,
        /// Whether the tool call was an error
        #[serde(skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
        /// Optional metadata
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<serde_json::Map<String, Value>>,
    },
}

/// Create message parameters (for server requests).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CreateMessageParams {
    /// Messages to sample from
    pub messages: Vec<SamplingMessage>,
    /// Optional model preferences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_preferences: Option<ModelPreferences>,
    /// Optional system prompt
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    /// Include context from MCP
    #[serde(default)]
    pub include_context: IncludeContext,
    /// Temperature (0-1)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f64>,
    /// Maximum tokens to generate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_tokens: Option<u32>,
    /// Stop sequences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    /// Additional model-specific parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// Tool definitions available to the model (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<super::tools::ToolInfo>>,
    /// Tool choice configuration (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,
}

impl CreateMessageParams {
    /// Create message parameters with the given messages.
    ///
    /// All optional fields default to `None`, `include_context` defaults
    /// to [`IncludeContext::None`].
    pub fn new(messages: Vec<SamplingMessage>) -> Self {
        Self {
            messages,
            model_preferences: None,
            system_prompt: None,
            include_context: IncludeContext::default(),
            temperature: None,
            max_tokens: None,
            stop_sequences: None,
            metadata: None,
            tools: None,
            tool_choice: None,
        }
    }

    /// Set model preferences.
    pub fn with_model_preferences(mut self, prefs: ModelPreferences) -> Self {
        self.model_preferences = Some(prefs);
        self
    }

    /// Set the system prompt.
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.system_prompt = Some(prompt.into());
        self
    }

    /// Set the temperature (0-1).
    pub fn with_temperature(mut self, temp: f64) -> Self {
        self.temperature = Some(temp);
        self
    }

    /// Set the maximum number of tokens to generate.
    pub fn with_max_tokens(mut self, tokens: u32) -> Self {
        self.max_tokens = Some(tokens);
        self
    }

    /// Set tool definitions available to the model.
    pub fn with_tools(mut self, tools: Vec<super::tools::ToolInfo>) -> Self {
        self.tools = Some(tools);
        self
    }

    /// Set the tool choice configuration.
    pub fn with_tool_choice(mut self, choice: ToolChoice) -> Self {
        self.tool_choice = Some(choice);
        self
    }
}

/// Create message result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CreateMessageResult {
    /// The content generated by the model
    pub content: super::content::Content,
    /// The model used for generation
    pub model: String,
    /// Token usage information
    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage: Option<TokenUsage>,
    /// Stop reason
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
}

impl CreateMessageResult {
    /// Create a message result with content and model.
    ///
    /// `usage` and `stop_reason` default to `None`.
    pub fn new(content: super::content::Content, model: impl Into<String>) -> Self {
        Self {
            content,
            model: model.into(),
            usage: None,
            stop_reason: None,
        }
    }

    /// Set the token usage information.
    pub fn with_usage(mut self, usage: TokenUsage) -> Self {
        self.usage = Some(usage);
        self
    }

    /// Set the stop reason.
    pub fn with_stop_reason(mut self, reason: impl Into<String>) -> Self {
        self.stop_reason = Some(reason.into());
        self
    }
}

/// Sampling result with tool use support (MCP 2025-11-25).
///
/// Extends `CreateMessageResult` with array content that can include
/// tool use and tool result items alongside standard content.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CreateMessageResultWithTools {
    /// The model used for sampling
    pub model: String,
    /// Reason the model stopped generating
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
    /// Role of the generated message
    pub role: Role,
    /// Array of content items (text, image, audio, `tool_use`, `tool_result`)
    pub content: Vec<SamplingMessageContent>,
    /// Optional metadata
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<serde_json::Map<String, Value>>,
}

impl CreateMessageResultWithTools {
    /// Create a sampling result with tool support.
    ///
    /// `stop_reason` and `meta` default to `None`.
    pub fn new(model: impl Into<String>, role: Role, content: Vec<SamplingMessageContent>) -> Self {
        Self {
            model: model.into(),
            stop_reason: None,
            role,
            content,
            meta: None,
        }
    }

    /// Set the stop reason.
    pub fn with_stop_reason(mut self, reason: impl Into<String>) -> Self {
        self.stop_reason = Some(reason.into());
        self
    }

    /// Set metadata.
    pub fn with_meta(mut self, meta: serde_json::Map<String, Value>) -> Self {
        self.meta = Some(meta);
        self
    }
}

/// Token usage information.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct TokenUsage {
    /// Input tokens used
    pub input_tokens: u32,
    /// Output tokens generated
    pub output_tokens: u32,
    /// Total tokens used
    pub total_tokens: u32,
}

impl TokenUsage {
    /// Create token usage information.
    pub fn new(input_tokens: u32, output_tokens: u32, total_tokens: u32) -> Self {
        Self {
            input_tokens,
            output_tokens,
            total_tokens,
        }
    }
}

/// Sampling message.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SamplingMessage {
    /// Message role
    pub role: Role,
    /// Message content (expanded to support tool use in MCP 2025-11-25)
    pub content: SamplingMessageContent,
}

impl SamplingMessage {
    /// Create a sampling message.
    pub fn new(role: Role, content: SamplingMessageContent) -> Self {
        Self { role, content }
    }
}

/// Context to include in sampling.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub enum IncludeContext {
    /// Include context from all connected servers
    AllServers,
    /// Include no additional context
    #[default]
    None,
    /// Include context from this server only
    ThisServer,
}

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

    #[test]
    fn include_context_serializes_correctly() {
        assert_eq!(
            serde_json::to_value(IncludeContext::AllServers).unwrap(),
            "allServers"
        );
        assert_eq!(serde_json::to_value(IncludeContext::None).unwrap(), "none");
        assert_eq!(
            serde_json::to_value(IncludeContext::ThisServer).unwrap(),
            "thisServer"
        );
    }

    #[test]
    fn include_context_deserializes_correctly() {
        let all: IncludeContext = serde_json::from_value(json!("allServers")).unwrap();
        assert!(matches!(all, IncludeContext::AllServers));

        let none: IncludeContext = serde_json::from_value(json!("none")).unwrap();
        assert!(matches!(none, IncludeContext::None));

        let this: IncludeContext = serde_json::from_value(json!("thisServer")).unwrap();
        assert!(matches!(this, IncludeContext::ThisServer));
    }

    #[test]
    fn tool_choice_serialization() {
        let choice = ToolChoice::auto();
        let json = serde_json::to_value(&choice).unwrap();
        assert_eq!(json["mode"], "auto");

        let choice2 = ToolChoice::required();
        let json2 = serde_json::to_value(&choice2).unwrap();
        assert_eq!(json2["mode"], "required");

        let choice3 = ToolChoice::none();
        let json3 = serde_json::to_value(&choice3).unwrap();
        assert_eq!(json3["mode"], "none");
    }

    #[test]
    fn create_message_result_with_tools_roundtrip() {
        let result = CreateMessageResultWithTools::new(
            "claude-3",
            Role::Assistant,
            vec![
                SamplingMessageContent::Text {
                    text: "I'll call the tool.".to_string(),
                    meta: None,
                },
                SamplingMessageContent::ToolUse {
                    name: "search".to_string(),
                    id: "tu-1".to_string(),
                    input: json!({"query": "rust"}),
                    meta: None,
                },
            ],
        )
        .with_stop_reason("end_turn");

        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["model"], "claude-3");
        assert_eq!(json["role"], "assistant");
        assert_eq!(json["content"].as_array().unwrap().len(), 2);
        assert_eq!(json["content"][0]["type"], "text");
        assert_eq!(json["content"][1]["type"], "tool_use");
        assert_eq!(json["content"][1]["name"], "search");

        let roundtrip: CreateMessageResultWithTools = serde_json::from_value(json).unwrap();
        assert_eq!(roundtrip.model, "claude-3");
        assert_eq!(roundtrip.content.len(), 2);
    }

    #[test]
    fn sampling_message_with_tool_use_content() {
        let msg = SamplingMessage::new(
            Role::Assistant,
            SamplingMessageContent::ToolUse {
                name: "calculate".to_string(),
                id: "tu-2".to_string(),
                input: json!({"expression": "2+2"}),
                meta: None,
            },
        );
        let json = serde_json::to_value(&msg).unwrap();
        assert_eq!(json["role"], "assistant");
        assert_eq!(json["content"]["type"], "tool_use");
        assert_eq!(json["content"]["name"], "calculate");

        let roundtrip: SamplingMessage = serde_json::from_value(json).unwrap();
        match roundtrip.content {
            SamplingMessageContent::ToolUse { name, id, .. } => {
                assert_eq!(name, "calculate");
                assert_eq!(id, "tu-2");
            },
            _ => panic!("Expected ToolUse content"),
        }
    }

    #[test]
    fn sampling_message_content_text_roundtrip() {
        let content = SamplingMessageContent::Text {
            text: "hello".to_string(),
            meta: None,
        };
        let json = serde_json::to_value(&content).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "hello");

        let roundtrip: SamplingMessageContent = serde_json::from_value(json).unwrap();
        match roundtrip {
            SamplingMessageContent::Text { text, .. } => assert_eq!(text, "hello"),
            _ => panic!("Expected Text"),
        }
    }
}