pmcp 2.4.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
//! MCP Task protocol types (2025-11-25).
//!
//! This module contains the wire types for MCP Tasks as defined
//! in the 2025-11-25 protocol version.

use serde::{Deserialize, Serialize};

/// Related task metadata key per MCP spec.
pub const RELATED_TASK_META_KEY: &str = "io.modelcontextprotocol/related-task";

/// Task status (5-value enum).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskStatus {
    /// Task is actively being worked on
    #[default]
    Working,
    /// Task requires user input to continue
    InputRequired,
    /// Task completed successfully
    Completed,
    /// Task failed
    Failed,
    /// Task was cancelled
    Cancelled,
}

impl std::fmt::Display for TaskStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Working => write!(f, "working"),
            Self::InputRequired => write!(f, "input_required"),
            Self::Completed => write!(f, "completed"),
            Self::Failed => write!(f, "failed"),
            Self::Cancelled => write!(f, "cancelled"),
        }
    }
}

impl TaskStatus {
    /// Returns `true` if this status is terminal (no further transitions allowed).
    ///
    /// Terminal states are `Completed`, `Failed`, and `Cancelled`.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::Completed | Self::Failed | Self::Cancelled)
    }

    /// Returns `true` if transitioning from this status to `next` is valid.
    ///
    /// The MCP spec defines these valid transitions:
    /// - `Working` -> `InputRequired`, `Completed`, `Failed`, `Cancelled`
    /// - `InputRequired` -> `Working`, `Completed`, `Failed`, `Cancelled`
    /// - Terminal states -> no transitions allowed
    ///
    /// Self-transitions (e.g., `Working` -> `Working`) are rejected per spec.
    pub fn can_transition_to(&self, next: &Self) -> bool {
        if self == next {
            return false;
        }

        match self {
            Self::Working => matches!(
                next,
                Self::InputRequired | Self::Completed | Self::Failed | Self::Cancelled
            ),
            Self::InputRequired => matches!(
                next,
                Self::Working | Self::Completed | Self::Failed | Self::Cancelled
            ),
            Self::Completed | Self::Failed | Self::Cancelled => false,
        }
    }
}

/// A task resource representing an in-progress or completed operation.
///
/// # Backward Compatibility
///
/// This struct is `#[non_exhaustive]`. Use the constructor to remain
/// forward-compatible:
///
/// ```rust
/// use pmcp::types::tasks::{Task, TaskStatus};
///
/// let task = Task::new("t-123", TaskStatus::Working)
///     .with_timestamps("2025-11-25T00:00:00Z", "2025-11-25T00:01:00Z")
///     .with_ttl(60000)
///     .with_poll_interval(5000)
///     .with_status_message("Processing...");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Task {
    /// Unique task identifier
    pub task_id: String,
    /// Current task status
    pub status: TaskStatus,
    /// Time-to-live in milliseconds. Required but nullable per MCP spec:
    /// `None` serializes as `null` (unlimited TTL), `Some(ms)` as a number.
    pub ttl: Option<u64>,
    /// ISO 8601 creation timestamp
    pub created_at: String,
    /// ISO 8601 last-updated timestamp
    pub last_updated_at: String,
    /// Suggested polling interval in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poll_interval: Option<u64>,
    /// Human-readable status message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_message: Option<String>,
}

impl Task {
    /// Create a task with the given ID and status.
    ///
    /// Timestamps default to empty strings (caller should set via
    /// [`Task::with_timestamps`]). Optional fields default to `None`.
    pub fn new(task_id: impl Into<String>, status: TaskStatus) -> Self {
        Self {
            task_id: task_id.into(),
            status,
            ttl: None,
            created_at: String::new(),
            last_updated_at: String::new(),
            poll_interval: None,
            status_message: None,
        }
    }

    /// Set the time-to-live in milliseconds.
    pub fn with_ttl(mut self, ttl: u64) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Set both creation and last-updated timestamps.
    pub fn with_timestamps(
        mut self,
        created_at: impl Into<String>,
        last_updated_at: impl Into<String>,
    ) -> Self {
        self.created_at = created_at.into();
        self.last_updated_at = last_updated_at.into();
        self
    }

    /// Set the suggested polling interval in milliseconds.
    pub fn with_poll_interval(mut self, interval: u64) -> Self {
        self.poll_interval = Some(interval);
        self
    }

    /// Set a human-readable status message.
    pub fn with_status_message(mut self, message: impl Into<String>) -> Self {
        self.status_message = Some(message.into());
        self
    }
}

/// Parameters for task creation (augments tools/call).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct TaskCreationParams {
    /// Time-to-live in milliseconds. Required but nullable per MCP spec:
    /// `None` serializes as `null` (unlimited TTL), `Some(ms)` as a number.
    pub ttl: Option<u64>,
    /// Suggested polling interval in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poll_interval: Option<u64>,
}

