Skip to content

Commit a9294be

Browse files
author
Yoshihiro Takahara
committed
fix(server): improve error handling in EditTextFileContentsHandler
- Add validation for required 'contents' field in patches - Return original file hash in error responses - Add missing 'content' field in error responses - Improve code readability
1 parent 5cfb0fc commit a9294be

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/mcp_text_editor/server.py

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -214,25 +214,32 @@ async def run_tool(self, arguments: Dict[str, Any]) -> Sequence[TextContent]:
214214
continue
215215

216216
encoding = arguments.get("encoding", "utf-8")
217-
result = await self.editor.edit_file_contents(
218-
file_path, file_hash, patches, encoding=encoding
219-
)
220-
results[file_path] = result
217+
# Validate patch fields first
218+
for patch in patches:
219+
if "contents" not in patch:
220+
results[file_path] = {
221+
"result": "error",
222+
"reason": "Missing required field 'contents' in patch",
223+
"file_hash": file_hash,
224+
"content": None,
225+
}
226+
break
227+
else: # No break occurred
228+
result = await self.editor.edit_file_contents(
229+
file_path, file_hash, patches, encoding=encoding
230+
)
231+
results[file_path] = result
221232
except Exception as e:
222-
current_hash = None
223-
if "path" in file_operation:
224-
file_path = file_operation["path"]
225-
try:
226-
_, _, _, current_hash, _, _ = (
227-
await self.editor.read_file_contents(file_path)
228-
)
229-
except Exception:
230-
current_hash = None
231-
232-
results[file_path if "path" in file_operation else "unknown"] = {
233+
error_file_path = (
234+
file_path if "path" in file_operation else "unknown"
235+
)
236+
results[error_file_path] = {
233237
"result": "error",
234238
"reason": str(e),
235-
"file_hash": current_hash,
239+
"file_hash": file_operation.get(
240+
"file_hash"
241+
), # Use original hash
242+
"content": None,
236243
}
237244

238245
return [TextContent(type="text", text=json.dumps(results, indent=2))]

0 commit comments

Comments
 (0)