Skip to main content

adk_tool/mcp/
task.rs

1// MCP Task Support
2//
3// Implements async task lifecycle for long-running MCP tool operations.
4// Tasks allow tools to be queued and polled rather than blocking.
5
6use serde::{Deserialize, Serialize};
7use std::time::Duration;
8
9pub use rmcp::model::{CreateTaskResult, Task as TaskInfo, TaskStatus};
10
11/// Configuration for MCP task-based execution
12#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
13#[serde(rename_all = "camelCase")]
14#[serde(default)]
15pub struct McpTaskConfig {
16    /// Allow task mode when a tool and server negotiate MCP task support.
17    pub enable_tasks: bool,
18    /// Default poll interval in milliseconds
19    pub poll_interval_ms: u64,
20    /// Maximum wait time before timeout (None = no timeout)
21    pub timeout_ms: Option<u64>,
22    /// Maximum number of poll attempts (None = unlimited)
23    pub max_poll_attempts: Option<u32>,
24    /// Maximum stateless MRTR input rounds before rejecting a looping peer.
25    pub max_input_rounds: usize,
26}
27
28impl Default for McpTaskConfig {
29    fn default() -> Self {
30        Self {
31            enable_tasks: false,
32            poll_interval_ms: 1000,
33            timeout_ms: Some(300_000), // 5 minutes default
34            max_poll_attempts: None,
35            max_input_rounds: 10,
36        }
37    }
38}
39
40impl McpTaskConfig {
41    /// Create a new task config with tasks enabled
42    pub fn enabled() -> Self {
43        Self { enable_tasks: true, ..Default::default() }
44    }
45
46    /// Set the poll interval
47    pub fn poll_interval(mut self, interval: Duration) -> Self {
48        self.poll_interval_ms = interval.as_millis() as u64;
49        self
50    }
51
52    /// Set the timeout
53    pub fn timeout(mut self, timeout: Duration) -> Self {
54        self.timeout_ms = Some(timeout.as_millis() as u64);
55        self
56    }
57
58    /// Set no timeout (wait indefinitely)
59    pub fn no_timeout(mut self) -> Self {
60        self.timeout_ms = None;
61        self
62    }
63
64    /// Set maximum poll attempts
65    pub fn max_attempts(mut self, attempts: u32) -> Self {
66        self.max_poll_attempts = Some(attempts);
67        self
68    }
69
70    /// Set the maximum number of MRTR input rounds.
71    pub fn max_input_rounds(mut self, rounds: usize) -> Self {
72        self.max_input_rounds = rounds;
73        self
74    }
75
76    /// Get poll interval as Duration
77    pub fn poll_duration(&self) -> Duration {
78        Duration::from_millis(self.poll_interval_ms)
79    }
80
81    /// Get timeout as Duration
82    pub fn timeout_duration(&self) -> Option<Duration> {
83        self.timeout_ms.map(Duration::from_millis)
84    }
85}
86
87/// Error during task operations
88#[derive(Debug, Clone)]
89pub enum TaskError {
90    /// Task creation failed
91    CreateFailed(String),
92    /// Task polling failed
93    PollFailed(String),
94    /// Task timed out
95    Timeout {
96        /// ID of the timed-out task.
97        task_id: String,
98        /// Elapsed time in milliseconds before timeout.
99        elapsed_ms: u64,
100    },
101    /// Task was cancelled
102    Cancelled(String),
103    /// Task failed with error
104    TaskFailed {
105        /// ID of the failed task.
106        task_id: String,
107        /// Error message from the task.
108        error: String,
109    },
110    /// The remote task paused until more information is supplied.
111    InputRequired {
112        /// ID of the task waiting for input.
113        task_id: String,
114        /// Human-readable explanation supplied by the MCP server.
115        message: String,
116    },
117    /// Maximum poll attempts exceeded
118    MaxAttemptsExceeded {
119        /// ID of the task that exceeded attempts.
120        task_id: String,
121        /// Number of attempts made.
122        attempts: u32,
123    },
124}
125
126impl std::fmt::Display for TaskError {
127    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128        match self {
129            TaskError::CreateFailed(msg) => write!(f, "Failed to create task: {}", msg),
130            TaskError::PollFailed(msg) => write!(f, "Failed to poll task: {}", msg),
131            TaskError::Timeout { task_id, elapsed_ms } => {
132                write!(f, "Task '{}' timed out after {}ms", task_id, elapsed_ms)
133            }
134            TaskError::Cancelled(task_id) => write!(f, "Task '{}' was cancelled", task_id),
135            TaskError::TaskFailed { task_id, error } => {
136                write!(f, "Task '{}' failed: {}", task_id, error)
137            }
138            TaskError::InputRequired { task_id, message } => {
139                write!(f, "Task '{task_id}' requires input: {message}")
140            }
141            TaskError::MaxAttemptsExceeded { task_id, attempts } => {
142                write!(f, "Task '{}' exceeded {} poll attempts", task_id, attempts)
143            }
144        }
145    }
146}
147
148impl std::error::Error for TaskError {}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn test_task_config_default() {
156        let config = McpTaskConfig::default();
157        assert!(!config.enable_tasks);
158        assert_eq!(config.poll_interval_ms, 1000);
159        assert_eq!(config.timeout_ms, Some(300_000));
160    }
161
162    #[test]
163    fn test_task_config_enabled() {
164        let config = McpTaskConfig::enabled();
165        assert!(config.enable_tasks);
166    }
167
168    #[test]
169    fn test_task_config_builder() {
170        let config = McpTaskConfig::enabled()
171            .poll_interval(Duration::from_secs(2))
172            .timeout(Duration::from_secs(60))
173            .max_attempts(10);
174
175        assert!(config.enable_tasks);
176        assert_eq!(config.poll_interval_ms, 2000);
177        assert_eq!(config.timeout_ms, Some(60_000));
178        assert_eq!(config.max_poll_attempts, Some(10));
179    }
180
181    #[test]
182    fn exports_the_rmcp_task_status_shape() {
183        assert_eq!(TaskStatus::default(), TaskStatus::Working);
184    }
185}