mcpkit-server 0.6.0

Server implementation for mcpkit
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
//! Task capability implementation.
//!
//! This module provides support for long-running tasks in MCP servers.
//!
//! Tasks allow servers to execute long-running operations while
//! providing progress updates and supporting cancellation.

use crate::context::CancellationToken;
use crate::context::Context;
use crate::handler::TaskHandler;
use mcpkit_core::error::McpError;
use mcpkit_core::types::task::{Task, TaskId, TaskStatus};
use serde_json::Value;
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::time::Instant;

/// Internal state for a running task.
#[derive(Debug)]
pub struct TaskState {
    /// Task metadata.
    pub task: Task,
    /// Cancellation token.
    pub cancel_token: CancellationToken,
    /// When the task was last accessed (for cleanup).
    pub last_access: Instant,
}

impl TaskState {
    /// Create a new task state.
    fn new(task: Task) -> Self {
        Self {
            task,
            cancel_token: CancellationToken::new(),
            last_access: Instant::now(),
        }
    }

    /// Check if the task is cancelled.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.is_cancelled()
    }
}

/// Handle for interacting with a running task.
///
/// This handle is given to task executors to report progress
/// and completion.
pub struct TaskHandle {
    task_id: TaskId,
    manager: Arc<TaskManager>,
}

impl TaskHandle {
    /// Get the task ID.
    #[must_use]
    pub const fn id(&self) -> &TaskId {
        &self.task_id
    }

    /// Report that the task is now running.
    pub async fn running(&self) -> Result<(), McpError> {
        self.manager
            .update_status(&self.task_id, TaskStatus::Running)
            .await
    }

    /// Report progress on the task.
    pub async fn progress(
        &self,
        current: u64,
        total: Option<u64>,
        message: Option<&str>,
    ) -> Result<(), McpError> {
        self.manager
            .update_progress(&self.task_id, current, total, message)
            .await
    }

    /// Mark the task as completed with a result.
    pub async fn complete(&self, result: Value) -> Result<(), McpError> {
        self.manager.complete_success(&self.task_id, result).await
    }

    /// Mark the task as failed with an error.
    pub async fn error(&self, message: impl Into<String>) -> Result<(), McpError> {
        self.manager
            .complete_error(&self.task_id, message.into())
            .await
    }

    /// Check if the task has been cancelled.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.manager
            .get(&self.task_id)
            .is_none_or(|s| s.is_cancelled())
    }

    /// Get a future that completes when the task is cancelled.
    pub async fn cancelled(&self) {
        if let Some(state) = self.manager.get(&self.task_id) {
            state.cancel_token.cancelled().await;
        }
    }
}

/// Manager for coordinating tasks.
///
/// This manages the lifecycle of tasks, including creation,
/// progress tracking, cancellation, and cleanup.
pub struct TaskManager {
    tasks: RwLock<HashMap<TaskId, TaskState>>,
}

impl Default for TaskManager {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskManager {
    /// Create a new task manager.
    #[must_use]
    pub fn new() -> Self {
        Self {
            tasks: RwLock::new(HashMap::new()),
        }
    }

    /// Create a new task.
    pub fn create(self: &Arc<Self>, tool_name: Option<&str>) -> TaskHandle {
        let mut task = Task::create();
        task.tool = tool_name.map(String::from);

        let task_id = task.id.clone();
        let state = TaskState::new(task);

        if let Ok(mut tasks) = self.tasks.write() {
            tasks.insert(task_id.clone(), state);
        }

        TaskHandle {
            task_id,
            manager: Arc::clone(self),
        }
    }

    /// Get a task state by ID.
    pub fn get(&self, id: &TaskId) -> Option<TaskState> {
        self.tasks.read().ok()?.get(id).map(|s| TaskState {
            task: s.task.clone(),
            cancel_token: s.cancel_token.clone(),
            last_access: s.last_access,
        })
    }

    /// List all tasks.
    pub fn list(&self) -> Vec<Task> {
        self.tasks
            .read()
            .map(|tasks| tasks.values().map(|s| s.task.clone()).collect())
            .unwrap_or_default()
    }

    /// Cancel a task.
    pub fn cancel(&self, id: &TaskId) -> Result<(), McpError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| McpError::internal("Failed to acquire task lock"))?;

