task-graph-mcp 0.2.0

MCP server for agent task workflows with phases, prompts, gates, and multi-agent coordination
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
//! File coordination tools (advisory marks for file coordination).

use super::{get_string, get_string_array, get_string_or_array, make_tool_with_prompts};
use crate::config::Prompts;
use crate::db::Database;
use crate::error::ToolError;
use crate::format::{OutputFormat, markdown_to_json};
use anyhow::Result;
use rmcp::model::Tool;
use serde_json::{Value, json};
use std::path::{Component, Path, PathBuf};

/// Normalize a file path to an absolute, canonical form.
///
/// This function:
/// 1. Resolves relative paths against the current working directory
/// 2. Normalizes path components (removes `.`, resolves `..`)
/// 3. Uses forward slashes for consistency across platforms
/// 4. Works with non-existent files (doesn't require file to exist)
///
/// # Examples
/// - `src/main.rs` -> `/project/src/main.rs`
/// - `./src/../src/main.rs` -> `/project/src/main.rs`
/// - `/absolute/path.rs` -> `/absolute/path.rs`
fn normalize_file_path(path: &str) -> String {
    let path = Path::new(path);

    // Get absolute path
    let absolute = if path.is_absolute() {
        path.to_path_buf()
    } else {
        // Resolve relative to current directory
        std::env::current_dir()
            .unwrap_or_else(|_| PathBuf::from("."))
            .join(path)
    };

    // Normalize the path (resolve . and ..)
    let normalized = normalize_path_components(&absolute);

    // Convert to string with forward slashes for consistency
    path_to_forward_slashes(&normalized)
}

/// Normalize path components without requiring the file to exist.
/// Handles `.` and `..` components.
fn normalize_path_components(path: &Path) -> PathBuf {
    let mut components = Vec::new();

    for component in path.components() {
        match component {
            Component::Prefix(p) => {
                // Windows drive prefix (e.g., C:)
                components.push(Component::Prefix(p));
            }
            Component::RootDir => {
                components.push(Component::RootDir);
            }
            Component::CurDir => {
                // Skip `.` - it refers to current directory
            }
            Component::ParentDir => {
                // Go up one directory if possible
                if let Some(Component::Normal(_)) = components.last() {
                    components.pop();
                } else {
                    // Can't go up from root, keep the component
                    // (this handles edge cases like `/../foo`)
                    components.push(Component::ParentDir);
                }
            }
            Component::Normal(name) => {
                components.push(Component::Normal(name));
            }
        }
    }

    components.iter().collect()
}

/// Convert path to string using forward slashes.
fn path_to_forward_slashes(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

/// Normalize a vector of file paths.
fn normalize_file_paths(paths: Vec<String>) -> Vec<String> {
    paths.into_iter().map(|p| normalize_file_path(&p)).collect()
}

/// Format milliseconds as human-readable duration (e.g., "5m 30s", "2h 15m")
fn format_duration(ms: i64) -> String {
    if ms < 1000 {
        return format!("{}ms", ms);
    }
    let secs = ms / 1000;
    if secs < 60 {
        return format!("{}s", secs);
    }
    let mins = secs / 60;
    if mins < 60 {
        let rem_secs = secs % 60;
        return if rem_secs > 0 {
            format!("{}m {}s", mins, rem_secs)
        } else {
            format!("{}m", mins)
        };
    }
    let hours = mins / 60;
    let rem_mins = mins % 60;
    if rem_mins > 0 {
        format!("{}h {}m", hours, rem_mins)
    } else {
        format!("{}h", hours)
    }
}

pub fn get_tools(prompts: &Prompts) -> Vec<Tool> {
    vec![
        make_tool_with_prompts(
            "mark_file",
            "Mark a file to signal intent to work on it (advisory, non-blocking). Returns warning if another agent has marked the file. Track changes via mark_updates.",
            json!({
                "agent": {
                    "type": "string",
                    "description": "Agent ID"
                },
                "file": {
                    "oneOf": [
                        { "type": "string" },
                        { "type": "array", "items": { "type": "string" } }
                    ],
                    "description": "Relative file path or array of file paths"
                },
                "task": {
                    "type": "string",
                    "description": "Optional task ID to associate with the mark (for auto-cleanup when task completes)"
                },
                "reason": {
                    "type": "string",
                    "description": "Optional reason for marking (visible to other agents)"
                }
            }),
            vec!["agent", "file"],
            prompts,
        ),
        make_tool_with_prompts(
            "unmark_file",
            "Remove mark from a file. Optionally include a note for the next agent.",
            json!({
                "agent": {
                    "type": "string",
                    "description": "Agent ID"
                },
                "file": {
                    "oneOf": [
                        { "type": "string" },
                        { "type": "array", "items": { "type": "string" } }
                    ],
                    "description": "Relative file path, array of paths, or '*' to unmark all files held by this agent"
                },
                "task": {
                    "type": "string",
                    "description": "Optional task ID - unmark all files associated with this task"
                },
                "reason": {
                    "type": "string",
                    "description": "Optional reason/note for next agent"
                }
            }),
            vec!["agent"],
            prompts,
        ),
        make_tool_with_prompts(
            "list_marks",
            "Get current file marks. Requires at least one filter: agent, task, or files.",
            json!({
                "files": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Specific file paths to check"
                },
                "agent": {
                    "type": "string",
                    "description": "Filter by agent ID"
                },
                "task": {
                    "type": "string",
                    "description": "Filter by task ID"
                }
            }),
            vec![],
            prompts,
        ),
        make_tool_with_prompts(
            "mark_updates",
            "Poll for file mark changes since last call. Returns new marks and removals. Use for coordination between agents.",
            json!({
                "agent": {
                    "type": "string",
                    "description": "Agent ID (tracks poll position)"
                }
            }),
            vec!["agent"],
            prompts,
        ),
    ]
}

