codive-tools 0.1.0

Tool implementations for Codive
Documentation
//! LSP tool for code intelligence operations
//!
//! This tool provides access to Language Server Protocol operations,
//! enabling the AI agent to perform code navigation and analysis.

use codive_core::tool::{Tool, ToolOutput};
use codive_lsp::{
    lsp, uri_to_file_path, DocumentSymbolResponse, Location, LspOperation, SymbolInformation,
};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tracing::{debug, warn};

/// Tool for LSP operations
pub struct LspTool;

impl LspTool {
    /// Create a new LspTool
    pub fn new() -> Self {
        Self
    }
}

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

/// Parameters for the LSP tool
#[derive(Debug, Deserialize)]
struct LspParams {
    /// The LSP operation to perform
    operation: String,
    /// Path to the file (required for most operations)
    #[serde(rename = "filePath")]
    file_path: String,
    /// Line number (1-based)
    line: u32,
    /// Character position (1-based)
    character: u32,
}

#[async_trait]
impl Tool for LspTool {
    fn name(&self) -> &str {
        "lsp"
    }

    fn description(&self) -> &str {
        r#"Interact with Language Server Protocol (LSP) servers to get code intelligence features.

Supported operations:
- goToDefinition: Find where a symbol is defined
- findReferences: Find all references to a symbol
- hover: Get hover information (documentation, type info) for a symbol
- documentSymbol: Get all symbols (functions, classes, variables) in a document
- workspaceSymbol: Search for symbols across the entire workspace
- goToImplementation: Find implementations of an interface or abstract method
- prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)
- incomingCalls: Find all functions/methods that call the function at a position
- outgoingCalls: Find all functions/methods called by the function at a position

All operations require:
- filePath: The file to operate on
- line: The line number (1-based, as shown in editors)
- character: The character offset (1-based, as shown in editors)

Note: LSP servers must be configured for the file type. If no server is available, an error will be returned."#
    }

    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "operation": {
                    "type": "string",
                    "enum": [
                        "goToDefinition",
                        "findReferences",
                        "hover",
                        "documentSymbol",
                        "workspaceSymbol",
                        "goToImplementation",
                        "prepareCallHierarchy",
                        "incomingCalls",
                        "outgoingCalls"
                    ],
                    "description": "The LSP operation to perform"
                },
                "filePath": {
                    "type": "string",
                    "description": "The absolute or relative path to the file"
                },
                "line": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "The line number (1-based, as shown in editors)"
                },
                "character": {
                    "type": "integer",
                    "minimum": 1,
                    "description": "The character offset (1-based, as shown in editors)"
                }
            },
            "required": ["operation", "filePath", "line", "character"]
        })
    }

    async fn execute(&self, params: serde_json::Value) -> ToolOutput {
        // Parse parameters
        let params: LspParams = match serde_json::from_value(params) {
            Ok(p) => p,
            Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
        };

        // Get LSP instance
        let lsp_instance = match lsp() {
            Some(l) => l,
            None => {
                return ToolOutput::error(
                    "LSP not initialized. The agent must initialize LSP with the working directory first.",
                )
            }
        };

        // Parse operation
        let operation: LspOperation = match params.operation.parse() {
            Ok(op) => op,
            Err(e) => return ToolOutput::error(e),
        };

        let file_path = Path::new(&params.file_path);
        // Convert to 0-based for LSP
        let line = params.line.saturating_sub(1);
        let character = params.character.saturating_sub(1);

        debug!(
            operation = %operation,
            file = %params.file_path,
            line = params.line,
            character = params.character,
            "Executing LSP operation"
        );

        // Check if file exists
        if !file_path.is_absolute() {
            let abs_path = lsp_instance.working_dir().join(file_path);
            if !abs_path.exists() {
                return ToolOutput::error(format!("File not found: {}", abs_path.display()));
            }
        } else if !file_path.exists() {
            return ToolOutput::error(format!("File not found: {}", file_path.display()));
        }

        // Check if LSP is available for this file
        if !lsp_instance.has_clients(file_path).await {
            return ToolOutput::error("No LSP server available for this file type.");
        }

        // Touch the file first
        if let Err(e) = lsp_instance.touch_file(file_path, true).await {
            warn!(error = ?e, "Failed to touch file for LSP");
        }

        // Execute the operation
        let result = match operation {
            LspOperation::GoToDefinition => {
                match lsp_instance.definition(file_path, line, character).await {
                    Ok(locations) => format_locations(&locations),
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::FindReferences => {
                match lsp_instance.references(file_path, line, character).await {
                    Ok(locations) => format_locations(&locations),
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::Hover => {
                match lsp_instance.hover(file_path, line, character).await {
                    Ok(hovers) => {
                        let hover = hovers.into_iter().flatten().next();
                        match hover {
                            Some(h) => format_hover(&h),
                            None => "No hover information available".to_string(),
                        }
                    }
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::DocumentSymbol => {
                match lsp_instance.document_symbols(file_path).await {
                    Ok(responses) => format_document_symbols(&responses),
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::WorkspaceSymbol => {
                // Use empty query to get all symbols
                match lsp_instance.workspace_symbols("").await {
                    Ok(symbols) => format_workspace_symbols(&symbols),
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::GoToImplementation => {
                match lsp_instance
                    .implementation(file_path, line, character)
                    .await
                {
                    Ok(locations) => format_locations(&locations),
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::PrepareCallHierarchy => {
                match lsp_instance
                    .prepare_call_hierarchy(file_path, line, character)
                    .await
                {
                    Ok(items) => {
                        if items.is_empty() {
                            "No call hierarchy item found at this position".to_string()
                        } else {
                            serde_json::to_string_pretty(&items).unwrap_or_else(|_| "[]".to_string())
                        }
                    }
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::IncomingCalls => {
                match lsp_instance
                    .incoming_calls(file_path, line, character)
                    .await
                {
                    Ok(calls) => {
                        if calls.is_empty() {
                            "No incoming calls found".to_string()
                        } else {
                            serde_json::to_string_pretty(&calls).unwrap_or_else(|_| "[]".to_string())
                        }
                    }
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
            LspOperation::OutgoingCalls => {
                match lsp_instance
                    .outgoing_calls(file_path, line, character)
                    .await
                {
                    Ok(calls) => {
                        if calls.is_empty() {
                            "No outgoing calls found".to_string()
                        } else {
                            serde_json::to_string_pretty(&calls).unwrap_or_else(|_| "[]".to_string())
                        }
                    }
                    Err(e) => return ToolOutput::error(format!("Failed: {}", e)),
                }
            }
        };

        ToolOutput::success(result)
    }
}

/// Format locations for output
fn format_locations(locations: &[Location]) -> String {
    if locations.is_empty() {
        return "No results found".to_string();
    }

    let mut output = Vec::new();
    for loc in locations {
        let path = uri_to_file_path(&loc.uri)
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| loc.uri.as_str().to_string());
        let line = loc.range.start.line + 1;
        let col = loc.range.start.character + 1;
        output.push(format!("{}:{}:{}", path, line, col));
    }

    output.join("\n")
}

/// Format hover information
fn format_hover(hover: &codive_lsp::Hover) -> String {
    use codive_lsp::types::{HoverContents, MarkedString};

    match &hover.contents {
        HoverContents::Scalar(marked) => format_marked_string(marked),
        HoverContents::Array(items) => items
            .iter()
            .map(format_marked_string)
            .collect::<Vec<_>>()
            .join("\n\n"),
        HoverContents::Markup(content) => content.value.clone(),
    }
}

fn format_marked_string(marked: &codive_lsp::types::MarkedString) -> String {
    use codive_lsp::types::MarkedString;
    match marked {
        MarkedString::String(s) => s.clone(),
        MarkedString::LanguageString(ls) => format!("```{}\n{}\n```", ls.language, ls.value),
    }
}

/// Format document symbols
fn format_document_symbols(responses: &[DocumentSymbolResponse]) -> String {
    let mut output = Vec::new();

    for response in responses {
        match response {
            DocumentSymbolResponse::Flat(symbols) => {
                for sym in symbols {
                    let line = sym.location.range.start.line + 1;
                    output.push(format!(
                        "{:?} {} (line {})",
                        sym.kind, sym.name, line
                    ));
                }
            }
            DocumentSymbolResponse::Nested(symbols) => {
                format_nested_symbols(symbols, &mut output, 0);
            }
        }
    }

    if output.is_empty() {
        "No symbols found".to_string()
    } else {
        output.join("\n")
    }
}

fn format_nested_symbols(
    symbols: &[codive_lsp::DocumentSymbol],
    output: &mut Vec<String>,
    indent: usize,
) {
    let prefix = "  ".repeat(indent);
    for sym in symbols {
        let line = sym.range.start.line + 1;
        output.push(format!(
            "{}{:?} {} (line {})",
            prefix, sym.kind, sym.name, line
        ));
        if let Some(children) = &sym.children {
            format_nested_symbols(children, output, indent + 1);
        }
    }
}

/// Format workspace symbols
fn format_workspace_symbols(symbols: &[SymbolInformation]) -> String {
    if symbols.is_empty() {
        return "No symbols found".to_string();
    }

    let mut output = Vec::new();
    for sym in symbols {
        let path = uri_to_file_path(&sym.location.uri)
            .map(|p| p.display().to_string())
            .unwrap_or_else(|| sym.location.uri.as_str().to_string());
        let line = sym.location.range.start.line + 1;
        output.push(format!("{:?} {} - {}:{}", sym.kind, sym.name, path, line));
    }

    output.join("\n")
}

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

    #[test]
    fn test_tool_name() {
        let tool = LspTool::new();
        assert_eq!(tool.name(), "lsp");
    }

    #[test]
    fn test_tool_schema() {
        let tool = LspTool::new();
        let schema = tool.parameters_schema();
        assert!(schema.get("properties").is_some());
        assert!(schema.get("required").is_some());
    }
}