impl TaskCreationParams {
    /// Create empty task creation parameters.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the time-to-live in milliseconds.
    pub fn with_ttl(mut self, ttl: u64) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Set the suggested polling interval in milliseconds.
    pub fn with_poll_interval(mut self, interval: u64) -> Self {
        self.poll_interval = Some(interval);
        self
    }
}

/// Task metadata for related-task references.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RelatedTaskMetadata {
    /// The referenced task ID
    pub task_id: String,
}

/// Result of creating a task.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CreateTaskResult {
    /// The created task
    pub task: Task,
}

impl CreateTaskResult {
    /// Create a task creation result.
    pub fn new(task: Task) -> Self {
        Self { task }
    }
}

/// Task status notification.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStatusNotification {
    /// Task with updated status
    pub task: Task,
}

/// Get task request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTaskRequest {
    /// Task ID to retrieve
    pub task_id: String,
}

/// Get task result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct GetTaskResult {
    /// The requested task
    pub task: Task,
}

impl GetTaskResult {
    /// Create a get task result.
    pub fn new(task: Task) -> Self {
        Self { task }
    }
}

/// Get task payload request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTaskPayloadRequest {
    /// Task ID whose payload to retrieve
    pub task_id: String,
}

/// List tasks request (paginated).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListTasksRequest {
    /// Pagination cursor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
}

/// List tasks result.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ListTasksResult {
    /// List of tasks
    pub tasks: Vec<Task>,
    /// Pagination cursor for next page
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

impl ListTasksResult {
    /// Create a list tasks result.
    pub fn new(tasks: Vec<Task>) -> Self {
        Self {
            tasks,
            next_cursor: None,
        }
    }

    /// Set the pagination cursor for the next page.
    pub fn with_next_cursor(mut self, cursor: impl Into<String>) -> Self {
        self.next_cursor = Some(cursor.into());
        self
    }
}

/// Cancel task request.
///
/// When `result` is `Some`, the task transitions to `Completed` status
/// (workflow completion). When `result` is `None`, the task transitions to
/// `Cancelled` status (standard cancel).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelTaskRequest {
    /// Task ID to cancel
    pub task_id: String,
    /// Optional result value for workflow completion.
    ///
    /// When present, completes the task (transitions to `Completed` status)
    /// instead of cancelling it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
}

/// Cancel task result.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct CancelTaskResult {
    /// The cancelled task
    pub task: Task,
}

