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
//! MCP tool implementations.

pub mod agents;
pub mod attachments;
pub mod claiming;
pub mod context;
pub mod deps;
pub mod files;
pub mod gates;
pub mod query;
pub mod schema;
pub mod search;
pub mod skills;
pub mod tasks;
pub mod tracking;

pub use context::ToolContext;

use crate::config::{
    AttachmentsConfig, AutoAdvanceConfig, DependenciesConfig, IdsConfig, PhasesConfig, Prompts,
    ServerPaths, StatesConfig, TagsConfig, workflows::WorkflowsConfig,
};
use crate::db::Database;
use crate::error::ToolError;
use crate::format::{OutputFormat, ToolResult};
use anyhow::Result;
use rmcp::model::Tool;
use serde_json::Value;
use std::path::PathBuf;
use std::sync::Arc;

/// Tool handler that processes MCP tool calls.
pub struct ToolHandler {
    pub db: Arc<Database>,
    pub media_dir: PathBuf,
    pub skills_dir: PathBuf,
    pub server_paths: Arc<ServerPaths>,
    pub prompts: Arc<Prompts>,
    pub states_config: Arc<StatesConfig>,
    pub phases_config: Arc<PhasesConfig>,
    pub deps_config: Arc<DependenciesConfig>,
    pub auto_advance: Arc<AutoAdvanceConfig>,
    pub attachments_config: Arc<AttachmentsConfig>,
    pub tags_config: Arc<TagsConfig>,
    pub ids_config: Arc<IdsConfig>,
    /// Workflow config with named_workflows cache for per-worker selection
    pub workflows: Arc<WorkflowsConfig>,
    pub default_format: OutputFormat,
    pub path_mapper: Arc<crate::paths::PathMapper>,
}

