@jwjp/ftp-mcp 0.3.2 → 0.4.0

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 CHANGED
@@ -116,10 +116,10 @@ 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
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 remote replacement can change permissions, and an interruption can leave a temporary or backup file. Use a separate deployment or backup process when interruption cannot be tolerated.
125
125
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jwjp/ftp-mcp",
3
- "version": "0.3.2",
3
+ "version": "0.4.0",
4
4
  "description": "A guarded FTP/SFTP MCP server for local AI coding workflows",
5
5
  "repository": {
6
6
  "type": "git",
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,10 @@ 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); }
82
86
  async close() { this.client.close(); }
83
87
  }
84
88
 
@@ -203,6 +207,16 @@ export class SftpTransport {
203
207
  return null;
204
208
  }
205
209
  async remove(relative) { await this.#run('cleanup', () => this.client.delete(this.remote(relative), true)); }
210
+ // ssh2-sftp-client's mkdir() succeeds when the directory already exists.
211
+ // Call the SFTP request directly so a directory another writer created is
212
+ // reported, not adopted and later removed as this upload's own.
213
+ async mkdir(relative) {
214
+ const target = this.remote(relative);
215
+ await this.#run('directory creation', () => new Promise((resolve, reject) => {
216
+ this.client.sftp.mkdir(target, error => error ? reject(error) : resolve());
217
+ }));
218
+ }
219
+ async rmdir(relative) { await this.#run('directory cleanup', () => this.client.rmdir(this.remote(relative), false)); }
206
220
  async close() {
207
221
  if (!this.#timeoutError) await this.#run('disconnect', () => this.client.end());
208
222
  }
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
- const remote = await this.readRemote(client, relative);
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,29 @@ 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
- // A listing catches a remote file that appeared, disappeared, or changed
311
- // size before any bytes are sent. A same-size change is caught by the
312
- // full comparison right before the rename.
313
- const current = await this.#remoteEntry(client, relative);
314
- if ((current === null) !== (preview.remoteSha256 === null) || (current && Number.isSafeInteger(current.size) && current.size !== preview.remoteBytes)) {
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 parent = path.posix.dirname(relative);
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 { handle } = await this.#openLocal(relative);
323
- if (!handle) throw new UserError('Local file changed during upload.');
324
- const source = Readable.from(this.#localChunks(handle), { objectMode: false });
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
- try {
339
- if (await this.entry(client, staged)) await client.remove(staged);
340
- } catch {
341
- const reason = error instanceof UserError ? error.message : 'Upload failed.';
342
- throw new UserError(`${reason} Temporary remote file may remain at ${staged}.`);
343
- }
344
- throw error;
340
+ throw await this.#removeCreated(client, created, error);
341
+ }
342
+ let backup;
343
+ let stagedFile;
344
+ try {
345
+ ({ backup, stagedFile } = await this.#stageAndRename(client, relative, preview));
346
+ } catch (error) {
347
+ // Nothing was renamed into place, so the new directories hold no file
348
+ // of this upload. Remove them so the remote tree is as it was.
349
+ throw await this.#removeCreated(client, created, error);
345
350
  }
346
351
  const recovery = backup ? ` The previous version remains at ${backup}.` : '';
347
352
  // The staged bytes were verified by hash, and a rename does not change
@@ -358,9 +363,64 @@ export class FtpWorkspace {
358
363
  try { await client.remove(backup); }
359
364
  catch { warning = `Upload succeeded, but the previous version remains at ${backup}; remove it manually.`; }
360
365
  }
361
- return { path: relative, status: 'uploaded', ...stagedFile, ...(warning ? { warning } : {}) };
366
+ return {
367
+ path: relative, status: 'uploaded', ...stagedFile,
368
+ ...(created.length ? { createdDirectories: created } : {}),
369
+ ...(warning ? { warning } : {})
370
+ };
362
371
  });
363
372
  }
373
+
374
+ // Remove directories this upload created, innermost first. RMD and SFTP
375
+ // rmdir remove only an empty directory, so another writer's files are kept.
376
+ async #removeCreated(client, created, error) {
377
+ for (const directory of created.toReversed()) {
378
+ try { await client.rmdir(directory); }
379
+ catch {
380
+ const reason = error instanceof UserError ? error.message : 'Upload failed.';
381
+ return new UserError(`${reason} Created remote directory ${directory} may remain.`, { cause: error });
382
+ }
383
+ }
384
+ return error;
385
+ }
386
+
387
+ async #stageAndRename(client, relative, preview) {
388
+ // A listing catches a remote file that appeared, disappeared, or changed
389
+ // size before any bytes are sent. A same-size change is caught by the
390
+ // full comparison right before the rename.
391
+ const current = await this.#remoteEntry(client, relative);
392
+ if ((current === null) !== (preview.remoteSha256 === null) || (current && Number.isSafeInteger(current.size) && current.size !== preview.remoteBytes)) {
393
+ throw new UserError('Remote file changed since the preview.');
394
+ }
395
+ const parent = path.posix.dirname(relative);
396
+ const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
397
+ try {
398
+ const { handle } = await this.#openLocal(relative);
399
+ if (!handle) throw new UserError('Local file changed during upload.');
400
+ const source = Readable.from(this.#localChunks(handle), { objectMode: false });
401
+ try { await client.uploadFrom(source, staged); }
402
+ finally {
403
+ source.destroy();
404
+ await handle.close();
405
+ }
406
+ const stagedFile = await this.readRemote(client, staged);
407
+ if (stagedFile?.sha256 !== preview.localSha256) throw new UserError('Staged upload verification failed.');
408
+ const latestLocal = await this.localFile(relative);
409
+ if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
410
+ const latestRemote = await this.readRemote(client, relative);
411
+ if ((latestRemote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
412
+ const backup = await client.rename(staged, relative, latestRemote !== null);
413
+ return { backup, stagedFile };
414
+ } catch (error) {
415
+ try {
416
+ if (await this.entry(client, staged)) await client.remove(staged);
417
+ } catch {
418
+ const reason = error instanceof UserError ? error.message : 'Upload failed.';
419
+ throw new UserError(`${reason} Temporary remote file may remain at ${staged}.`);
420
+ }
421
+ throw error;
422
+ }
423
+ }
364
424
  }
365
425
 
366
426
  function safeExcluded(parent, name, extra) {