impl CancelTaskResult {
    /// Create a cancel task result.
    pub fn new(task: Task) -> Self {
        Self { task }
    }
}

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

    #[test]
    fn task_status_serialization() {
        assert_eq!(
            serde_json::to_value(TaskStatus::Working).unwrap(),
            "working"
        );
        assert_eq!(
            serde_json::to_value(TaskStatus::InputRequired).unwrap(),
            "input_required"
        );
        assert_eq!(
            serde_json::to_value(TaskStatus::Completed).unwrap(),
            "completed"
        );
        assert_eq!(serde_json::to_value(TaskStatus::Failed).unwrap(), "failed");
        assert_eq!(
            serde_json::to_value(TaskStatus::Cancelled).unwrap(),
            "cancelled"
        );
    }

    #[test]
    fn task_roundtrip() {
        let task = Task::new("t-123", TaskStatus::Working)
            .with_timestamps("2025-11-25T00:00:00Z", "2025-11-25T00:01:00Z")
            .with_ttl(60000)
            .with_poll_interval(5000)
            .with_status_message("Processing...");
        let json = serde_json::to_value(&task).unwrap();
        assert_eq!(json["taskId"], "t-123");
        assert_eq!(json["status"], "working");
        assert_eq!(json["ttl"], 60000);
        assert_eq!(json["createdAt"], "2025-11-25T00:00:00Z");
        assert_eq!(json["pollInterval"], 5000);

        let roundtrip: Task = serde_json::from_value(json).unwrap();
        assert_eq!(roundtrip.task_id, "t-123");
        assert_eq!(roundtrip.status, TaskStatus::Working);
    }

    #[test]
    fn create_task_result_roundtrip() {
        let result = CreateTaskResult::new(
            Task::new("t-456", TaskStatus::Completed)
                .with_timestamps("2025-11-25T00:00:00Z", "2025-11-25T00:05:00Z"),
        );
        let json = serde_json::to_value(&result).unwrap();
        assert_eq!(json["task"]["taskId"], "t-456");
        assert_eq!(json["task"]["status"], "completed");

        let roundtrip: CreateTaskResult = serde_json::from_value(json).unwrap();
        assert_eq!(roundtrip.task.status, TaskStatus::Completed);
    }

    #[test]
    fn task_ts_format_interop() {
        // Test deserialization from TypeScript-format JSON
        let ts_json = json!({
            "taskId": "task-abc",
            "status": "input_required",
            "createdAt": "2025-11-25T12:00:00.000Z",
            "lastUpdatedAt": "2025-11-25T12:01:00.000Z",
            "pollInterval": 3000,
            "statusMessage": "Waiting for user input"
        });
        let task: Task = serde_json::from_value(ts_json).unwrap();
        assert_eq!(task.task_id, "task-abc");
        assert_eq!(task.status, TaskStatus::InputRequired);
        assert_eq!(task.poll_interval, Some(3000));
    }

    #[test]
    fn related_task_meta_key_value() {
        assert_eq!(
            RELATED_TASK_META_KEY,
            "io.modelcontextprotocol/related-task"
        );
    }

    #[test]
    fn task_status_is_terminal() {
        assert!(!TaskStatus::Working.is_terminal());
        assert!(!TaskStatus::InputRequired.is_terminal());
        assert!(TaskStatus::Completed.is_terminal());
        assert!(TaskStatus::Failed.is_terminal());
        assert!(TaskStatus::Cancelled.is_terminal());
    }

    #[test]
    fn task_status_can_transition_to() {
        // Working can transition to all except itself
        assert!(TaskStatus::Working.can_transition_to(&TaskStatus::InputRequired));
        assert!(TaskStatus::Working.can_transition_to(&TaskStatus::Completed));
        assert!(TaskStatus::Working.can_transition_to(&TaskStatus::Failed));
        assert!(TaskStatus::Working.can_transition_to(&TaskStatus::Cancelled));

        // InputRequired can transition to all except itself
        assert!(TaskStatus::InputRequired.can_transition_to(&TaskStatus::Working));
        assert!(TaskStatus::InputRequired.can_transition_to(&TaskStatus::Completed));
        assert!(TaskStatus::InputRequired.can_transition_to(&TaskStatus::Failed));
        assert!(TaskStatus::InputRequired.can_transition_to(&TaskStatus::Cancelled));
    }

    #[test]
    fn task_status_self_transition_rejected() {
        assert!(!TaskStatus::Working.can_transition_to(&TaskStatus::Working));
        assert!(!TaskStatus::InputRequired.can_transition_to(&TaskStatus::InputRequired));
        assert!(!TaskStatus::Completed.can_transition_to(&TaskStatus::Completed));
        assert!(!TaskStatus::Failed.can_transition_to(&TaskStatus::Failed));
        assert!(!TaskStatus::Cancelled.can_transition_to(&TaskStatus::Cancelled));
    }

    #[test]
    fn task_status_terminal_rejects_all() {
        for terminal in [
            TaskStatus::Completed,
            TaskStatus::Failed,
            TaskStatus::Cancelled,
        ] {
            for target in [
                TaskStatus::Working,
                TaskStatus::InputRequired,
                TaskStatus::Completed,
                TaskStatus::Failed,
                TaskStatus::Cancelled,
            ] {
                assert!(
                    !terminal.can_transition_to(&target),
                    "{terminal:?} should not transition to {target:?}"
                );
            }
        }
    }

    #[test]
    fn task_ttl_null_serialization() {
        let task = Task::new("test-null-ttl", TaskStatus::Working)
            .with_timestamps("2025-11-25T00:00:00Z", "2025-11-25T00:01:00Z");
        let json = serde_json::to_value(&task).unwrap();
        // ttl MUST be present as null, not omitted (MCP spec: number | null)
        assert!(json.get("ttl").is_some(), "ttl must be present");
        assert!(json["ttl"].is_null(), "ttl must be null when None");
        // pollInterval SHOULD be omitted when None
        assert!(
            json.get("pollInterval").is_none(),
            "pollInterval should be omitted when None"
        );
    }

    #[test]
    fn task_ttl_present_serialization() {
        let task = Task::new("test-present-ttl", TaskStatus::Working)
            .with_timestamps("2025-11-25T00:00:00Z", "2025-11-25T00:01:00Z")
            .with_ttl(60000);
        let json = serde_json::to_value(&task).unwrap();
        assert_eq!(json["ttl"], 60000);
    }

    #[test]
    fn task_status_display() {
        assert_eq!(TaskStatus::Working.to_string(), "working");
        assert_eq!(TaskStatus::InputRequired.to_string(), "input_required");
        assert_eq!(TaskStatus::Completed.to_string(), "completed");
        assert_eq!(TaskStatus::Failed.to_string(), "failed");
        assert_eq!(TaskStatus::Cancelled.to_string(), "cancelled");
    }
}