use codive_core::tool::{Tool, ToolOutput};
use async_trait::async_trait;
use serde::Deserialize;
use std::path::Path;
use tokio::fs;
use tracing::debug;
const MAX_FILE_SIZE: u64 = 10 * 1024 * 1024;
const DEFAULT_MAX_LINES: usize = 2000;
pub struct ReadFileTool {
max_file_size: u64,
max_lines: usize,
}
impl ReadFileTool {
pub fn new() -> Self {
Self {
max_file_size: MAX_FILE_SIZE,
max_lines: DEFAULT_MAX_LINES,
}
}
pub fn with_max_file_size(mut self, size: u64) -> Self {
self.max_file_size = size;
self
}
pub fn with_max_lines(mut self, lines: usize) -> Self {
self.max_lines = lines;
self
}
}
impl Default for ReadFileTool {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Deserialize)]
struct ReadFileParams {
path: String,
#[serde(default)]
offset: Option<usize>,
#[serde(default)]
limit: Option<usize>,
}
#[async_trait]
impl Tool for ReadFileTool {
fn name(&self) -> &str {
"read_file"
}
fn description(&self) -> &str {
"Read the contents of a file. Returns the file content with line numbers. \
For large files, use offset and limit to read specific sections."
}
fn parameters_schema(&self) -> serde_json::Value {
serde_json::json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "The path to the file to read"
},
"offset": {
"type": "integer",
"description": "Line number to start from (1-indexed). Default: 1"
},
"limit": {
"type": "integer",
"description": "Maximum number of lines to read. Default: 2000"
}
},
"required": ["path"]
})
}
async fn execute(&self, params: serde_json::Value) -> ToolOutput {
let params: ReadFileParams = match serde_json::from_value(params) {
Ok(p) => p,
Err(e) => return ToolOutput::error(format!("Invalid parameters: {}", e)),
};
let path = Path::new(¶ms.path);
debug!(path = %path.display(), "Reading file");
if !path.exists() {
return ToolOutput::error(format!("File not found: {}", path.display()));
}
if !path.is_file() {
return ToolOutput::error(format!("Not a file: {}", path.display()));
}
let metadata = match fs::metadata(path).await {
Ok(m) => m,
Err(e) => return ToolOutput::error(format!("Failed to read file metadata: {}", e)),
};
if metadata.len() > self.max_file_size {
return ToolOutput::error(format!(
"File too large: {} bytes (max: {} bytes). Use offset/limit to read sections.",
metadata.len(),
self.max_file_size
));
}
let content = match fs::read_to_string(path).await {
Ok(c) => c,
Err(e) => {
if e.kind() == std::io::ErrorKind::InvalidData {
return ToolOutput::error(
"File appears to be binary and cannot be read as text",
);
}
return ToolOutput::error(format!("Failed to read file: {}", e));
}
};
let lines: Vec<&str> = content.lines().collect();
let total_lines = lines.len();
let offset = params.offset.unwrap_or(1).saturating_sub(1); let limit = params.limit.unwrap_or(self.max_lines);
let start = offset.min(lines.len());
let end = (start + limit).min(lines.len());
let selected_lines = &lines[start..end];
let mut output = String::new();
if start > 0 || end < total_lines {
output.push_str(&format!(
"Showing lines {}-{} of {} total\n\n",
start + 1,
end,
total_lines
));
}
for (i, line) in selected_lines.iter().enumerate() {
let line_num = start + i + 1;
output.push_str(&format!("{:>6}│{}\n", line_num, line));
}
if end < total_lines {
output.push_str(&format!(
"\n... {} more lines. Use offset={} to continue.",
total_lines - end,
end + 1
));
}
ToolOutput::success(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use tempfile::NamedTempFile;
#[test]
fn test_read_file_tool_name() {
let tool = ReadFileTool::new();
assert_eq!(tool.name(), "read_file");
}
#[test]
fn test_read_file_schema() {
let tool = ReadFileTool::new();
let schema = tool.parameters_schema();
assert_eq!(schema["type"], "object");
assert!(schema["properties"]["path"].is_object());
assert_eq!(schema["required"][0], "path");
}
#[tokio::test]
async fn test_read_simple_file() {
let mut file = NamedTempFile::new().unwrap();
writeln!(file, "line 1").unwrap();
writeln!(file, "line 2").unwrap();
writeln!(file, "line 3").unwrap();
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file.path().to_str().unwrap()
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("line 1"));
assert!(output.content.contains("line 2"));
assert!(output.content.contains("line 3"));
}
#[tokio::test]
async fn test_read_with_line_numbers() {
let mut file = NamedTempFile::new().unwrap();
writeln!(file, "first").unwrap();
writeln!(file, "second").unwrap();
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file.path().to_str().unwrap()
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("1│"));
assert!(output.content.contains("2│"));
}
#[tokio::test]
async fn test_read_with_offset() {
let mut file = NamedTempFile::new().unwrap();
for i in 1..=10 {
writeln!(file, "line {}", i).unwrap();
}
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file.path().to_str().unwrap(),
"offset": 5
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("line 5"));
assert!(!output.content.contains("│line 4"));
}
#[tokio::test]
async fn test_read_with_limit() {
let mut file = NamedTempFile::new().unwrap();
for i in 1..=10 {
writeln!(file, "line {}", i).unwrap();
}
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file.path().to_str().unwrap(),
"limit": 3
}))
.await;
assert!(output.is_success());
assert!(output.content.contains("line 1"));
assert!(output.content.contains("line 2"));
assert!(output.content.contains("line 3"));
assert!(!output.content.contains("│line 4"));
assert!(output.content.contains("more lines"));
}
#[tokio::test]
async fn test_read_nonexistent_file() {
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": "/nonexistent/file/path/12345.txt"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("not found"));
}
#[tokio::test]
async fn test_read_directory() {
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": "/tmp"
}))
.await;
assert!(output.is_error);
assert!(output.content.contains("Not a file"));
}
#[tokio::test]
async fn test_read_invalid_params() {
let tool = ReadFileTool::new();
let output = tool.execute(serde_json::json!({})).await;
assert!(output.is_error);
assert!(output.content.contains("Invalid parameters"));
}
#[tokio::test]
async fn test_read_empty_file() {
let file = NamedTempFile::new().unwrap();
let tool = ReadFileTool::new();
let output = tool
.execute(serde_json::json!({
"path": file.path().to_str().unwrap()
}))
.await;
assert!(output.is_success());
}
}