matrixcode_core/tools/
write.rs1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4
5use super::{Tool, ToolDefinition};
6use crate::approval::RiskLevel;
7use crate::path_validator::{validate_path, validate_content_size};
8
9pub struct WriteTool;
10
11#[async_trait]
12impl Tool for WriteTool {
13 fn definition(&self) -> ToolDefinition {
14 ToolDefinition {
15 name: "write".to_string(),
16 description: "向文件写入内容,若文件不存在则创建。
17
18【重要】写入现有文件前必须先读取:
19- 如果文件已存在,必须先用 read 工具读取当前内容
20- 如果没先读文件,此工具会失败
21- 了解现有内容可防止意外覆盖重要信息
22
23优先用 edit 工具修改现有文件(只发送 diff)
24只在以下情况使用此工具:
25- 创建新文件
26- 完整重写文件(用户明确要求)
27
28路径安全:自动验证路径安全性,阻止路径穿越和系统文件写入".to_string(),
29 parameters: json!({
30 "type": "object",
31 "properties": {
32 "path": {
33 "type": "string",
34 "description": "要写入的文件路径(会自动验证安全性,阻止路径穿越和系统文件写入)"
35 },
36 "content": {
37 "type": "string",
38 "description": "要写入的内容(单次写入最大10MB,超大内容请分批写入)"
39 }
40 },
41 "required": ["path", "content"]
42 }),
43 ..Default::default()
44 }
45 }
46
47 async fn execute(&self, params: Value) -> Result<String> {
48 let path_str = params["path"]
49 .as_str()
50 .ok_or_else(|| anyhow::anyhow!("missing 'path'"))?;
51 let content = params["content"]
52 .as_str()
53 .ok_or_else(|| anyhow::anyhow!("missing 'content'"))?;
54
55 validate_content_size(content)?;
57
58 let validated_path = validate_path(path_str, None, true)?;
61
62 if let Some(parent) = validated_path.parent() {
64 tokio::fs::create_dir_all(parent).await?;
65 }
66
67 let total_bytes = content.len();
69 let size_mb = total_bytes as f64 / 1_000_000.0;
70
71 tokio::fs::write(&validated_path, content).await?;
73
74 let size_feedback = if size_mb > 1.0 {
76 format!(
77 " ({:.2} MB - large file written successfully. \
78 Consider splitting if this causes performance issues)",
79 size_mb
80 )
81 } else if size_mb > 0.1 {
82 format!(" ({:.2} MB)", size_mb)
83 } else {
84 format!(" ({:.2} KB)", total_bytes as f64 / 1_000.0)
85 };
86
87 Ok(format!(
88 "Successfully wrote {} bytes{} to {}\nPath validated: {}",
89 total_bytes, size_feedback, path_str, validated_path.display()
90 ))
91 }
92
93 fn risk_level(&self) -> RiskLevel {
94 RiskLevel::Mutating
95 }
96}