1use codive_core::tool::{Tool, ToolOutput};
7use codive_lsp::{
8 lsp, uri_to_file_path, DocumentSymbolResponse, Location, LspOperation, SymbolInformation,
9};
10use async_trait::async_trait;
11use serde::Deserialize;
12use std::path::Path;
13use tracing::{debug, warn};
14
15pub struct LspTool;
17
18impl LspTool {
19 pub fn new() -> Self {
21 Self
22 }
23}
24
25impl Default for LspTool {
26 fn default() -> Self {
27 Self::new()
28 }
29}
30
31#[derive(Debug, Deserialize)]
33struct LspParams {
34 operation: String,
36 #[serde(rename = "filePath")]
38 file_path: String,
39 line: u32,
41 character: u32,
43}
44
45#[async_trait]
46impl Tool for LspTool {
47 fn name(&self) -> &str {
48 "lsp"
49 }
50
51 fn description(&self) -> &str {
52 r#"Interact with Language Server Protocol (LSP) servers to get code intelligence features.
53
54Supported operations:
55- goToDefinition: Find where a symbol is defined
56- findReferences: Find all references to a symbol
57- hover: Get hover information (documentation, type info) for a symbol
58- documentSymbol: Get all symbols (functions, classes, variables) in a document
59- workspaceSymbol: Search for symbols across the entire workspace
60- goToImplementation: Find implementations of an interface or abstract method
61- prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)
62- incomingCalls: Find all functions/methods that call the function at a position
63- outgoingCalls: Find all functions/methods called by the function at a position
64
65All operations require:
66- filePath: The file to operate on
67- line: The line number (1-based, as shown in editors)
68- character: The character offset (1-based, as shown in editors)
69
70Note: LSP servers must be configured for the file type. If no server is available, an error will be returned."#
71 }
72
73 fn parameters_schema(&self) -> serde_json::Value {
74 serde_json::json!({
75 "type": "object",
76 "properties": {
77 "operation": {
78 "type": "string",
79 "enum": [
80 "goToDefinition",
81 "findReferences",
82 "hover",
83 "documentSymbol",
84 "workspaceSymbol",
85 "goToImplementation",
86 "prepareCallHierarchy",
87 "incomingCalls",
88 "outgoingCalls"
89 ],
90 "description": "The LSP operation to perform"
91 },
92 "filePath": {
93 "type": "string",
94 "description": "The absolute or relative path to the file"
95 },
96 "line": {
97 "type": "integer",
98 "minimum": 1,
99 "description": "The line number (1-based, as shown in editors)"
100 },
101 "character": {
102 "type": "integer",
103 "minimum": 1,
104 "description": "The character offset (1-based, as shown in editors)"
105 }
106 },
107 "required": ["operation", "filePath", "line", "character"]
108 })
109 }
110
111 async fn execute(&self, params: serde_json::Value) -> ToolOutput {
112 let params: LspParams = match serde_json::from_value(params) {
114 Ok(p) => p,
115 Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
116 };
117
118 let lsp_instance = match lsp() {
120 Some(l) => l,
121 None => {
122 return ToolOutput::error(
123 "LSP not initialized. The agent must initialize LSP with the working directory first.",
124 )
125 }
126 };
127
128 let operation: LspOperation = match params.operation.parse() {
130 Ok(op) => op,
131 Err(e) => return ToolOutput::error(e),
132 };
133
134 let file_path = Path::new(¶ms.file_path);
135 let line = params.line.saturating_sub(1);
137 let character = params.character.saturating_sub(1);
138
139 debug!(
140 operation = %operation,
141 file = %params.file_path,
142 line = params.line,
143 character = params.character,
144 "Executing LSP operation"
145 );
146
147 if !file_path.is_absolute() {
149 let abs_path = lsp_instance.working_dir().join(file_path);
150 if !abs_path.exists() {
151 return ToolOutput::error(format!("File not found: {}", abs_path.display()));
152 }
153 } else if !file_path.exists() {
154 return ToolOutput::error(format!("File not found: {}", file_path.display()));
155 }
156
157 if !lsp_instance.has_clients(file_path).await {
159 return ToolOutput::error("No LSP server available for this file type.");
160 }
161
162 if let Err(e) = lsp_instance.touch_file(file_path, true).await {
164 warn!(error = ?e, "Failed to touch file for LSP");
165 }
166
167 let result = match operation {
169 LspOperation::GoToDefinition => {
170 match lsp_instance.definition(file_path, line, character).await {
171 Ok(locations) => format_locations(&locations),
172 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
173 }
174 }
175 LspOperation::FindReferences => {
176 match lsp_instance.references(file_path, line, character).await {
177 Ok(locations) => format_locations(&locations),
178 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
179 }
180 }
181 LspOperation::Hover => {
182 match lsp_instance.hover(file_path, line, character).await {
183 Ok(hovers) => {
184 let hover = hovers.into_iter().flatten().next();
185 match hover {
186 Some(h) => format_hover(&h),
187 None => "No hover information available".to_string(),
188 }
189 }
190 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
191 }
192 }
193 LspOperation::DocumentSymbol => {
194 match lsp_instance.document_symbols(file_path).await {
195 Ok(responses) => format_document_symbols(&responses),
196 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
197 }
198 }
199 LspOperation::WorkspaceSymbol => {
200 match lsp_instance.workspace_symbols("").await {
202 Ok(symbols) => format_workspace_symbols(&symbols),
203 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
204 }
205 }
206 LspOperation::GoToImplementation => {
207 match lsp_instance
208 .implementation(file_path, line, character)
209 .await
210 {
211 Ok(locations) => format_locations(&locations),
212 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
213 }
214 }
215 LspOperation::PrepareCallHierarchy => {
216 match lsp_instance
217 .prepare_call_hierarchy(file_path, line, character)
218 .await
219 {
220 Ok(items) => {
221 if items.is_empty() {
222 "No call hierarchy item found at this position".to_string()
223 } else {
224 serde_json::to_string_pretty(&items).unwrap_or_else(|_| "[]".to_string())
225 }
226 }
227 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
228 }
229 }
230 LspOperation::IncomingCalls => {
231 match lsp_instance
232 .incoming_calls(file_path, line, character)
233 .await
234 {
235 Ok(calls) => {
236 if calls.is_empty() {
237 "No incoming calls found".to_string()
238 } else {
239 serde_json::to_string_pretty(&calls).unwrap_or_else(|_| "[]".to_string())
240 }
241 }
242 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
243 }
244 }
245 LspOperation::OutgoingCalls => {
246 match lsp_instance
247 .outgoing_calls(file_path, line, character)
248 .await
249 {
250 Ok(calls) => {
251 if calls.is_empty() {
252 "No outgoing calls found".to_string()
253 } else {
254 serde_json::to_string_pretty(&calls).unwrap_or_else(|_| "[]".to_string())
255 }
256 }
257 Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
258 }
259 }
260 };
261
262 ToolOutput::success(result)
263 }
264}
265
266fn format_locations(locations: &[Location]) -> String {
268 if locations.is_empty() {
269 return "No results found".to_string();
270 }
271
272 let mut output = Vec::new();
273 for loc in locations {
274 let path = uri_to_file_path(&loc.uri)
275 .map(|p| p.display().to_string())
276 .unwrap_or_else(|| loc.uri.as_str().to_string());
277 let line = loc.range.start.line + 1;
278 let col = loc.range.start.character + 1;
279 output.push(format!("{}:{}:{}", path, line, col));
280 }
281
282 output.join("\n")
283}
284
285fn format_hover(hover: &codive_lsp::Hover) -> String {
287 use codive_lsp::types::{HoverContents, MarkedString};
288
289 match &hover.contents {
290 HoverContents::Scalar(marked) => format_marked_string(marked),
291 HoverContents::Array(items) => items
292 .iter()
293 .map(format_marked_string)
294 .collect::<Vec<_>>()
295 .join("\n\n"),
296 HoverContents::Markup(content) => content.value.clone(),
297 }
298}
299
300fn format_marked_string(marked: &codive_lsp::types::MarkedString) -> String {
301 use codive_lsp::types::MarkedString;
302 match marked {
303 MarkedString::String(s) => s.clone(),
304 MarkedString::LanguageString(ls) => format!("```{}\n{}\n```", ls.language, ls.value),
305 }
306}
307
308fn format_document_symbols(responses: &[DocumentSymbolResponse]) -> String {
310 let mut output = Vec::new();
311
312 for response in responses {
313 match response {
314 DocumentSymbolResponse::Flat(symbols) => {
315 for sym in symbols {
316 let line = sym.location.range.start.line + 1;
317 output.push(format!(
318 "{:?} {} (line {})",
319 sym.kind, sym.name, line
320 ));
321 }
322 }
323 DocumentSymbolResponse::Nested(symbols) => {
324 format_nested_symbols(symbols, &mut output, 0);
325 }
326 }
327 }
328
329 if output.is_empty() {
330 "No symbols found".to_string()
331 } else {
332 output.join("\n")
333 }
334}
335
336fn format_nested_symbols(
337 symbols: &[codive_lsp::DocumentSymbol],
338 output: &mut Vec<String>,
339 indent: usize,
340) {
341 let prefix = " ".repeat(indent);
342 for sym in symbols {
343 let line = sym.range.start.line + 1;
344 output.push(format!(
345 "{}{:?} {} (line {})",
346 prefix, sym.kind, sym.name, line
347 ));
348 if let Some(children) = &sym.children {
349 format_nested_symbols(children, output, indent + 1);
350 }
351 }
352}
353
354fn format_workspace_symbols(symbols: &[SymbolInformation]) -> String {
356 if symbols.is_empty() {
357 return "No symbols found".to_string();
358 }
359
360 let mut output = Vec::new();
361 for sym in symbols {
362 let path = uri_to_file_path(&sym.location.uri)
363 .map(|p| p.display().to_string())
364 .unwrap_or_else(|| sym.location.uri.as_str().to_string());
365 let line = sym.location.range.start.line + 1;
366 output.push(format!("{:?} {} - {}:{}", sym.kind, sym.name, path, line));
367 }
368
369 output.join("\n")
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 #[test]
377 fn test_tool_name() {
378 let tool = LspTool::new();
379 assert_eq!(tool.name(), "lsp");
380 }
381
382 #[test]
383 fn test_tool_schema() {
384 let tool = LspTool::new();
385 let schema = tool.parameters_schema();
386 assert!(schema.get("properties").is_some());
387 assert!(schema.get("required").is_some());
388 }
389}