impl ToolHandler {
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        db: Arc<Database>,
        media_dir: PathBuf,
        skills_dir: PathBuf,
        server_paths: Arc<ServerPaths>,
        prompts: Arc<Prompts>,
        states_config: Arc<StatesConfig>,
        phases_config: Arc<PhasesConfig>,
        deps_config: Arc<DependenciesConfig>,
        auto_advance: Arc<AutoAdvanceConfig>,
        attachments_config: Arc<AttachmentsConfig>,
        tags_config: Arc<TagsConfig>,
        ids_config: Arc<IdsConfig>,
        workflows: Arc<WorkflowsConfig>,
        default_format: OutputFormat,
        path_mapper: Arc<crate::paths::PathMapper>,
    ) -> Self {
        Self {
            db,
            media_dir,
            skills_dir,
            server_paths,
            prompts,
            states_config,
            phases_config,
            deps_config,
            auto_advance,
            attachments_config,
            tags_config,
            ids_config,
            workflows,
            default_format,
            path_mapper,
        }
    }

    /// Get the workflow config for a worker.
    /// Looks up the worker's workflow name and returns the corresponding config,
    /// or falls back to the configured default workflow, or the base config.
    pub fn get_workflow_for_worker(&self, worker_id: &str) -> Arc<WorkflowsConfig> {
        // Look up worker's workflow name from database
        if let Ok(Some(worker)) = self.db.get_worker(worker_id) {
            if let Some(ref workflow_name) = worker.workflow {
                // Try to get from named_workflows cache
                if let Some(workflow_config) = self.workflows.get_named_workflow(workflow_name) {
                    return Arc::clone(workflow_config);
                }
            }
        }
        // Fall back to configured default workflow, or base config
        if let Some(default_workflow) = self.workflows.get_default_workflow() {
            Arc::clone(default_workflow)
        } else {
            Arc::clone(&self.workflows)
        }
    }

    /// Get all available tools.
    pub fn get_tools(&self) -> Vec<Tool> {
        let mut tools = Vec::new();

        // Worker tools
        tools.extend(agents::get_tools(&self.prompts));

        // Task tools (with dynamic state schema)
        tools.extend(tasks::get_tools(&self.prompts, &self.states_config));

        // Tracking tools
        tools.extend(tracking::get_tools(&self.prompts, &self.states_config));

        // Dependency tools
        tools.extend(deps::get_tools(&self.prompts, &self.deps_config));

        // Claiming tools (with dynamic state schema)
        tools.extend(claiming::get_tools(&self.prompts, &self.states_config));

        // File coordination tools
        tools.extend(files::get_tools(&self.prompts));

        // Attachment tools
        tools.extend(attachments::get_tools(&self.prompts));

        // Skill tools (no prompts needed, always available)
        tools.extend(skills::get_tools());

        // Schema introspection tools
        tools.extend(schema::get_tools());

        // Search tools
        tools.extend(search::get_tools(&self.prompts));

        // Query tools (read-only SQL)
        tools.extend(query::get_tools());

        // Gate checking tools
        tools.extend(gates::get_tools(&self.prompts));

        tools
    }

    /// Call a tool by name.
    #[allow(unused_variables)]
    pub async fn call_tool(
        &self,
        name: &str,
        arguments: Value,
        ctx: &ToolContext,
    ) -> Result<ToolResult> {
        // Helper to wrap JSON results
        let json = |r: Result<Value>| r.map(ToolResult::Json);

        match name {
            // Worker tools
            "connect" => json(agents::connect(
                &self.db,
                &self.server_paths,
                &self.states_config,
                &self.phases_config,
                &self.deps_config,
                &self.tags_config,
                &self.ids_config,
                arguments,
            )),
            "disconnect" => json(agents::disconnect(&self.db, &self.states_config, arguments)),
            "list_agents" => agents::list_agents(
                &self.db,
                &self.states_config,
                self.default_format,
                arguments,
            ),
            "cleanup_stale" => json(agents::cleanup_stale(
                &self.db,
                &self.states_config,
                arguments,
            )),

            // Task tools
            "create" => json(tasks::create(
                &self.db,
                &self.states_config,
                &self.phases_config,
                &self.tags_config,
                &self.ids_config,
                arguments,
            )),
            "create_tree" => json(tasks::create_tree(
                &self.db,
                &self.states_config,
                &self.phases_config,
                &self.tags_config,
                &self.ids_config,
                arguments,
            )),
            "get" => json(tasks::get(&self.db, self.default_format, arguments)),
            "list_tasks" => json(tasks::list_tasks(
                &self.db,
                &self.states_config,
                &self.deps_config,
                self.default_format,
                arguments,
            )),
            "update" => {
                // Look up worker's workflow for prompts
                let worker_id = arguments
                    .get("worker_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let workflow = self.get_workflow_for_worker(worker_id);
                json(tasks::update(
                    &self.db,
                    &self.attachments_config,
                    &self.states_config,
                    &self.phases_config,
                    &self.deps_config,
                    &self.auto_advance,
                    &self.tags_config,
                    &workflow,
                    arguments,
                ))
            }
            "delete" => json(tasks::delete(&self.db, arguments)),
            "scan" => json(tasks::scan(&self.db, self.default_format, arguments)),

            // Tracking tools
            "thinking" => json(tracking::thinking(&self.db, arguments)),
            "task_history" => json(tracking::task_history(
                &self.db,
                &self.states_config,
                self.default_format,
                arguments,
            )),
            "log_metrics" => json(tracking::log_metrics(&self.db, arguments)),
            "get_metrics" => json(tracking::get_metrics(&self.db, arguments)),
            "project_history" => json(tracking::project_history(
                &self.db,
                self.default_format,
                arguments,
            )),

            // Dependency tools
            "link" => json(deps::link(&self.db, &self.deps_config, arguments)),
            "unlink" => json(deps::unlink(&self.db, arguments)),
            "relink" => json(deps::relink(&self.db, &self.deps_config, arguments)),

            // Claiming tools
            "claim" => {
                // Look up worker's workflow for prompts
                let worker_id = arguments
                    .get("worker_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let workflow = self.get_workflow_for_worker(worker_id);
                json(claiming::claim(
                    &self.db,
                    &self.states_config,
                    &self.phases_config,
                    &self.deps_config,
                    &self.auto_advance,
                    &workflow,
                    arguments,
                ))
            }

            // File coordination tools
            "mark_file" => json(files::mark_file(&self.db, arguments)),
            "unmark_file" => json(files::unmark_file(&self.db, arguments)),
            "list_marks" => json(files::list_marks(&self.db, self.default_format, arguments)),
            "mark_updates" => {
                json(files::mark_updates_async(std::sync::Arc::clone(&self.db), arguments).await)
            }

            // Attachment tools
            "attach" => json(attachments::attach(
                &self.db,
                &self.media_dir,
                &self.attachments_config,
                arguments,
            )),
            "attachments" => json(attachments::attachments(
                &self.db,
                &self.media_dir,
                self.default_format,
                arguments,
            )),
            "detach" => json(attachments::detach(&self.db, &self.media_dir, arguments)),

            // Skill tools
            name if skills::is_skill_tool(name) => {
                json(skills::call_tool(&self.skills_dir, name, &arguments))
            }

            // Schema introspection tools
            "get_schema" => json(schema::get_schema(&self.db, arguments)),

            // Search tools
            "search" => json(search::search(&self.db, arguments)),

            // Query tools (read-only SQL)
            "query" => query::query(&self.db, self.default_format, arguments),

            // Gate checking tools
            "check_gates" => {
                // Look up worker's workflow for gate definitions
                // Since check_gates doesn't require worker_id, use base workflow
                json(gates::check_gates(&self.db, &self.workflows, arguments))
            }

            _ => Err(ToolError::unknown_tool(name).into()),
        }
    }
}

/// Helper to create a tool definition.
pub fn make_tool(name: &str, description: &str, properties: Value, required: Vec<&str>) -> Tool {
    let input_schema = rmcp::model::JsonObject::from_iter([
        ("type".to_string(), serde_json::json!("object")),
        ("properties".to_string(), properties),
        ("required".to_string(), serde_json::json!(required)),
    ]);

    Tool::new(name.to_string(), description.to_string(), input_schema)
}

/// Helper to create a tool definition with prompt overrides.
/// Looks up the tool description in prompts, falls back to default_description.
pub fn make_tool_with_prompts(
    name: &str,
    default_description: &str,
    properties: Value,
    required: Vec<&str>,
    prompts: &Prompts,
) -> Tool {
    let description = prompts
        .get_tool_description(name)
        .unwrap_or(default_description);
    make_tool(name, description, properties, required)
}

/// Helper to get a string from arguments.
pub fn get_string(args: &Value, key: &str) -> Option<String> {
    args.get(key).and_then(|v| v.as_str().map(String::from))
}

/// Helper to get an i32 from arguments.
pub fn get_i32(args: &Value, key: &str) -> Option<i32> {
    args.get(key).and_then(|v| v.as_i64().map(|n| n as i32))
}

/// Helper to get an i64 from arguments.
pub fn get_i64(args: &Value, key: &str) -> Option<i64> {
    args.get(key).and_then(|v| v.as_i64())
}

/// Helper to get an f64 from arguments.
pub fn get_f64(args: &Value, key: &str) -> Option<f64> {
    args.get(key).and_then(|v| v.as_f64())
}

/// Helper to get a bool from arguments.
pub fn get_bool(args: &Value, key: &str) -> Option<bool> {
    args.get(key).and_then(|v| v.as_bool())
}

/// Helper to get a string array from arguments.
pub fn get_string_array(args: &Value, key: &str) -> Option<Vec<String>> {
    args.get(key).and_then(|v| {
        v.as_array().map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
    })
}

/// Helper to get either a single string or array of strings from arguments.
/// Normalizes to a Vec<String>.
pub fn get_string_or_array(args: &Value, key: &str) -> Option<Vec<String>> {
    args.get(key).and_then(|v| {
        if let Some(s) = v.as_str() {
            // Single string - wrap in vec
            Some(vec![s.to_string()])
        } else {
            v.as_array().map(|arr| {
                arr.iter()
                    .filter_map(|item| item.as_str().map(String::from))
                    .collect()
            })
        }
    })
}