aether-mcp-servers 0.8.9

Built-in MCP tool servers for the Aether AI agent framework
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
use super::types::{Task, TaskId, TaskStatus, TaskUpdate};
use std::collections::BTreeMap;
use std::fs::{self, File};
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use thiserror::Error;
use utils::fs::{append_line, write_atomic};

/// Errors that can occur during task store operations
#[derive(Debug, Error)]
pub enum TaskStoreError {
    #[error("Task not found: {id}")]
    NotFound { id: String },

    #[error("Task already exists: {id}")]
    AlreadyExists { id: String },

    #[error("Parent task not found: {id}")]
    ParentNotFound { id: String },

    #[error("Dependency not found: {id}")]
    DependencyNotFound { id: String },

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    #[error("Task store worker failed: {0}")]
    Worker(#[from] tokio::task::JoinError),
}

/// Renders the error as the text content of an errored MCP tool result.
impl rmcp::model::IntoContents for TaskStoreError {
    fn into_contents(self) -> Vec<rmcp::model::ContentBlock> {
        vec![rmcp::model::ContentBlock::text(self.to_string())]
    }
}

/// Task store backed by one JSONL file per task tree, held in memory in [`TaskId`] order
#[derive(Debug)]
pub struct TaskStore {
    root: PathBuf,
    tasks: BTreeMap<TaskId, Task>,
    initialized: bool,
}

impl TaskStore {
    /// Create a new task store at the given root directory
    pub fn new(root: PathBuf) -> Self {
        Self { root, tasks: BTreeMap::new(), initialized: false }
    }

    /// Initialize the store by loading all active tasks.
    /// This is idempotent - subsequent calls are no-ops.
    pub fn init(&mut self) -> Result<(), TaskStoreError> {
        if self.initialized {
            return Ok(());
        }

        let active_dir = self.active_dir();
        if !active_dir.exists() {
            fs::create_dir_all(&active_dir)?;
        }

        self.tasks.clear();

        for entry in fs::read_dir(&active_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().and_then(|s| s.to_str()) == Some("jsonl") {
                self.load_tree_file(&path)?;
            }
        }

        self.initialized = true;
        Ok(())
    }

    pub fn create(&mut self, parent: Option<&TaskId>, title: &str, fields: TaskUpdate) -> Result<Task, TaskStoreError> {
        if let Some(parent) = parent.filter(|parent| !self.tasks.contains_key(parent)) {
            return Err(TaskStoreError::ParentNotFound { id: parent.to_string() });
        }
        self.ensure_deps_exist(fields.deps.as_deref())?;

        let mut task = if let Some(parent) = parent {
            let id = TaskId::new_subtask(parent, self.next_subtask_index(&parent.root()));
            Task::new_subtask(id, parent.clone(), title.to_string())
        } else {
            let id = TaskId::new_root(&self.generate_hash());
            if self.tasks.contains_key(&id) {
                return Err(TaskStoreError::AlreadyExists { id: id.to_string() });
            }
            Task::new_root(id, title.to_string())
        };
        fields.apply_to(&mut task);

        append_line(&self.tree_path(&task.id), &serde_json::to_string(&task)?)?;
        self.tasks.insert(task.id.clone(), task.clone());

        Ok(task)
    }

    /// Update a task's fields
    pub fn update(&mut self, id: &TaskId, updates: TaskUpdate) -> Result<Task, TaskStoreError> {
        self.ensure_deps_exist(updates.deps.as_deref())?;

        let mut task = self.tasks.get(id).cloned().ok_or_else(|| TaskStoreError::NotFound { id: id.to_string() })?;
        updates.apply_to(&mut task);

        self.write_updated_tree(&task)?;
        self.tasks.insert(task.id.clone(), task.clone());

        Ok(task)
    }

    /// Get a task by ID
    pub fn get(&self, id: &TaskId) -> Option<&Task> {
        self.tasks.get(id)
    }

    /// All tasks in [`TaskId`] order
    pub fn tasks(&self) -> impl Iterator<Item = &Task> {
        self.tasks.values()
    }

    /// Whether `task` can start: it is pending and every dependency is completed
    pub fn is_ready(&self, task: &Task) -> bool {
        task.status == TaskStatus::Pending
            && task.deps.iter().all(|dep| self.get(dep).is_some_and(|dep| dep.status == TaskStatus::Completed))
    }

    fn active_dir(&self) -> PathBuf {
        self.root.join("active")
    }

    fn tree_path(&self, id: &TaskId) -> PathBuf {
        self.active_dir().join(id.filename())
    }

    fn tree(&self, root_id: &TaskId) -> impl Iterator<Item = &Task> {
        self.tasks().filter(move |task| task.id.root() == *root_id)
    }

    fn next_subtask_index(&self, root_id: &TaskId) -> usize {
        self.tree(root_id).filter_map(|task| task.id.index()).max().unwrap_or(0) + 1
    }

    fn ensure_deps_exist(&self, deps: Option<&[TaskId]>) -> Result<(), TaskStoreError> {
        match deps.into_iter().flatten().find(|dep| !self.tasks.contains_key(dep)) {
            Some(dep) => Err(TaskStoreError::DependencyNotFound { id: dep.to_string() }),
            None => Ok(()),
        }
    }

    fn generate_hash(&self) -> String {
        use std::time::{SystemTime, UNIX_EPOCH};

        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();

        let pid = u128::from(std::process::id());
        let count = self.tasks.len() as u128;
        let mixed = now.wrapping_add(pid << 16).wrapping_add(count);
        // Intentional truncation: value is masked to 32 bits for ID generation
        #[allow(clippy::cast_possible_truncation)]
        let truncated = mixed as u64;
        format!("{:08x}", truncated & 0xFFFF_FFFF)
    }

    fn load_tree_file(&mut self, path: &Path) -> Result<(), TaskStoreError> {
        for line in BufReader::new(File::open(path)?).lines() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }

            let task: Task = serde_json::from_str(&line)?;
            self.tasks.insert(task.id.clone(), task);
        }

