refactor: use typed Deserialize structs for tool arguments
Convert read_file, write_file, edit_file, and glob from manual args["key"].as_str() parsing to serde_json::from_value with typed Args structs. Gives type safety, default values via serde attributes, and clearer error messages on missing/wrong-type arguments. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
29db4ff409
commit
74f05924ff
4 changed files with 77 additions and 57 deletions
|
|
@ -1,11 +1,18 @@
|
|||
// tools/write.rs — Write file contents
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::types::ToolDef;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Args {
|
||||
file_path: String,
|
||||
content: String,
|
||||
}
|
||||
|
||||
pub fn definition() -> ToolDef {
|
||||
ToolDef::new(
|
||||
"write_file",
|
||||
|
|
@ -29,19 +36,16 @@ pub fn definition() -> ToolDef {
|
|||
}
|
||||
|
||||
pub fn write_file(args: &serde_json::Value) -> Result<String> {
|
||||
let path = args["file_path"]
|
||||
.as_str()
|
||||
.context("file_path is required")?;
|
||||
let content = args["content"].as_str().context("content is required")?;
|
||||
let args: Args = serde_json::from_value(args.clone())
|
||||
.context("invalid write_file arguments")?;
|
||||
|
||||
// Create parent directories if needed
|
||||
if let Some(parent) = Path::new(path).parent() {
|
||||
if let Some(parent) = Path::new(&args.file_path).parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("Failed to create directories for {}", path))?;
|
||||
.with_context(|| format!("Failed to create directories for {}", args.file_path))?;
|
||||
}
|
||||
|
||||
std::fs::write(path, content).with_context(|| format!("Failed to write {}", path))?;
|
||||
std::fs::write(&args.file_path, &args.content)
|
||||
.with_context(|| format!("Failed to write {}", args.file_path))?;
|
||||
|
||||
let line_count = content.lines().count();
|
||||
Ok(format!("Wrote {} lines to {}", line_count, path))
|
||||
Ok(format!("Wrote {} lines to {}", args.content.lines().count(), args.file_path))
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue