brainwires-relay 0.2.0

MCP server framework, relay client, and agent communication backbone for Brainwires
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
//! Agent Management Tools for MCP
//!
//! Provides MCP tools for spawning and managing task agents

use brainwires_core::{Tool, ToolInputSchema};
use serde_json::json;
use std::collections::HashMap;

/// Registry of agent management tools
pub struct AgentToolRegistry {
    tools: Vec<Tool>,
}

impl AgentToolRegistry {
    /// Create a new agent tool registry
    pub fn new() -> Self {
        let tools = vec![
            Tool {
                name: "agent_spawn".to_string(),
                description: "Spawn a new task agent to work on a subtask autonomously. \
                              The agent will execute the task in the background and report results. \
                              Useful for breaking down large workloads hierarchically."
                    .to_string(),
                input_schema: ToolInputSchema::object(
                    {
                        let mut props = HashMap::new();
                        props.insert("description".to_string(), json!({
                            "type": "string",
                            "description": "Description of the task for the agent to execute"
                        }));
                        props.insert("working_directory".to_string(), json!({
                            "type": "string",
                            "description": "Optional working directory for file operations. If not specified, uses the MCP server's current directory."
                        }));
                        props.insert("max_iterations".to_string(), json!({
                            "type": "integer",
                            "description": "Optional maximum number of iterations before the agent stops (default: 100). Set lower for simple tasks or higher for complex ones."
                        }));
                        props.insert("enable_validation".to_string(), json!({
                            "type": "boolean",
                            "description": "Enable automatic validation checks before completion (default: true). Validates syntax, duplicates, and build success."
                        }));
                        props.insert("build_type".to_string(), json!({
                            "type": "string",
                            "enum": ["npm", "cargo", "typescript"],
                            "description": "Optional build type for validation (npm, cargo, or typescript). If specified, agent must pass build before completing."
                        }));
                        props.insert("enable_mdap".to_string(), json!({
                            "type": "boolean",
                            "description": "Enable MDAP (Massively Decomposed Agentic Processes) for zero-error execution through task decomposition and multi-agent voting (default: false)"
                        }));
                        props.insert("mdap_k".to_string(), json!({
                            "type": "integer",
                            "description": "Vote margin threshold for MDAP (default: 3). Higher values = more reliability but higher cost. Range: 1-7."
                        }));
                        props.insert("mdap_target_success".to_string(), json!({
                            "type": "number",
                            "description": "Target success rate for MDAP (default: 0.95). Range: 0.90-0.99."
                        }));
                        props.insert("mdap_preset".to_string(), json!({
                            "type": "string",
                            "enum": ["default", "high_reliability", "cost_optimized"],
                            "description": "MDAP preset: 'default' (k=3, 95%), 'high_reliability' (k=5, 99%), 'cost_optimized' (k=2, 90%)"
                        }));
                        props
                    },
                    vec!["description".to_string()],
                ),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_list".to_string(),
                description: "List all currently running task agents and their status"
                    .to_string(),
                input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_status".to_string(),
                description: "Get detailed status of a specific task agent".to_string(),
                input_schema: ToolInputSchema::object(
                    {
                        let mut props = HashMap::new();
                        props.insert("agent_id".to_string(), json!({
                            "type": "string",
                            "description": "ID of the agent to query"
                        }));
                        props
                    },
                    vec!["agent_id".to_string()],
                ),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_stop".to_string(),
                description: "Stop a running task agent".to_string(),
                input_schema: ToolInputSchema::object(
                    {
                        let mut props = HashMap::new();
                        props.insert("agent_id".to_string(), json!({
                            "type": "string",
                            "description": "ID of the agent to stop"
                        }));
                        props
                    },
                    vec!["agent_id".to_string()],
                ),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_await".to_string(),
                description: "Wait for a task agent to complete and return its result. \
                              Unlike agent_status which returns immediately, this tool blocks \
                              until the agent finishes (completes or fails) and returns the final result."
                    .to_string(),
                input_schema: ToolInputSchema::object(
                    {
                        let mut props = HashMap::new();
                        props.insert("agent_id".to_string(), json!({
                            "type": "string",
                            "description": "ID of the agent to wait for"
                        }));
                        props.insert("timeout_secs".to_string(), json!({
                            "type": "integer",
                            "description": "Optional timeout in seconds. If not provided, waits indefinitely."
                        }));
                        props
                    },
                    vec!["agent_id".to_string()],
                ),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_pool_stats".to_string(),
                description: "Get statistics about the agent pool".to_string(),
                input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "agent_file_locks".to_string(),
                description: "List all currently held file locks by agents".to_string(),
                input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
                requires_approval: false,
                ..Default::default()
            },
            // Self-improvement tools
            Tool {
                name: "self_improve_start".to_string(),
                description: "Start an autonomous self-improvement loop that analyzes the codebase \
                              and spawns agents to fix issues (clippy warnings, TODOs, missing docs, \
                              dead code, test gaps, code smells)"
                    .to_string(),
                input_schema: ToolInputSchema::object(
                    {
                        let mut props = HashMap::new();
                        props.insert("max_cycles".to_string(), json!({
                            "type": "integer",
                            "description": "Maximum number of improvement cycles (default: 10)"
                        }));
                        props.insert("max_budget".to_string(), json!({
                            "type": "number",
                            "description": "Maximum budget in dollars (default: 10.0)"
                        }));
                        props.insert("dry_run".to_string(), json!({
                            "type": "boolean",
                            "description": "List tasks without executing (default: false)"
                        }));
                        props.insert("strategies".to_string(), json!({
                            "type": "string",
                            "description": "Comma-separated list of strategies: clippy,todo_scanner,doc_gaps,test_coverage,refactoring,dead_code (empty = all)"
                        }));
                        props.insert("no_bridge".to_string(), json!({
                            "type": "boolean",
                            "description": "Disable MCP bridge execution path (default: false)"
                        }));
                        props.insert("no_direct".to_string(), json!({
                            "type": "boolean",
                            "description": "Disable direct agent execution path (default: false)"
                        }));
                        props
                    },
                    vec![],
                ),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "self_improve_status".to_string(),
                description: "Get the status of a running self-improvement session"
                    .to_string(),
                input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
                requires_approval: false,
                ..Default::default()
            },
            Tool {
                name: "self_improve_stop".to_string(),
                description: "Stop a running self-improvement session"
                    .to_string(),
                input_schema: ToolInputSchema::object(HashMap::new(), vec![]),
                requires_approval: false,
                ..Default::default()
            },
        ];

        Self { tools }
    }

