fix(filesystem): handle Windows EPERM on file rename when target is locked#3632
Open
ctonneslan wants to merge 1 commit intomodelcontextprotocol:mainfrom
Open
Conversation
…ocked On Windows, fs.rename() throws EPERM when the target file is locked by another process (e.g., open in VS Code or Notepad). This breaks both write_file and edit_file operations. Added an atomicReplace() helper that falls back to copyFile + unlink on Windows when rename fails with EPERM. This preserves the atomic write semantics on Linux/macOS while working around the Windows file locking limitation. Fixes modelcontextprotocol#3199
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
On Windows,
fs.rename()throwsEPERMwhen the target file is locked by another process (e.g., open in VS Code, Notepad, or any editor). This breaks bothwrite_fileandedit_fileoperations with:This works fine on Linux and macOS where rename atomically replaces the target regardless of read locks.
Fix
Added an
atomicReplace()helper function that:fs.rename()first (preserves atomic semantics on Linux/macOS)EPERM+process.platform === 'win32'), falls back tofs.copyFile()+fs.unlink()of the temp fileApplied to both write locations in
lib.ts:writeFileSecure()(used bywrite_filetool)applyFileEdits()(used byedit_filetool)The fallback is only triggered on Windows and only when the specific
EPERMerror occurs, so behavior on other platforms is unchanged.Fixes #3199