Skip to content

Commit c5137fb

Browse files
committed
fix(filesystem): handle Windows EPERM when renaming over locked files
On Windows, fs.rename() fails with EPERM when the target file is locked by another process (e.g., open in an editor). This adds a fallback that uses fs.cp() + fs.unlink() when EPERM is encountered, allowing edits to succeed even when the file is open. Fixes modelcontextprotocol#3199
1 parent 10d3827 commit c5137fb

2 files changed

Lines changed: 82 additions & 6 deletions

File tree

‎src/filesystem/__tests__/lib.test.ts‎

Lines changed: 57 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -279,11 +279,66 @@ describe('Lib Functions', () => {
279279
describe('writeFileContent', () => {
280280
it('writes file content', async () => {
281281
mockFs.writeFile.mockResolvedValueOnce(undefined);
282-
282+
283283
await writeFileContent('/test/file.txt', 'new content');
284-
284+
285285
expect(mockFs.writeFile).toHaveBeenCalledWith('/test/file.txt', 'new content', { encoding: "utf-8", flag: 'wx' });
286286
});
287+
288+
it('falls back to fs.cp when fs.rename fails with EPERM (Windows locked file)', async () => {
289+
// First write fails because file exists
290+
const eexistError = new Error('EEXIST') as NodeJS.ErrnoException;
291+
eexistError.code = 'EEXIST';
292+
293+
// Rename fails with EPERM (Windows file lock)
294+
const epermError = new Error('EPERM') as NodeJS.ErrnoException;
295+
epermError.code = 'EPERM';
296+
297+
mockFs.writeFile
298+
.mockRejectedValueOnce(eexistError) // First write fails (file exists)
299+
.mockResolvedValueOnce(undefined); // Temp file write succeeds
300+
mockFs.rename.mockRejectedValueOnce(epermError);
301+
mockFs.cp.mockResolvedValueOnce(undefined);
302+
mockFs.unlink.mockResolvedValueOnce(undefined);
303+
304+
await writeFileContent('/test/file.txt', 'new content');
305+
306+
// Should have tried rename first, then fallen back to cp + unlink
307+
expect(mockFs.rename).toHaveBeenCalledWith(
308+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
309+
'/test/file.txt'
310+
);
311+
expect(mockFs.cp).toHaveBeenCalledWith(
312+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/),
313+
'/test/file.txt',
314+
{ force: true }
315+
);
316+
expect(mockFs.unlink).toHaveBeenCalledWith(
317+
expect.stringMatching(/\/test\/file\.txt\.[a-f0-9]+\.tmp$/)
318+
);
319+
});
320+
321+
it('propagates non-EPERM errors from fs.rename', async () => {
322+
// First write fails because file exists
323+
const eexistError = new Error('EEXIST') as NodeJS.ErrnoException;
324+
eexistError.code = 'EEXIST';
325+
326+
// Rename fails with EACCES (not EPERM)
327+
const eaccesError = new Error('EACCES') as NodeJS.ErrnoException;
328+
eaccesError.code = 'EACCES';
329+
330+
mockFs.writeFile
331+
.mockRejectedValueOnce(eexistError)
332+
.mockResolvedValueOnce(undefined);
333+
mockFs.rename.mockRejectedValueOnce(eaccesError);
334+
mockFs.unlink.mockResolvedValueOnce(undefined); // Cleanup of temp file
335+
336+
await expect(writeFileContent('/test/file.txt', 'content'))
337+
.rejects.toThrow('EACCES');
338+
339+
// Should not have tried cp fallback
340+
expect(mockFs.cp).not.toHaveBeenCalled();
341+
});
287342
});
288343

289344
});

‎src/filesystem/lib.ts‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,27 @@ export async function readFileContent(filePath: string, encoding: string = 'utf-
135135
return await fs.readFile(filePath, encoding as BufferEncoding);
136136
}
137137

138+
/**
139+
* Atomically replaces a file by renaming a temporary file over it.
140+
* On Windows, fs.rename() fails with EPERM when the target file is locked
141+
* by another process (e.g., open in an editor). This function falls back
142+
* to fs.cp() + fs.unlink() which can overwrite locked files.
143+
*/
144+
async function atomicReplaceFile(tempPath: string, targetPath: string): Promise<void> {
145+
try {
146+
await fs.rename(tempPath, targetPath);
147+
} catch (error) {
148+
// On Windows, rename fails with EPERM if target file is locked by another process
149+
if ((error as NodeJS.ErrnoException).code === 'EPERM') {
150+
// Fallback: copy over the locked file, then remove temp file
151+
await fs.cp(tempPath, targetPath, { force: true });
152+
await fs.unlink(tempPath);
153+
} else {
154+
throw error;
155+
}
156+
}
157+
}
158+
138159
export async function writeFileContent(filePath: string, content: string): Promise<void> {
139160
try {
140161
// Security: 'wx' flag ensures exclusive creation - fails if file/symlink exists,
@@ -148,12 +169,12 @@ export async function writeFileContent(filePath: string, content: string): Promi
148169
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
149170
try {
150171
await fs.writeFile(tempPath, content, 'utf-8');
151-
await fs.rename(tempPath, filePath);
152-
} catch (renameError) {
172+
await atomicReplaceFile(tempPath, filePath);
173+
} catch (replaceError) {
153174
try {
154175
await fs.unlink(tempPath);
155176
} catch {}
156-
throw renameError;
177+
throw replaceError;
157178
}
158179
} else {
159180
throw error;
@@ -246,7 +267,7 @@ export async function applyFileEdits(
246267
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
247268
try {
248269
await fs.writeFile(tempPath, modifiedContent, 'utf-8');
249-
await fs.rename(tempPath, filePath);
270+
await atomicReplaceFile(tempPath, filePath);
250271
} catch (error) {
251272
try {
252273
await fs.unlink(tempPath);

0 commit comments

Comments
 (0)