@jwjp/ftp-mcp 0.3.2 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/package.json +1 -1
- package/src/server.js +2 -2
- package/src/transports.js +30 -0
- package/src/workspace.js +111 -37
package/README.md
CHANGED
|
@@ -116,12 +116,12 @@ Replace the script path and set the required variables locally before starting C
|
|
|
116
116
|
1. `remote_list({"path":""})`, then list only relevant subdirectories. Each page returns up to 200 allowed entries sorted by name, with case-sensitive ordering. When `truncated` is `true`, pass `nextCursor` as `cursor` with the same `path` to get the next page. Each page reads the current directory, so files added or renamed at or before the cursor may be missed.
|
|
117
117
|
2. `remote_download({"path":"src/example.php"})`. If a local copy differs, the tool returns its SHA-256; compare it before replacing it with `expectedLocalSha256`.
|
|
118
118
|
3. Edit and test locally.
|
|
119
|
-
4. `remote_preview_upload({"path":"src/example.php"})`. Review the path and both hashes. It returns an `uploadToken` when content differs.
|
|
120
|
-
5. `remote_upload({"path":"src/example.php","uploadToken":"..."})` within ten minutes. A changed local or remote file invalidates the preview.
|
|
119
|
+
4. `remote_preview_upload({"path":"src/example.php"})`. Review the path and both hashes. It returns an `uploadToken` when content differs. `createDirectories` lists remote parent directories that do not exist yet; the upload creates them.
|
|
120
|
+
5. `remote_upload({"path":"src/example.php","uploadToken":"..."})` within ten minutes. A changed local or remote file invalidates the preview, and so does a listed directory that someone else created in the meantime. The result lists any `createdDirectories`.
|
|
121
121
|
|
|
122
|
-
Upload tokens are single-use and held only in the MCP process. Restarting it requires a fresh preview. Uploads first check the remote listing against the preview, so a file that appeared, disappeared, or changed size stops the upload before any bytes are sent. They then write a temporary remote file, verify it by SHA-256, compare the remote target with the preview by SHA-256 again, and rename the temporary file into place. After the rename, the listing must show a file of the uploaded size. For FTP replacement, the old file is moved to a backup name because some servers refuse to rename over an existing file. If the final rename fails, the server checks whether the target is absent before attempting to restore the backup. If it cannot confirm the result, it reports the target and backup paths for inspection. The server also keeps the FTP backup until it verifies the final file and reports the backup location if verification or cleanup fails. For SFTP replacement, the server must support the `posix-rename@openssh.com` extension.
|
|
122
|
+
Upload tokens are single-use and held only in the MCP process. Restarting it requires a fresh preview. Uploads first create the directories the preview listed, one at a time, outermost first. If the upload then fails before the file is renamed into place, the server removes those directories again, innermost first. It removes only empty directories, so files another writer added are kept, and it reports any directory it could not remove. Uploads then check the remote listing against the preview, so a file that appeared, disappeared, or changed size stops the upload before any bytes are sent. They then write a temporary remote file, verify it by SHA-256, compare the remote target with the preview by SHA-256 again, and rename the temporary file into place. After the rename, the listing must show a file of the uploaded size. For FTP replacement, the old file is moved to a backup name because some servers refuse to rename over an existing file. If the final rename fails, the server checks whether the target is absent before attempting to restore the backup. If it cannot confirm the result, it reports the target and backup paths for inspection. The server also keeps the FTP backup until it verifies the final file and reports the backup location if verification or cleanup fails. For SFTP replacement, the server must support the `posix-rename@openssh.com` extension.
|
|
123
123
|
|
|
124
|
-
Each MCP process keeps one remote connection and runs one tool call on it at a time. A connection unused for `REMOTE_IDLE_TIMEOUT_MS` is closed, and an idle connection is checked (FTP `NOOP`, or an SFTP directory query) before reuse, so one the server has dropped is replaced. A check that gets no answer within 5 seconds, as happens when a firewall drops an idle connection silently, also leads to a new connection. A failed tool call closes its connection, and the next call reconnects. Each MCP process runs one upload or download at a time. Other MCP processes, editors, and remote writers can still change files between verification and rename. FTP replacement has a brief interval when the target name is absent. A
|
|
124
|
+
Each MCP process keeps one remote connection and runs one tool call on it at a time. A connection unused for `REMOTE_IDLE_TIMEOUT_MS` is closed, and an idle connection is checked (FTP `NOOP`, or an SFTP directory query) before reuse, so one the server has dropped is replaced. A check that gets no answer within 5 seconds, as happens when a firewall drops an idle connection silently, also leads to a new connection. A failed tool call closes its connection, and the next call reconnects. Each MCP process runs one upload or download at a time. Other MCP processes, editors, and remote writers can still change files between verification and rename. FTP replacement has a brief interval when the target name is absent. A replacement keeps the permission bits of the file it replaces: the server copies them to the temporary file before the rename. SFTP reads and sets them directly. FTP reads them from a Unix-style listing and sets them with `SITE CHMOD`; a server that lists no permissions, such as most Windows servers, is left alone. If the server refuses the change, the upload still completes and its result carries a warning with the previous mode. Ownership is not preserved. An interruption can leave a temporary or backup file. Use a separate deployment or backup process when interruption cannot be tolerated.
|
|
125
125
|
|
|
126
126
|
## Boundaries
|
|
127
127
|
|
package/package.json
CHANGED
package/src/server.js
CHANGED
|
@@ -51,12 +51,12 @@ export function createServer(workspace) {
|
|
|
51
51
|
annotations: { readOnlyHint: false }
|
|
52
52
|
}, tool('remote_download', workspace, ({ path, expectedLocalSha256 }) => workspace.download(path, expectedLocalSha256)));
|
|
53
53
|
server.registerTool('remote_preview_upload', {
|
|
54
|
-
description: 'Compare one local file with its remote counterpart and issue a short-lived token if upload is needed.',
|
|
54
|
+
description: 'Compare one local file with its remote counterpart and issue a short-lived token if upload is needed. createDirectories lists the missing remote parent directories the upload would create.',
|
|
55
55
|
inputSchema: z.object({ path: relativeInput }),
|
|
56
56
|
annotations: { readOnlyHint: true }
|
|
57
57
|
}, tool('remote_preview_upload', workspace, ({ path }) => workspace.previewUpload(path)));
|
|
58
58
|
server.registerTool('remote_upload', {
|
|
59
|
-
description: 'Upload exactly one file after preview. Reject changed local or remote content and verify uploaded bytes. Replacement may not be atomic.',
|
|
59
|
+
description: 'Upload exactly one file after preview, first creating the remote directories the preview listed. Reject changed local or remote content and verify uploaded bytes. Replacement may not be atomic.',
|
|
60
60
|
inputSchema: z.object({ path: relativeInput, uploadToken: z.string().uuid() }),
|
|
61
61
|
annotations: { readOnlyHint: false, destructiveHint: true }
|
|
62
62
|
}, tool('remote_upload', workspace, ({ path, uploadToken }) => workspace.upload(path, uploadToken)));
|
package/src/transports.js
CHANGED
|
@@ -79,6 +79,21 @@ export class FtpTransport {
|
|
|
79
79
|
return backup;
|
|
80
80
|
}
|
|
81
81
|
async remove(relative) { await this.client.remove(relative); }
|
|
82
|
+
// MKD and RMD act on one directory: no parents are created, and only an
|
|
83
|
+
// empty directory is removed.
|
|
84
|
+
async mkdir(relative) { await this.client.send(`MKD ${relative}`); }
|
|
85
|
+
async rmdir(relative) { await this.client.removeEmptyDir(relative); }
|
|
86
|
+
// Permission bits from a Unix-style listing, or null when the server does
|
|
87
|
+
// not report them (as Windows FTP servers do not).
|
|
88
|
+
async mode(relative) {
|
|
89
|
+
const parent = path.posix.dirname(relative);
|
|
90
|
+
const name = path.posix.basename(relative);
|
|
91
|
+
const permissions = (await this.client.list(parent)).find(entry => entry.name === name)?.permissions;
|
|
92
|
+
if (!permissions) return null;
|
|
93
|
+
return (permissions.user << 6) | (permissions.group << 3) | permissions.world;
|
|
94
|
+
}
|
|
95
|
+
// SITE CHMOD is a common extension, not part of the FTP standard.
|
|
96
|
+
async chmod(relative, mode) { await this.client.send(`SITE CHMOD ${mode.toString(8).padStart(3, '0')} ${relative}`); }
|
|
82
97
|
async close() { this.client.close(); }
|
|
83
98
|
}
|
|
84
99
|
|
|
@@ -203,6 +218,21 @@ export class SftpTransport {
|
|
|
203
218
|
return null;
|
|
204
219
|
}
|
|
205
220
|
async remove(relative) { await this.#run('cleanup', () => this.client.delete(this.remote(relative), true)); }
|
|
221
|
+
// ssh2-sftp-client's mkdir() succeeds when the directory already exists.
|
|
222
|
+
// Call the SFTP request directly so a directory another writer created is
|
|
223
|
+
// reported, not adopted and later removed as this upload's own.
|
|
224
|
+
async mkdir(relative) {
|
|
225
|
+
const target = this.remote(relative);
|
|
226
|
+
await this.#run('directory creation', () => new Promise((resolve, reject) => {
|
|
227
|
+
this.client.sftp.mkdir(target, error => error ? reject(error) : resolve());
|
|
228
|
+
}));
|
|
229
|
+
}
|
|
230
|
+
async rmdir(relative) { await this.#run('directory cleanup', () => this.client.rmdir(this.remote(relative), false)); }
|
|
231
|
+
async mode(relative) {
|
|
232
|
+
const { mode } = await this.#run('permission check', () => this.client.stat(this.remote(relative)));
|
|
233
|
+
return Number.isInteger(mode) ? mode & 0o777 : null;
|
|
234
|
+
}
|
|
235
|
+
async chmod(relative, mode) { await this.#run('permission change', () => this.client.chmod(this.remote(relative), mode)); }
|
|
206
236
|
async close() {
|
|
207
237
|
if (!this.#timeoutError) await this.#run('disconnect', () => this.client.end());
|
|
208
238
|
}
|
package/src/workspace.js
CHANGED
|
@@ -134,6 +134,20 @@ export class FtpWorkspace {
|
|
|
134
134
|
}
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
+
// The parent directories of a file that do not exist yet, outermost first.
|
|
138
|
+
// An existing parent must be a real directory.
|
|
139
|
+
async #missingDirectories(client, relative) {
|
|
140
|
+
const parts = relative.split('/').slice(0, -1);
|
|
141
|
+
for (let i = 0; i < parts.length; i++) {
|
|
142
|
+
const parent = parts.slice(0, i).join('/') || '.';
|
|
143
|
+
const found = (await client.list(parent)).find(item => item.name === parts[i]);
|
|
144
|
+
if (!found) return parts.slice(i).map((_, j) => parts.slice(0, i + j + 1).join('/'));
|
|
145
|
+
if (found.type === FileType.SymbolicLink) throw new UserError('Remote symlink paths are not allowed.');
|
|
146
|
+
if (found.type !== FileType.Directory) throw new UserError('Remote parent is not a directory.');
|
|
147
|
+
}
|
|
148
|
+
return [];
|
|
149
|
+
}
|
|
150
|
+
|
|
137
151
|
async list(relative = '', cursor = '') {
|
|
138
152
|
relative = safePath(relative, this.config.extra, { allowRoot: true });
|
|
139
153
|
return this.withClient(async client => {
|
|
@@ -282,16 +296,19 @@ export class FtpWorkspace {
|
|
|
282
296
|
const local = await this.localFile(relative);
|
|
283
297
|
if (local.sha256 === null) throw new UserError('Local file does not exist.');
|
|
284
298
|
return this.withClient(async client => {
|
|
285
|
-
|
|
299
|
+
// A file in a new remote directory has no remote version yet. The
|
|
300
|
+
// directories are created only by the approved upload.
|
|
301
|
+
const createDirectories = await this.#missingDirectories(client, relative);
|
|
302
|
+
const remote = createDirectories.length ? null : await this.readRemote(client, relative);
|
|
286
303
|
const localSha256 = local.sha256;
|
|
287
304
|
const remoteSha256 = remote?.sha256 ?? null;
|
|
288
305
|
const changed = localSha256 !== remoteSha256;
|
|
289
306
|
const token = changed ? randomUUID() : null;
|
|
290
307
|
if (token) {
|
|
291
308
|
if (this.previews.size >= 100) this.previews.delete(this.previews.keys().next().value);
|
|
292
|
-
this.previews.set(token, { relative, localSha256, remoteSha256, remoteBytes: remote?.bytes ?? null, expires: Date.now() + 10 * 60_000 });
|
|
309
|
+
this.previews.set(token, { relative, localSha256, remoteSha256, remoteBytes: remote?.bytes ?? null, createDirectories, expires: Date.now() + 10 * 60_000 });
|
|
293
310
|
}
|
|
294
|
-
return { path: relative, changed, localSha256, remoteSha256, localBytes: local.bytes, remoteBytes: remote?.bytes ?? null, uploadToken: token };
|
|
311
|
+
return { path: relative, changed, localSha256, remoteSha256, localBytes: local.bytes, remoteBytes: remote?.bytes ?? null, createDirectories, uploadToken: token };
|
|
295
312
|
});
|
|
296
313
|
}
|
|
297
314
|
|
|
@@ -307,41 +324,30 @@ export class FtpWorkspace {
|
|
|
307
324
|
const local = await this.localFile(relative);
|
|
308
325
|
if (local.sha256 !== preview.localSha256) throw new UserError('Local file changed since the preview.');
|
|
309
326
|
return this.withClient(async client => {
|
|
310
|
-
//
|
|
311
|
-
//
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
throw new UserError('Remote file changed since the preview.');
|
|
327
|
+
// Create only the directories the preview showed. If another writer
|
|
328
|
+
// created one since, the approved change no longer applies.
|
|
329
|
+
const missing = await this.#missingDirectories(client, relative);
|
|
330
|
+
if (missing.length !== preview.createDirectories.length || missing.some((directory, i) => directory !== preview.createDirectories[i])) {
|
|
331
|
+
throw new UserError('Remote directories changed since the preview.');
|
|
316
332
|
}
|
|
317
|
-
const
|
|
318
|
-
const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
|
|
319
|
-
let backup = null;
|
|
320
|
-
let stagedFile;
|
|
333
|
+
const created = [];
|
|
321
334
|
try {
|
|
322
|
-
const
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
try { await client.uploadFrom(source, staged); }
|
|
326
|
-
finally {
|
|
327
|
-
source.destroy();
|
|
328
|
-
await handle.close();
|
|
335
|
+
for (const directory of missing) {
|
|
336
|
+
await client.mkdir(directory);
|
|
337
|
+
created.push(directory);
|
|
329
338
|
}
|
|
330
|
-
stagedFile = await this.readRemote(client, staged);
|
|
331
|
-
if (stagedFile?.sha256 !== preview.localSha256) throw new UserError('Staged upload verification failed.');
|
|
332
|
-
const latestLocal = await this.localFile(relative);
|
|
333
|
-
if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
|
|
334
|
-
const latestRemote = await this.readRemote(client, relative);
|
|
335
|
-
if ((latestRemote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
|
|
336
|
-
backup = await client.rename(staged, relative, latestRemote !== null);
|
|
337
339
|
} catch (error) {
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
340
|
+
throw await this.#removeCreated(client, created, error);
|
|
341
|
+
}
|
|
342
|
+
let backup;
|
|
343
|
+
let stagedFile;
|
|
344
|
+
let permissionWarning;
|
|
345
|
+
try {
|
|
346
|
+
({ backup, stagedFile, permissionWarning } = await this.#stageAndRename(client, relative, preview));
|
|
347
|
+
} catch (error) {
|
|
348
|
+
// Nothing was renamed into place, so the new directories hold no file
|
|
349
|
+
// of this upload. Remove them so the remote tree is as it was.
|
|
350
|
+
throw await this.#removeCreated(client, created, error);
|
|
345
351
|
}
|
|
346
352
|
const recovery = backup ? ` The previous version remains at ${backup}.` : '';
|
|
347
353
|
// The staged bytes were verified by hash, and a rename does not change
|
|
@@ -353,14 +359,82 @@ export class FtpWorkspace {
|
|
|
353
359
|
if (uploaded?.type !== FileType.File || (Number.isSafeInteger(uploaded.size) && uploaded.size !== stagedFile.bytes)) {
|
|
354
360
|
throw new UserError(`Upload verification failed; inspect the remote file before retrying.${recovery}`);
|
|
355
361
|
}
|
|
356
|
-
|
|
362
|
+
const warnings = permissionWarning ? [permissionWarning] : [];
|
|
357
363
|
if (backup) {
|
|
358
364
|
try { await client.remove(backup); }
|
|
359
|
-
catch {
|
|
365
|
+
catch { warnings.push(`Upload succeeded, but the previous version remains at ${backup}; remove it manually.`); }
|
|
360
366
|
}
|
|
361
|
-
|
|
367
|
+
const warning = warnings.join(' ');
|
|
368
|
+
return {
|
|
369
|
+
path: relative, status: 'uploaded', ...stagedFile,
|
|
370
|
+
...(created.length ? { createdDirectories: created } : {}),
|
|
371
|
+
...(warning ? { warning } : {})
|
|
372
|
+
};
|
|
362
373
|
});
|
|
363
374
|
}
|
|
375
|
+
|
|
376
|
+
// Remove directories this upload created, innermost first. RMD and SFTP
|
|
377
|
+
// rmdir remove only an empty directory, so another writer's files are kept.
|
|
378
|
+
async #removeCreated(client, created, error) {
|
|
379
|
+
for (const directory of created.toReversed()) {
|
|
380
|
+
try { await client.rmdir(directory); }
|
|
381
|
+
catch {
|
|
382
|
+
const reason = error instanceof UserError ? error.message : 'Upload failed.';
|
|
383
|
+
return new UserError(`${reason} Created remote directory ${directory} may remain.`, { cause: error });
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return error;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// A replacement is a new file, so it would get the server's default
|
|
390
|
+
// permissions. Give the staged file the target's permission bits before the
|
|
391
|
+
// rename, so a private file such as a 0600 configuration stays private.
|
|
392
|
+
async #copyMode(client, relative, staged) {
|
|
393
|
+
const mode = await client.mode(relative);
|
|
394
|
+
if (mode === null || mode === await client.mode(staged)) return null;
|
|
395
|
+
try { await client.chmod(staged, mode); }
|
|
396
|
+
catch { return `Upload succeeded, but the server refused to keep the previous permissions (${mode.toString(8).padStart(3, '0')}); check ${relative}.`; }
|
|
397
|
+
return null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async #stageAndRename(client, relative, preview) {
|
|
401
|
+
// A listing catches a remote file that appeared, disappeared, or changed
|
|
402
|
+
// size before any bytes are sent. A same-size change is caught by the
|
|
403
|
+
// full comparison right before the rename.
|
|
404
|
+
const current = await this.#remoteEntry(client, relative);
|
|
405
|
+
if ((current === null) !== (preview.remoteSha256 === null) || (current && Number.isSafeInteger(current.size) && current.size !== preview.remoteBytes)) {
|
|
406
|
+
throw new UserError('Remote file changed since the preview.');
|
|
407
|
+
}
|
|
408
|
+
const parent = path.posix.dirname(relative);
|
|
409
|
+
const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
|
|
410
|
+
try {
|
|
411
|
+
const { handle } = await this.#openLocal(relative);
|
|
412
|
+
if (!handle) throw new UserError('Local file changed during upload.');
|
|
413
|
+
const source = Readable.from(this.#localChunks(handle), { objectMode: false });
|
|
414
|
+
try { await client.uploadFrom(source, staged); }
|
|
415
|
+
finally {
|
|
416
|
+
source.destroy();
|
|
417
|
+
await handle.close();
|
|
418
|
+
}
|
|
419
|
+
const stagedFile = await this.readRemote(client, staged);
|
|
420
|
+
if (stagedFile?.sha256 !== preview.localSha256) throw new UserError('Staged upload verification failed.');
|
|
421
|
+
const latestLocal = await this.localFile(relative);
|
|
422
|
+
if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
|
|
423
|
+
const latestRemote = await this.readRemote(client, relative);
|
|
424
|
+
if ((latestRemote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
|
|
425
|
+
const permissionWarning = latestRemote ? await this.#copyMode(client, relative, staged) : null;
|
|
426
|
+
const backup = await client.rename(staged, relative, latestRemote !== null);
|
|
427
|
+
return { backup, stagedFile, permissionWarning };
|
|
428
|
+
} catch (error) {
|
|
429
|
+
try {
|
|
430
|
+
if (await this.entry(client, staged)) await client.remove(staged);
|
|
431
|
+
} catch {
|
|
432
|
+
const reason = error instanceof UserError ? error.message : 'Upload failed.';
|
|
433
|
+
throw new UserError(`${reason} Temporary remote file may remain at ${staged}.`);
|
|
434
|
+
}
|
|
435
|
+
throw error;
|
|
436
|
+
}
|
|
437
|
+
}
|
|
364
438
|
}
|
|
365
439
|
|
|
366
440
|
function safeExcluded(parent, name, extra) {
|