class FileEditTool implements Tool {
name = 'strReplace';
description = 'Replace text in a file';
inputSchema = z.object({
path: z.string(),
oldStr: z.string(),
newStr: z.string(),
});
async execute(input, context) {
try {
// 1. 权限检查
const allowed = await context.checkPermission('file:write');
if (!allowed) {
return { success: false, error: 'Permission denied' };
}
// 2. 读取文件
const content = await fs.readFile(input.path, 'utf-8');
// 3. 查找并替换
const occurrences = countOccurrences(content, input.oldStr);
if (occurrences === 0) {
return { success: false, error: 'String not found' };
}
if (occurrences > 1) {
return { success: false, error: 'Multiple matches found' };
}
const newContent = content.replace(input.oldStr, input.newStr);
// 4. 写入文件
await fs.writeFile(input.path, newContent);
// 5. 通知 LSP
await notifyLSP(input.path);
return {
success: true,
output: `Successfully replaced text in ${input.path}`,
};
} catch (error) {
return {
success: false,
error: error.message,
};
}
}
}