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 struct WriteFileTool {
working_dir: PathBuf,
}
impl WriteFileTool {
pub fn new(working_dir: impl Into<PathBuf>) -> Self {
Self {
working_dir: working_dir.into(),
}
}
fn write_inner(&self, path: &std::path::Path, content: &str) -> Result<(), FsError> {
let scoped = scoped_path(&self.working_dir, path)?;
if let Some(parent) = scoped.parent() {
std::fs::create_dir_all(parent).map_err(|e| FsError::io(parent, e))?;
}
std::fs::write(&scoped, content).map_err(|e| FsError::io(&scoped, e))?;
Ok(())
}
}
#[async_trait]
impl ToolExecutor for WriteFileTool {
fn name(&self) -> &str {
"write_file"
}
fn schema(&self) -> Value {
json!({
"type": "function",
"function": {
"name": "write_file",
"description": "Create or overwrite a file with the provided content. Parent directories are created automatically. The path must be inside the working directory.",
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Relative or absolute path to the file (must be inside the working directory)."
},
"content": {
"type": "string",
"description": "Text content to write to the file."
}
},
"required": ["path", "content"],
"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("write_file: missing required argument 'path'");
};
let Some(content) = args.get("content").and_then(Value::as_str) else {
return ToolResult::err("write_file: missing required argument 'content'");
};
match self.write_inner(std::path::Path::new(path_str), content) {
Ok(()) => ToolResult::ok(format!("wrote {path_str}")),
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) -> WriteFileTool {
WriteFileTool::new(tmp.path())
}
#[tokio::test]
async fn write_creates_new_file() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "new.py", "content": "# hello"}))
.await;
assert!(!result.is_error(), "unexpected error: {}", result.content());
let content = fs::read_to_string(tmp.path().join("new.py")).expect("read back");
assert_eq!(content, "# hello");
}
#[tokio::test]
async fn write_creates_parent_dirs() {
let tmp = tempfile::tempdir().expect("tempdir");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "a/b/c.txt", "content": "deep"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let content = fs::read_to_string(tmp.path().join("a/b/c.txt")).expect("read back");
assert_eq!(content, "deep");
}
#[tokio::test]
async fn write_overwrites_existing_file() {
let tmp = tempfile::tempdir().expect("tempdir");
fs::write(tmp.path().join("f.txt"), "v1").expect("seed");
let tool = make_tool(&tmp);
let result = tool
.execute(json!({"path": "f.txt", "content": "v2"}))
.await;
assert!(!result.is_error(), "{}", result.content());
let content = fs::read_to_string(tmp.path().join("f.txt")).expect("read back");
assert_eq!(content, "v2");
}
#[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": "../../evil.sh", "content": "harm"}))
.await;
assert!(result.is_error());
assert!(
result.content().contains("escapes"),
"unexpected message: {}",
result.content()
);
}
#[test]
fn schema_has_required_fields() {
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");
let names: Vec<&str> = required.iter().filter_map(Value::as_str).collect();
assert!(names.contains(&"path"), "must require 'path'");
assert!(names.contains(&"content"), "must require 'content'");
}
}