pub fn mark_file(db: &Database, args: Value) -> Result<Value> {
    let worker_id = get_string(&args, "agent").ok_or_else(|| ToolError::missing_field("agent"))?;
    let file_paths =
        get_string_or_array(&args, "file").ok_or_else(|| ToolError::missing_field("file"))?;
    let task_id = get_string(&args, "task");
    let reason = get_string(&args, "reason");

    // Normalize all file paths to absolute canonical form
    let normalized_paths = normalize_file_paths(file_paths);

    let mut results = Vec::new();
    let mut warnings = Vec::new();

    for file_path in &normalized_paths {
        let warning = db.lock_file(
            file_path.clone(),
            &worker_id,
            reason.clone(),
            task_id.clone(),
        )?;

        if let Some(other_agent) = warning {
            warnings.push(json!({
                "file": file_path,
                "marked_by": other_agent
            }));
        }
        results.push(file_path.clone());
    }

    let mut response = json!({
        "success": true,
        "marked": results
    });

    if !warnings.is_empty() {
        response["warnings"] = json!(warnings);
    }

    Ok(response)
}

pub fn unmark_file(db: &Database, args: Value) -> Result<Value> {
    let worker_id = get_string(&args, "agent").ok_or_else(|| ToolError::missing_field("agent"))?;
    let reason = get_string(&args, "reason");
    let task_id = get_string(&args, "task");

    // If task_id is provided, unmark all files for that task
    if let Some(tid) = task_id {
        let unmarked = db.release_task_locks_verbose(&tid, reason)?;
        return Ok(json!({
            "success": true,
            "unmarked": unmarked.iter().map(|(f, w)| json!({
                "file": f,
                "agent": w
            })).collect::<Vec<_>>(),
            "count": unmarked.len()
        }));
    }

    // Get file parameter - can be string, array, or '*'
    let file_param = get_string_or_array(&args, "file");

    match file_param {
        Some(files) if files.len() == 1 && files[0] == "*" => {
            // Wildcard: unmark all files held by this agent
            let unmarked = db.release_worker_locks_verbose(&worker_id, reason)?;
            Ok(json!({
                "success": true,
                "unmarked": unmarked.iter().map(|(f, w)| json!({
                    "file": f,
                    "agent": w
                })).collect::<Vec<_>>(),
                "count": unmarked.len()
            }))
        }
        Some(files) => {
            // Normalize the file paths before unmarking
            let normalized_files = normalize_file_paths(files);
            // Specific files: unmark each one
            let unmarked = db.unlock_files_verbose(normalized_files, &worker_id, reason)?;
            Ok(json!({
                "success": true,
                "unmarked": unmarked.iter().map(|(f, w)| json!({
                    "file": f,
                    "agent": w
                })).collect::<Vec<_>>(),
                "count": unmarked.len()
            }))
        }
        None => {
            // No file specified and no task - error
            Err(ToolError::missing_field("file or task").into())
        }
    }
}