        if let Some(state) = tasks.get_mut(id) {
            state.cancel_token.cancel();
            state.task.status = TaskStatus::Cancelled;
            state.task.updated_at = chrono::Utc::now();
            Ok(())
        } else {
            Err(McpError::invalid_params(
                "tasks/cancel",
                format!("Unknown task: {}", id.as_str()),
            ))
        }
    }

    /// Update task status.
    async fn update_status(&self, id: &TaskId, status: TaskStatus) -> Result<(), McpError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| McpError::internal("Failed to acquire task lock"))?;

        if let Some(state) = tasks.get_mut(id) {
            state.task.status = status;
            state.task.updated_at = chrono::Utc::now();
            state.last_access = Instant::now();
            Ok(())
        } else {
            Err(McpError::invalid_params(
                "tasks/get",
                format!("Unknown task: {}", id.as_str()),
            ))
        }
    }

    /// Update task progress.
    async fn update_progress(
        &self,
        id: &TaskId,
        current: u64,
        total: Option<u64>,
        message: Option<&str>,
    ) -> Result<(), McpError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| McpError::internal("Failed to acquire task lock"))?;

        if let Some(state) = tasks.get_mut(id) {
            state.task.progress = Some(mcpkit_core::types::task::TaskProgress {
                current,
                total,
                message: message.map(String::from),
            });
            state.task.updated_at = chrono::Utc::now();
            state.last_access = Instant::now();
            Ok(())
        } else {
            Err(McpError::invalid_params(
                "tasks/get",
                format!("Unknown task: {}", id.as_str()),
            ))
        }
    }

    /// Complete a task with success.
    async fn complete_success(&self, id: &TaskId, result: Value) -> Result<(), McpError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| McpError::internal("Failed to acquire task lock"))?;

        if let Some(state) = tasks.get_mut(id) {
            state.task.status = TaskStatus::Completed;
            state.task.result = Some(result);
            state.task.updated_at = chrono::Utc::now();
            state.last_access = Instant::now();
            Ok(())
        } else {
            Err(McpError::invalid_params(
                "tasks/get",
                format!("Unknown task: {}", id.as_str()),
            ))
        }
    }

    /// Complete a task with an error.
    async fn complete_error(&self, id: &TaskId, message: String) -> Result<(), McpError> {
        let mut tasks = self
            .tasks
            .write()
            .map_err(|_| McpError::internal("Failed to acquire task lock"))?;

        if let Some(state) = tasks.get_mut(id) {
            state.task.status = TaskStatus::Failed;
            state.task.error = Some(mcpkit_core::types::task::TaskError {
                code: -1,
                message,
                data: None,
            });
            state.task.updated_at = chrono::Utc::now();
            state.last_access = Instant::now();
            Ok(())
        } else {
            Err(McpError::invalid_params(
                "tasks/get",
                format!("Unknown task: {}", id.as_str()),
            ))
        }
    }

    /// Remove completed tasks older than the given duration.
    pub fn cleanup(&self, max_age: std::time::Duration) {
        if let Ok(mut tasks) = self.tasks.write() {
            tasks.retain(|_, state| {
                let is_terminal = state.task.status.is_terminal();
                !is_terminal || state.last_access.elapsed() < max_age
            });
        }
    }
}

/// Task service implementing the `TaskHandler` trait.
pub struct TaskService {
    manager: Arc<TaskManager>,
}

impl Default for TaskService {
    fn default() -> Self {
        Self::new()
    }
}

impl TaskService {
    /// Create a new task service.
    #[must_use]
    pub fn new() -> Self {
        Self {
            manager: Arc::new(TaskManager::new()),
        }
    }

    /// Get the underlying task manager.
    #[must_use]
    pub const fn manager(&self) -> &Arc<TaskManager> {
        &self.manager
    }

    /// Create a new task and get a handle for it.
    #[must_use]
    pub fn create(&self, tool_name: Option<&str>) -> TaskHandle {
        self.manager.create(tool_name)
    }
}

impl TaskHandler for TaskService {
    async fn list_tasks(&self, _ctx: &Context<'_>) -> Result<Vec<Task>, McpError> {
        Ok(self.manager.list())
    }

    async fn get_task(
        &self,
        task_id: &TaskId,
        _ctx: &Context<'_>,
    ) -> Result<Option<Task>, McpError> {
        Ok(self.manager.get(task_id).map(|s| s.task))
    }

    async fn cancel_task(&self, task_id: &TaskId, _ctx: &Context<'_>) -> Result<bool, McpError> {
        match self.manager.cancel(task_id) {
            Ok(()) => Ok(true),
            Err(_) => Ok(false),
        }
    }
}

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

    #[test]
    fn test_task_manager() {
        let manager = Arc::new(TaskManager::new());

        let handle = manager.create(Some("test-tool"));
        assert!(!handle.is_cancelled());

        let tasks = manager.list();
        assert_eq!(tasks.len(), 1);
        assert_eq!(tasks[0].tool.as_deref(), Some("test-tool"));
        assert_eq!(tasks[0].status, TaskStatus::Pending);
    }

    #[tokio::test]
    async fn test_task_lifecycle() -> Result<(), Box<dyn std::error::Error>> {
        let manager = Arc::new(TaskManager::new());

        let handle = manager.create(Some("processor"));
        let task_id = handle.id().clone();

        // Start running
        handle.running().await?;
        let state = manager.get(&task_id).ok_or("Task not found")?;
        assert_eq!(state.task.status, TaskStatus::Running);

        // Report progress
        handle.progress(50, Some(100), Some("Halfway done")).await?;
        let state = manager.get(&task_id).ok_or("Task not found")?;
        assert_eq!(state.task.progress.as_ref().map(|p| p.current), Some(50));

        // Complete
        handle
            .complete(serde_json::json!({"result": "success"}))
            .await?;
        let state = manager.get(&task_id).ok_or("Task not found")?;
        assert_eq!(state.task.status, TaskStatus::Completed);

        Ok(())
    }

    #[test]
    fn test_task_cancellation() -> Result<(), Box<dyn std::error::Error>> {
        let manager = Arc::new(TaskManager::new());

        let handle = manager.create(None);
        let task_id = handle.id().clone();

        assert!(!handle.is_cancelled());

        manager.cancel(&task_id)?;

        assert!(handle.is_cancelled());
        let state = manager.get(&task_id).ok_or("Task not found")?;
        assert_eq!(state.task.status, TaskStatus::Cancelled);

        Ok(())
    }

    #[tokio::test]
    async fn test_task_service() -> Result<(), Box<dyn std::error::Error>> {
        let service = TaskService::new();

        let handle = service.create(Some("service-task"));
        handle.running().await?;

        let tasks = service.manager.list();
        assert_eq!(tasks.len(), 1);

        Ok(())
    }
}