        Ok(())
    }

    fn write_updated_tree(&self, updated: &Task) -> Result<(), TaskStoreError> {
        let mut bytes = Vec::new();
        for task in self.tree(&updated.id.root()) {
            let task = if task.id == updated.id { updated } else { task };
            serde_json::to_writer(&mut bytes, task)?;
            bytes.push(b'\n');
        }
        Ok(write_atomic(&self.tree_path(&updated.id), &bytes)?)
    }
}

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

    #[test]
    fn test_create_tree() {
        let mut tasks = TestTaskStore::new();

        let description = TaskUpdate { description: Some("Detailed description".to_string()), ..Default::default() };
        let task = tasks.store_mut().create(None, "Research topic X", description).unwrap();

        assert!(task.id.is_root());
        assert_eq!(task.title, "Research topic X");
        assert_eq!(task.description, Some("Detailed description".to_string()));
        assert_eq!(task.status, TaskStatus::Pending);

        let file_path = tasks.store().active_dir().join(task.id.filename());
        assert!(file_path.exists());
    }

    #[test]
    fn test_add_subtask() {
        let mut tasks = TestTaskStore::new();

        let root = tasks.root_task("Root task");
        let subtask = tasks.subtask(&root.id, "Subtask 1");

        assert!(!subtask.id.is_root());
        assert_eq!(subtask.parent, Some(root.id.clone()));
        assert_eq!(subtask.title, "Subtask 1");
        assert_eq!(tasks.store().tasks().count(), 2);
    }

    #[test]
    fn subtask_numbering_continues_across_the_tree_after_reopen() {
        let mut tasks = TestTaskStore::new();
        let root = tasks.root_task("Root");
        let first = tasks.subtask(&root.id, "First");
        let nested = tasks.subtask(&first.id, "Nested");

        tasks.reopen();
        let next = tasks.subtask(&root.id, "Next");

        assert_eq!(nested.id.as_str(), format!("{}.1.2", root.id));
        assert_eq!(next.id.as_str(), format!("{}.3", root.id));
    }

    #[test]
    fn test_update_task() {
        let mut tasks = TestTaskStore::new();
        let task = tasks.root_task("Original title");

        let updated = tasks
            .store_mut()
            .update(
                &task.id,
                TaskUpdate {
                    title: Some("Updated title".to_string()),
                    status: Some(TaskStatus::InProgress),
                    assignee: Some("worker-1".to_string()),
                    ..Default::default()
                },
            )
            .unwrap();

        assert_eq!(updated.title, "Updated title");
        assert_eq!(updated.status, TaskStatus::InProgress);
        assert_eq!(updated.assignee, Some("worker-1".to_string()));
    }

    #[test]
    fn failed_update_keeps_the_previous_task_in_memory_and_on_disk() {
        let mut tasks = TestTaskStore::new();
        let task = tasks.root_task("Original title");
        let path = tasks.root().join("active").join(task.id.filename());
        let saved = path.with_extension("saved");
        fs::rename(&path, &saved).unwrap();
        fs::create_dir(&path).unwrap();

        let result = tasks
            .store_mut()
            .update(&task.id, TaskUpdate { title: Some("Rejected title".into()), ..Default::default() });

        assert!(matches!(result, Err(TaskStoreError::Io(_))));
        assert_eq!(tasks.store().get(&task.id).unwrap().title, "Original title");
        fs::remove_dir(&path).unwrap();
        fs::rename(saved, path).unwrap();
        tasks.reopen();
        assert_eq!(tasks.store().get(&task.id).unwrap().title, "Original title");
    }

    #[test]
    fn updating_a_task_preserves_its_tree_after_reopen() {
        let mut tasks = TestTaskStore::new();
        let root = tasks.root_task("Root");
        let child = tasks.subtask(&root.id, "Child");
        let sibling = tasks.subtask(&root.id, "Sibling");

        tasks
            .store_mut()
            .update(&child.id, TaskUpdate { title: Some("Updated child".into()), ..Default::default() })
            .unwrap();
        tasks.reopen();

        assert_eq!(tasks.store().get(&root.id).unwrap().title, "Root");
        assert_eq!(tasks.store().get(&child.id).unwrap().title, "Updated child");
        assert_eq!(tasks.store().get(&sibling.id).unwrap().title, "Sibling");
    }

    #[test]
    fn test_complete_task_with_summary() {
        let mut tasks = TestTaskStore::new();
        let task = tasks.root_task("Task to complete");

        let completed = tasks
            .store_mut()
            .update(
                &task.id,
                TaskUpdate {
                    status: Some(TaskStatus::Completed),
                    summary: Some("Found the answer!".to_string()),
                    ..Default::default()
                },
            )
            .unwrap();

        assert_eq!(completed.status, TaskStatus::Completed);
        assert_eq!(completed.summary, Some("Found the answer!".to_string()));
    }

    #[test]
    fn test_is_ready() {
        let mut tasks = TestTaskStore::new();

        let root = tasks.root_task("Root");
        let subtask1 = tasks.subtask(&root.id, "Subtask 1");
        let subtask2 = tasks.subtask(&root.id, "Subtask 2");

        tasks
            .store_mut()
            .update(&subtask2.id, TaskUpdate { deps: Some(vec![subtask1.id.clone()]), ..Default::default() })
            .unwrap();

        assert_eq!(ready_titles(&tasks), ["Root", "Subtask 1"]);

        tasks
            .store_mut()
            .update(
                &subtask1.id,
                TaskUpdate {
                    status: Some(TaskStatus::Completed),
                    summary: Some("done".to_string()),
                    ..Default::default()
                },
            )
            .unwrap();

        assert_eq!(ready_titles(&tasks), ["Root", "Subtask 2"]);
    }

    #[test]
    fn test_persistence() {
        let mut tasks = TestTaskStore::new();

        let task = tasks.root_task("Persistent task");
        tasks.subtask(&task.id, "Subtask 1");
        tasks.subtask(&task.id, "Subtask 2");

        tasks.reopen();

        assert_eq!(tasks.store().tasks().count(), 3);
    }

    #[test]
    fn test_error_task_not_found() {
        let tasks = TestTaskStore::new();

        let result = tasks.store().get(&TaskId::from("at-nonexistent"));
        assert!(result.is_none());
    }

    #[test]
    fn test_error_parent_not_found() {
        let mut tasks = TestTaskStore::new();

        let result = tasks.store_mut().create(Some(&TaskId::from("at-nonexistent")), "Orphan", TaskUpdate::default());
        assert!(matches!(result, Err(TaskStoreError::ParentNotFound { .. })));
    }

    #[test]
    fn test_error_dependency_not_found() {
        let mut tasks = TestTaskStore::new();
        let task = tasks.root_task("Task");

        let result = tasks
            .store_mut()
            .update(&task.id, TaskUpdate { deps: Some(vec![TaskId::from("at-nonexistent")]), ..Default::default() });

        assert!(matches!(result, Err(TaskStoreError::DependencyNotFound { .. })));
    }

    #[test]
    fn test_init_is_idempotent() {
        let mut tasks = TestTaskStore::new();
        let store = tasks.store_mut();

        let task = store.create(None, "Test task", TaskUpdate::default()).unwrap();
        assert_eq!(store.tasks().count(), 1);

        store.init().unwrap();
        assert_eq!(store.tasks().count(), 1);

        let retrieved = store.get(&task.id);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().title, "Test task");
    }

    fn ready_titles(tasks: &TestTaskStore) -> Vec<&str> {
        let store = tasks.store();
        store.tasks().filter(|task| store.is_ready(task)).map(|task| task.title.as_str()).collect()
    }
}