synwire-agent 0.1.0

Agent runtime implementations for synwire
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
//! `code.*` tool provider for semantic code navigation and search.
//!
//! The tools in this module provide multi-backend dispatch for code
//! intelligence operations. When no backend is configured, each tool returns a
//! descriptive message explaining which dependencies are required.
//!
//! The actual backend dispatch (daemon proxy, LSP client) is injected by the
//! consumer (e.g. the MCP server) at startup.

use synwire_core::error::SynwireError;
use synwire_core::tools::{
    StaticToolProvider, StructuredTool, Tool, ToolOutput, ToolProvider, ToolSchema,
};

/// Configuration controlling which `code.*` backends are available.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct CodeToolConfig {
    /// If set, daemon-backed tools are available.
    pub daemon_available: bool,
    /// If set, LSP-backed tools are available.
    pub lsp_available: bool,
}

/// Build a tool provider containing all `code.*` tools.
///
/// The returned provider includes:
/// - `code.search` (semantic/graph/community modes)
/// - `code.search_hybrid` (combined semantic + keyword search)
/// - `code.definition` (LSP-first, graph fallback)
/// - `code.references` (LSP -> xref -> graph fallback)
/// - `code.symbols` (LSP with skeleton fallback)
/// - `code.type_info` (LSP hover)
/// - `code.dependencies` (package/module dependency graph)
/// - `code.community_members` (community detection clusters)
/// - `code.trace_dataflow` (data flow analysis)
/// - `code.trace_callers` (call graph traversal)
/// - `code.fault_localize` (SBFL-based fault localization)
///
/// # Errors
///
/// Returns [`SynwireError`] if any tool fails validation.
pub fn code_tool_provider() -> Result<Box<dyn ToolProvider>, SynwireError> {
    let tools: Vec<Box<dyn Tool>> = vec![
        Box::new(build_code_search()?),
        Box::new(build_code_search_hybrid()?),
        Box::new(build_code_definition()?),
        Box::new(build_code_references()?),
        Box::new(build_code_symbols()?),
        Box::new(build_code_type_info()?),
        Box::new(build_code_dependencies()?),
        Box::new(build_code_community_members()?),
        Box::new(build_code_trace_dataflow()?),
        Box::new(build_code_trace_callers()?),
        Box::new(build_code_fault_localize()?),
    ];
    Ok(Box::new(StaticToolProvider::new(tools)))
}

/// Create a stub tool that returns a "not configured" message.
///
/// This is the default behaviour until the consumer injects a real backend.
fn stub_response(tool_name: &str) -> ToolOutput {
    ToolOutput {
        content: format!(
            "{tool_name}: not configured. This tool requires a daemon or LSP backend. \
             Configure the appropriate backend to enable this tool."
        ),
        ..Default::default()
    }
}

fn build_code_search() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.search")
        .description(
            "Search code semantically using embeddings, call graphs, or community clusters. \
             Supports modes: semantic, graph, community.",
        )
        .schema(ToolSchema {
            name: "code.search".into(),
            description: "Search code semantically".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Natural language search query"
                    },
                    "mode": {
                        "type": "string",
                        "enum": ["semantic", "graph", "community"],
                        "description": "Search mode (default: semantic)"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of results (default: 10)"
                    }
                },
                "required": ["query"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.search")) }))
        .build()
}

fn build_code_search_hybrid() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.search_hybrid")
        .description(
            "Combined semantic and keyword search across the codebase. \
             Merges embedding similarity with BM25 text matching.",
        )
        .schema(ToolSchema {
            name: "code.search_hybrid".into(),
            description: "Hybrid semantic + keyword code search".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Natural language search query"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of results (default: 10)"
                    }
                },
                "required": ["query"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.search_hybrid")) }))
        .build()
}

fn build_code_definition() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.definition")
        .description(
            "Go to definition of a symbol. Uses LSP when available, \
             falls back to call graph data.",
        )
        .schema(ToolSchema {
            name: "code.definition".into(),
            description: "Find the definition of a symbol".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path containing the symbol"
                    },
                    "line": {
                        "type": "integer",
                        "description": "1-based line number"
                    },
                    "column": {
                        "type": "integer",
                        "description": "1-based column number"
                    },
                    "symbol": {
                        "type": "string",
                        "description": "Symbol name (used for graph fallback)"
                    }
                },
                "required": ["file", "line", "column"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.definition")) }))
        .build()
}

fn build_code_references() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.references")
        .description(
            "Find all references to a symbol. Tries LSP, cross-reference index, \
             then call graph in order of availability.",
        )
        .schema(ToolSchema {
            name: "code.references".into(),
            description: "Find all references to a symbol".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path containing the symbol"
                    },
                    "line": {
                        "type": "integer",
                        "description": "1-based line number"
                    },
                    "column": {
                        "type": "integer",
                        "description": "1-based column number"
                    },
                    "symbol": {
                        "type": "string",
                        "description": "Symbol name (used for index/graph fallback)"
                    }
                },
                "required": ["file", "line", "column"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.references")) }))
        .build()
}