pub fn list_marks(db: &Database, default_format: OutputFormat, args: Value) -> Result<Value> {
    let files = get_string_array(&args, "files");
    let worker_id = get_string(&args, "agent");
    let task_id = get_string(&args, "task");
    let format = get_string(&args, "format")
        .and_then(|s| OutputFormat::parse(&s))
        .unwrap_or(default_format);

    // Require at least one filter
    if files.is_none() && worker_id.is_none() && task_id.is_none() {
        return Err(ToolError::invalid_value(
            "filter",
            "At least one filter required: agent, task, or files",
        )
        .into());
    }

    // Normalize file paths in the filter if provided
    let normalized_files = files.map(normalize_file_paths);

    let marks = db.get_file_locks(normalized_files, worker_id.as_deref(), task_id.as_deref())?;
    let now = crate::db::now_ms();

    match format {
        OutputFormat::Markdown => {
            let mut md = String::from("# File Marks\n\n");
            if marks.is_empty() {
                md.push_str("No marks found.\n");
            } else {
                md.push_str("| File | Agent | Task | Reason | Age |\n");
                md.push_str("|------|-------|------|--------|-----|\n");
                for (path, mark) in &marks {
                    let age_ms = now - mark.locked_at;
                    let age_str = format_duration(age_ms);
                    md.push_str(&format!(
                        "| {} | {} | {} | {} | {} |\n",
                        path,
                        mark.worker_id,
                        mark.task_id.as_deref().unwrap_or("-"),
                        mark.reason.as_deref().unwrap_or("-"),
                        age_str
                    ));
                }
            }
            Ok(markdown_to_json(md))
        }
        OutputFormat::Json => {
            let marks_json: Vec<Value> = marks
                .into_iter()
                .map(|(path, mark)| {
                    let age_ms = now - mark.locked_at;
                    json!({
                        "file": path,
                        "agent": mark.worker_id,
                        "task_id": mark.task_id,
                        "reason": mark.reason,
                        "marked_at": mark.locked_at,
                        "mark_age_ms": age_ms
                    })
                })
                .collect();

            Ok(json!({ "marks": marks_json }))
        }
    }
}

/// Async version of mark_updates.
pub async fn mark_updates_async(db: std::sync::Arc<Database>, args: Value) -> Result<Value> {
    let worker_id = get_string(&args, "agent").ok_or_else(|| ToolError::missing_field("agent"))?;

    // Run on blocking thread pool since db operations are synchronous
    let updates = tokio::task::spawn_blocking(move || db.claim_updates(&worker_id))
        .await
        .map_err(|e| anyhow::anyhow!("Task join error: {}", e))??;

    Ok(json!({
        "new_marks": updates.new_claims.iter().map(|e| json!({
            "file": e.file_path,
            "agent": e.worker_id,
            "reason": e.reason,
            "marked_at": e.timestamp
        })).collect::<Vec<_>>(),
        "removed_marks": updates.dropped_claims.iter().map(|e| json!({
            "file": e.file_path,
            "agent": e.worker_id,
            "reason": e.reason,
            "removed_at": e.timestamp
        })).collect::<Vec<_>>(),
        "sequence": updates.sequence
    }))
}

/// Synchronous version of mark_updates.
pub fn mark_updates(db: &Database, args: Value) -> Result<Value> {
    let worker_id = get_string(&args, "agent").ok_or_else(|| ToolError::missing_field("agent"))?;

    let updates = db.claim_updates(&worker_id)?;

    Ok(json!({
        "new_marks": updates.new_claims.iter().map(|e| json!({
            "file": e.file_path,
            "agent": e.worker_id,
            "reason": e.reason,
            "marked_at": e.timestamp
        })).collect::<Vec<_>>(),
        "removed_marks": updates.dropped_claims.iter().map(|e| json!({
            "file": e.file_path,
            "agent": e.worker_id,
            "reason": e.reason,
            "removed_at": e.timestamp
        })).collect::<Vec<_>>(),
        "sequence": updates.sequence
    }))
}

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

    #[test]
    fn test_normalize_path_components() {
        // Test removing current directory markers
        let path = Path::new("/foo/./bar/./baz");
        let normalized = normalize_path_components(path);
        assert_eq!(path_to_forward_slashes(&normalized), "/foo/bar/baz");

        // Test resolving parent directory markers
        let path = Path::new("/foo/bar/../baz");
        let normalized = normalize_path_components(path);
        assert_eq!(path_to_forward_slashes(&normalized), "/foo/baz");

        // Test complex case
        let path = Path::new("/foo/bar/./baz/../qux");
        let normalized = normalize_path_components(path);
        assert_eq!(path_to_forward_slashes(&normalized), "/foo/bar/qux");
    }

    #[test]
    fn test_path_to_forward_slashes() {
        // Test Windows-style path
        let path = Path::new("C:\\foo\\bar\\baz");
        assert_eq!(path_to_forward_slashes(path), "C:/foo/bar/baz");

        // Test Unix-style path (no change)
        let path = Path::new("/foo/bar/baz");
        assert_eq!(path_to_forward_slashes(path), "/foo/bar/baz");
    }

    #[test]
    fn test_normalize_file_paths() {
        // Test that normalization is applied to all paths in a vector
        let paths = vec!["src/main.rs".to_string(), "./src/lib.rs".to_string()];
        let normalized = normalize_file_paths(paths);

        // All paths should be absolute (start with / or drive letter on Windows)
        for path in &normalized {
            assert!(
                path.starts_with('/') || (path.len() > 2 && path.chars().nth(1) == Some(':')),
                "Path should be absolute: {}",
                path
            );
        }
    }
}