    /// Get all agent management tools
    pub fn get_tools(&self) -> &[Tool] {
        &self.tools
    }
}

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

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

    #[test]
    fn test_registry_creation() {
        let registry = AgentToolRegistry::new();
        assert_eq!(registry.get_tools().len(), 10, "Should have 10 agent tools");
    }

    #[test]
    fn test_default_creation() {
        let registry = AgentToolRegistry::default();
        assert_eq!(registry.get_tools().len(), 10);
    }

    #[test]
    fn test_agent_spawn_tool() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        let spawn_tool = tools
            .iter()
            .find(|t| t.name == "agent_spawn")
            .expect("agent_spawn tool should exist");

        assert_eq!(spawn_tool.name, "agent_spawn");
        assert!(spawn_tool.description.contains("autonomous"));
        assert!(!spawn_tool.requires_approval);

        // Check schema structure
        assert_eq!(spawn_tool.input_schema.schema_type, "object");
        assert!(spawn_tool.input_schema.properties.is_some());
        let props = spawn_tool.input_schema.properties.as_ref().unwrap();
        assert!(props.contains_key("description"));

        assert!(spawn_tool.input_schema.required.is_some());
        let required = spawn_tool.input_schema.required.as_ref().unwrap();
        assert!(required.contains(&"description".to_string()));
    }

    #[test]
    fn test_agent_list_tool() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        let list_tool = tools
            .iter()
            .find(|t| t.name == "agent_list")
            .expect("agent_list tool should exist");

        assert_eq!(list_tool.name, "agent_list");
        assert!(list_tool.description.contains("running"));
        assert!(!list_tool.requires_approval);

        // Should have empty properties
        assert_eq!(list_tool.input_schema.schema_type, "object");
        let props = list_tool.input_schema.properties.as_ref().unwrap();
        assert!(props.is_empty());
    }

    #[test]
    fn test_agent_status_tool() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        let status_tool = tools
            .iter()
            .find(|t| t.name == "agent_status")
            .expect("agent_status tool should exist");

        assert_eq!(status_tool.name, "agent_status");
        assert!(status_tool.description.contains("status"));
        assert!(!status_tool.requires_approval);

        // Should require agent_id parameter
        let props = status_tool.input_schema.properties.as_ref().unwrap();
        assert!(props.contains_key("agent_id"));

        let required = status_tool.input_schema.required.as_ref().unwrap();
        assert!(required.contains(&"agent_id".to_string()));
    }

    #[test]
    fn test_agent_stop_tool() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        let stop_tool = tools
            .iter()
            .find(|t| t.name == "agent_stop")
            .expect("agent_stop tool should exist");

        assert_eq!(stop_tool.name, "agent_stop");
        assert!(stop_tool.description.contains("Stop"));
        assert!(!stop_tool.requires_approval);

        // Should require agent_id parameter
        let props = stop_tool.input_schema.properties.as_ref().unwrap();
        assert!(props.contains_key("agent_id"));

        let required = stop_tool.input_schema.required.as_ref().unwrap();
        assert!(required.contains(&"agent_id".to_string()));
    }

    #[test]
    fn test_agent_await_tool() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        let await_tool = tools
            .iter()
            .find(|t| t.name == "agent_await")
            .expect("agent_await tool should exist");

        assert_eq!(await_tool.name, "agent_await");
        assert!(await_tool.description.contains("Wait"));
        assert!(await_tool.description.contains("complete"));
        assert!(!await_tool.requires_approval);

        // Should require agent_id parameter
        let props = await_tool.input_schema.properties.as_ref().unwrap();
        assert!(props.contains_key("agent_id"));
        assert!(props.contains_key("timeout_secs"));

        let required = await_tool.input_schema.required.as_ref().unwrap();
        assert!(required.contains(&"agent_id".to_string()));
        // timeout_secs is optional
        assert!(!required.contains(&"timeout_secs".to_string()));
    }

    #[test]
    fn test_all_tools_have_descriptions() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        for tool in tools {
            assert!(
                !tool.description.is_empty(),
                "Tool {} should have a description",
                tool.name
            );
        }
    }

    #[test]
    fn test_all_tools_have_object_schemas() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        for tool in tools {
            assert_eq!(
                tool.input_schema.schema_type, "object",
                "Tool {} should have object schema",
                tool.name
            );
        }
    }

    #[test]
    fn test_tool_names_are_prefixed() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        for tool in tools {
            assert!(
                tool.name.starts_with("agent_") || tool.name.starts_with("self_improve_"),
                "Tool {} should be prefixed with 'agent_' or 'self_improve_'",
                tool.name
            );
        }
    }

    #[test]
    fn test_no_approval_required() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        for tool in tools {
            assert!(
                !tool.requires_approval,
                "Tool {} should not require approval for autonomous operation",
                tool.name
            );
        }
    }

    #[test]
    fn test_schema_serialization() {
        let registry = AgentToolRegistry::new();
        let tools = registry.get_tools();

        for tool in tools {
            let serialized = serde_json::to_value(&tool.input_schema);
            assert!(
                serialized.is_ok(),
                "Tool {} schema should serialize to JSON",
                tool.name
            );

            let value = serialized.unwrap();
            assert!(value.is_object());
            assert_eq!(value["type"], "object");
        }
    }
}