use rig::tool::{Tool, ToolContext};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
env,
fs::{self, read_to_string},
io::{Error, ErrorKind},
path::{Path, PathBuf},
};
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
enum DirectoryEntryKind {
File,
Directory,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct DirectoryEntry {
path: String,
kind: DirectoryEntryKind,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DirectoryListing {
entries: Vec<DirectoryEntry>,
total_entries: usize,
truncated: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Location {
path: PathBuf,
line: usize,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Range {
path: PathBuf,
start: usize,
end: usize,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct SearchMatch {
location: Location,
preview: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct SearchResults {
total_entries: usize,
returned_entries: usize,
truncated: bool,
entries: Vec<SearchMatch>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct FileContent {
range: Range,
content: String,
}
#[derive(Deserialize, Serialize)]
pub struct ListDirArgs {
path: PathBuf,
start: Option<usize>,
}
#[derive(Deserialize, Serialize)]
pub struct ListDir {
base_dir: PathBuf,
max_results: usize,
}
impl ListDir {
pub fn new(base_dir: &Path, max_results: usize) -> Self {
Self {
base_dir: base_dir.to_path_buf(),
max_results,
}
}
}
impl Tool for ListDir {
const NAME: &'static str = "list_dir";
type Error = std::io::Error;
type Args = ListDirArgs;
type Output = DirectoryListing;
async fn call(
&self,
_context: &mut ToolContext,
args: Self::Args,
) -> Result<Self::Output, Self::Error> {
let path = allowed_canonical_path(&args.path, &self.base_dir)?;
list_dir(&path, false)
}
fn description(&self) -> String {
format!(
"List the files and directories in the given directory (relative to project root), \
returning at most {} entries. Use an empty string \"\" for the project root. \
Results include both files and subdirectories with their types.",
self.max_results
)
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the directory relative to project root directory. \
Use an empty string for the root directory."
},
"start": {
"type": "integer",
"description": "Optional, zero-based index of the first result to return. \
Use this to paginate through results if a previous call was truncated."
},
},
"required": ["path"]
})
}
}
#[derive(Deserialize, Serialize)]
pub struct ReadFileArgs {
path: PathBuf,
start: Option<usize>,
end: Option<usize>,
}
#[derive(Deserialize, Serialize)]
pub struct ReadFile {
base_dir: PathBuf,
}
impl ReadFile {
pub fn new(base_dir: &Path) -> Self {
Self {
base_dir: base_dir.to_path_buf(),
}
}
}
impl Tool for ReadFile {
const NAME: &'static str = "read_file";
type Error = std::io::Error;
type Args = ReadFileArgs;
type Output = FileContent;
async fn call(
&self,
_context: &mut ToolContext,
args: Self::Args,
) -> Result<Self::Output, Self::Error> {
let path = allowed_canonical_path(&args.path, &self.base_dir)?;
let content: Vec<String> = fs::read_to_string(path)?
.lines()
.map(|line| line.to_string())
.collect();
let mut start = match args.start {
Some(v) => v.saturating_sub(1),
None => 0,
};
let mut end = match args.end {
Some(v) => {
if v > 0 {
v } else {
1 }
}
None => content.len(),
};
if end > content.len() {
end = content.len();
}
if start > end {
start = end;
};
let extract = &content[start..end].join("\n");
Ok(FileContent {
range: Range {
path: args.path,
start: start + 1,
end: end + 1,
},
content: extract.to_owned(),
})
}
fn description(&self) -> String {
"Read the content of a file, optionally specifying a line range. \
Lines are 1-indexed and inclusive. \
If no range is specified, the entire file is returned."
.to_string()
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the file relative to project root directory"
},
"start": {
"type": "integer",
"description": "First line number to read (1-indexed, inclusive). \
If not provided, reads from the beginning of the file."
},
"end": {
"type": "integer",
"description": "Last line number to read (1-indexed, inclusive). \
If not provided, reads to the end of the file. \
If end exceeds the file length, reads until the end."
}
},
"required": ["path"]
})
}
fn map_error(&self, error: Self::Error) -> rig::tool::ToolExecutionError {
rig::tool::ToolExecutionError::from_error(error)
}
}
#[derive(Deserialize, Serialize)]
pub struct SearchTextArgs {
path: PathBuf,
text: String,
start: Option<usize>,
}
#[derive(Deserialize, Serialize)]
pub struct SearchText {
base_dir: PathBuf,
max_results: usize,
}
impl SearchText {
pub fn new(base_dir: &Path, max_results: usize) -> Self {
Self {
base_dir: base_dir.to_path_buf(),
max_results,
}
}
}
impl Tool for SearchText {
const NAME: &'static str = "search_text";
type Error = std::io::Error;
type Args = SearchTextArgs;
type Output = SearchResults;
async fn call(
&self,
_context: &mut ToolContext,
args: Self::Args,
) -> Result<Self::Output, Self::Error> {
let path = allowed_canonical_path(&args.path, &self.base_dir)?;
let entries = list_dir(&path, true)?;
let matches: Vec<SearchMatch> = entries
.entries
.iter()
.filter_map(|e| match e.kind {
DirectoryEntryKind::File => {
read_to_string(&e.path).ok().map(|v| (e.path.clone(), v))
}
DirectoryEntryKind::Directory => None,
})
.map(|(path, content)| {
(
path,
content
.lines()
.enumerate()
.filter(|(_nr, line)| line.contains(&args.text))
.map(|(nr, line)| (nr, line.to_owned()))
.collect::<Vec<(usize, String)>>(),
)
})
.filter(|(_path, content)| !content.is_empty())
.flat_map(|(path, content)| {
content
.iter()
.map(move |(nr, line)| SearchMatch {
location: Location {
path: PathBuf::from(path.clone()),
line: *nr,
},
preview: line.clone(),
})
.collect::<Vec<_>>()
})
.collect();
let start = args.start.unwrap_or_default();
let requested_matches = &matches[start..];
let final_matches = if requested_matches.len() > 100 {
&requested_matches[..100]
} else {
requested_matches
};
Ok(SearchResults {
total_entries: matches.len(),
returned_entries: final_matches.len(),
truncated: final_matches.len() != matches.len(),
entries: final_matches.to_vec(),
})
}
fn description(&self) -> String {
format!(
"Search for text in all files within the given directory and its subdirectories. \
Returns matches with file paths, line numbers, and content previews. \
The search is case-sensitive. Results are clipped at {} entries.",
self.max_results
)
}
fn parameters(&self) -> serde_json::Value {
json!({
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Path to the directory to search in, \
relative to project root directory. \
Use an empty string for the root directory. \
Search is recursive."
},
"text": {
"type": "string",
"description": "The exact text string to search for. \
The search is case-sensitive."
},
"start": {
"type": "integer",
"description": "Optional, zero-based index of the first result to return. \
Use this to paginate through results if a previous call was truncated."
},
},
"required": ["path", "text"]
})
}
}
fn list_dir(path: &Path, recursive: bool) -> Result<DirectoryListing, std::io::Error> {
let mut result = DirectoryListing {
entries: Vec::new(),
total_entries: 0,
truncated: false,
};
let mut backlog = vec![path.to_path_buf()];
while let Some(dir) = backlog.pop() {
let paths = fs::read_dir(dir)?;
for entry in paths.flatten() {
if entry.path().is_dir() {
if recursive {
backlog.push(entry.path());
}
result.entries.push(DirectoryEntry {
path: entry.path().to_string_lossy().to_string(),
kind: DirectoryEntryKind::Directory,
});
} else {
result.entries.push(DirectoryEntry {
path: entry.path().to_string_lossy().to_string(),
kind: DirectoryEntryKind::File,
});
}
}
}
result.total_entries = result.entries.len();
Ok(result)
}
fn allowed_canonical_path(path_string: &Path, base_dir: &Path) -> Result<PathBuf, std::io::Error> {
let canonical_base = base_dir.canonicalize()?;
let path = base_dir.join(path_string).canonicalize()?;
if path.starts_with(canonical_base) {
Ok(path)
} else {
Err(Error::new(
ErrorKind::PermissionDenied,
"Path must be subpath of project root",
))
}
}
#[tokio::test]
async fn test_list_dir() {
let base_dir = env::current_dir().expect("Cannot get current directory");
let ld = ListDir::new(&base_dir, 100);
let result = ld
.call(
&mut ToolContext::default(),
ListDirArgs {
path: PathBuf::from(""),
start: None,
},
)
.await
.unwrap();
println!("Result: {:?}", result.total_entries);
}
#[tokio::test]
async fn test_read_file() {
let base_dir = env::current_dir().expect("Cannot get current directory");
let ld = ReadFile::new(&base_dir);
let result = ld
.call(
&mut ToolContext::default(),
ReadFileArgs {
path: PathBuf::from("src/main.rs"),
start: Some(1),
end: Some(14),
},
)
.await
.unwrap();
println!("Result: {:?}", result);
}
#[tokio::test]
async fn test_search_text() {
let base_dir = env::current_dir().expect("Cannot get current directory");
let ld = SearchText::new(&base_dir, 100);
let result = ld
.call(
&mut ToolContext::default(),
SearchTextArgs {
path: PathBuf::from("src"),
text: "unwrap()".to_string(),
start: None,
},
)
.await
.unwrap();
println!("Result: {:?}", result);
}