use std::path::PathBuf;
use async_trait::async_trait;
use serde_json::{Value, json};
use crate::tools::fs::{FsError, scoped_path};
use crate::tools::traits::{ToolExecutor, ToolResult};
pub const MAX_FILE_BYTES: u64 = 1024 * 1024;
pub struct ReadFileTool {
working_dir: PathBuf,
}
impl ReadFileTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn read_inner(
&self,
path: &std::path::Path,
start_line: Option<usize>,
end_line: Option<usize>,
) -> Result<String, FsError> {
let scoped = scoped_path(&self.working_dir, path)?;
let meta = std::fs::metadata(&scoped).map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
FsError::NotFound(scoped.clone())
} else {
FsError::io(&scoped, e)
}
})?;
if meta.len() > MAX_FILE_BYTES {
return Err(FsError::FileTooLarge {
path: scoped,
bytes: meta.len(),
max: MAX_FILE_BYTES,
});
}
let content = std::fs::read_to_string(&scoped).map_err(|e| FsError::io(&scoped, e))?;
match (start_line, end_line) {
(None, None) => Ok(content),
(start, end) => {
let start_idx = start.unwrap_or(1).saturating_sub(1); let lines: Vec<&str> = content.lines().collect();
let end_idx = end.map(|e| e.min(lines.len())).unwrap_or(lines.len());
let slice = lines[start_idx.min(lines.len())..end_idx].join("\n");
Ok(slice)
}
}
}
}
#[async_trait]
impl ToolExecutor for ReadFileTool {
fn name(&self) -> &str {
"read_file"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "read_file",
"description": "Read the contents of a file. Limited to 1 MiB. Optional start_line/end_line (1-based, inclusive) restrict the returned text.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative or absolute path to the file (must be inside the working directory)."
},
"start_line": {
"type": "integer",
"description": "First line to return (1-based, inclusive). Defaults to 1."
},
"end_line": {
"type": "integer",
"description": "Last line to return (1-based, inclusive). Defaults to end-of-file."
}
},
"required": ["path"],
"additionalProperties": false
}
}
})
}
async fn execute(&self, args: Value) -> ToolResult {
let Some(path_str) = args.get("path").and_then(Value::as_str) else {
return ToolResult::err("read_file: missing required argument 'path'");
};
let start_line = args
.get("start_line")
.and_then(Value::as_u64)
.map(|n| n as usize);
let end_line = args
.get("end_line")
.and_then(Value::as_u64)
.map(|n| n as usize);
match self.read_inner(std::path::Path::new(path_str), start_line, end_line) {
Ok(content) => ToolResult::ok(content),
Err(e) => ToolResult::err(e.to_string()),
}
}
}
#[cfg(test)]
mod tests {
use std::fs;
use serde_json::json;
use super::*;
use crate::tools::traits::ToolExecutor;
fn make_tool(tmp: &tempfile::TempDir) -> ReadFileTool {
ReadFileTool::new(tmp.path())
}
#[tokio::test]
async fn read_round_trips_file() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("hello.txt"), "line one\nline two\n").expect("write");
let tool = make_tool(&tmp);
let result = tool.execute(json!({"path": "hello.txt"})).await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
assert!(result.content().contains("line one"));
assert!(result.content().contains("line two"));
}
#[tokio::test]
async fn read_honors_line_range() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("multi.txt"), "a\nb\nc\n").expect("write");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "multi.txt", "start_line": 2, "end_line": 2}))
.await;
assert!(!result.is_error());
assert_eq!(result.content(), "b");
}
#[tokio::test]
async fn read_returns_error_on_oversized_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let big = vec![b'x'; (MAX_FILE_BYTES + 1) as usize];
fs::write(tmp.path().join("big.bin"), &big).expect("write");
let tool = make_tool(&tmp);
let result = tool.execute(json!({"path": "big.bin"})).await;
assert!(result.is_error());
assert!(
result.content().contains("too large"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn read_returns_error_on_missing_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool.execute(json!({"path": "does_not_exist.txt"})).await;
assert!(result.is_error());
assert!(
result.content().contains("not found"),
"unexpected message: {}",
result.content()
);
}
#[tokio::test]
async fn path_traversal_is_rejected() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool.execute(json!({"path": "../../etc/passwd"})).await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[test]
fn schema_has_required_path() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let schema = tool.schema();
let required = schema["function"]["parameters"]["required"]
.as_array()
.expect("required array");
assert!(
required.iter().any(|v| v.as_str() == Some("path")),
"schema must list 'path' as required"
);
}
}