fn build_code_symbols() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.symbols")
        .description(
            "List symbols in a file or workspace. Uses LSP document/workspace symbols \
             when available, falls back to tree-sitter skeleton extraction.",
        )
        .schema(ToolSchema {
            name: "code.symbols".into(),
            description: "List symbols in a file or workspace".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path (omit for workspace-wide search)"
                    },
                    "query": {
                        "type": "string",
                        "description": "Filter symbols by name pattern"
                    }
                },
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.symbols")) }))
        .build()
}

fn build_code_type_info() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.type_info")
        .description(
            "Get type information and documentation for a symbol at a given position. \
             Backed by LSP hover.",
        )
        .schema(ToolSchema {
            name: "code.type_info".into(),
            description: "Get type info for a symbol via LSP hover".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path"
                    },
                    "line": {
                        "type": "integer",
                        "description": "1-based line number"
                    },
                    "column": {
                        "type": "integer",
                        "description": "1-based column number"
                    }
                },
                "required": ["file", "line", "column"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.type_info")) }))
        .build()
}

fn build_code_dependencies() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.dependencies")
        .description("List package or module dependencies for a file or the project root.")
        .schema(ToolSchema {
            name: "code.dependencies".into(),
            description: "List package/module dependencies".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path (omit for project-level dependencies)"
                    },
                    "depth": {
                        "type": "integer",
                        "description": "Maximum dependency depth (default: 1)"
                    }
                },
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.dependencies")) }))
        .build()
}

fn build_code_community_members() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.community_members")
        .description(
            "List symbols belonging to the same community cluster as the given symbol. \
             Requires community detection index (hit-leiden).",
        )
        .schema(ToolSchema {
            name: "code.community_members".into(),
            description: "List symbols in the same community cluster".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "Fully qualified symbol name"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of members (default: 20)"
                    }
                },
                "required": ["symbol"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.community_members")) }))
        .build()
}

fn build_code_trace_dataflow() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.trace_dataflow")
        .description("Trace data flow forwards or backwards from a variable or expression.")
        .schema(ToolSchema {
            name: "code.trace_dataflow".into(),
            description: "Trace data flow from a variable".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "file": {
                        "type": "string",
                        "description": "File path"
                    },
                    "line": {
                        "type": "integer",
                        "description": "1-based line number"
                    },
                    "column": {
                        "type": "integer",
                        "description": "1-based column number"
                    },
                    "direction": {
                        "type": "string",
                        "enum": ["forward", "backward"],
                        "description": "Trace direction (default: forward)"
                    },
                    "depth": {
                        "type": "integer",
                        "description": "Maximum trace depth (default: 5)"
                    }
                },
                "required": ["file", "line", "column"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.trace_dataflow")) }))
        .build()
}

fn build_code_trace_callers() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.trace_callers")
        .description(
            "Trace the call graph upward from a function to find all callers, \
             transitively up to a configurable depth.",
        )
        .schema(ToolSchema {
            name: "code.trace_callers".into(),
            description: "Trace callers of a function".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "symbol": {
                        "type": "string",
                        "description": "Fully qualified function name"
                    },
                    "depth": {
                        "type": "integer",
                        "description": "Maximum caller depth (default: 3)"
                    }
                },
                "required": ["symbol"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.trace_callers")) }))
        .build()
}

fn build_code_fault_localize() -> Result<StructuredTool, SynwireError> {
    StructuredTool::builder()
        .name("code.fault_localize")
        .description(
            "Rank files and functions by suspiciousness using spectrum-based fault \
             localization (SBFL). Requires test coverage data.",
        )
        .schema(ToolSchema {
            name: "code.fault_localize".into(),
            description: "SBFL fault localization".into(),
            parameters: serde_json::json!({
                "type": "object",
                "properties": {
                    "failing_tests": {
                        "type": "array",
                        "items": { "type": "string" },
                        "description": "List of failing test identifiers"
                    },
                    "formula": {
                        "type": "string",
                        "enum": ["ochiai", "tarantula", "dstar"],
                        "description": "SBFL formula (default: ochiai)"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of results (default: 20)"
                    }
                },
                "required": ["failing_tests"],
                "additionalProperties": false,
            }),
        })
        .func(|_input| Box::pin(async { Ok(stub_response("code.fault_localize")) }))
        .build()
}

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

    #[tokio::test]
    async fn code_provider_discovers_all_tools() {
        let provider = code_tool_provider().unwrap();
        let tools = provider.discover_tools().await.unwrap();
        assert_eq!(tools.len(), 11);
    }

    #[tokio::test]
    async fn code_provider_get_by_name() {
        let provider = code_tool_provider().unwrap();
        let tool = provider.get_tool("code.search").await.unwrap();
        assert!(tool.is_some());
        let missing = provider.get_tool("code.nonexistent").await.unwrap();
        assert!(missing.is_none());
    }

    #[tokio::test]
    async fn stub_tools_return_not_configured() {
        let provider = code_tool_provider().unwrap();
        let tool = provider.get_tool("code.definition").await.unwrap().unwrap();
        let output = tool
            .invoke(serde_json::json!({"file": "main.rs", "line": 1, "column": 1}))
            .await
            .unwrap();
        assert!(output.content.contains("not configured"));
    }
}