@jwjp/ftp-mcp 0.6.1 → 0.7.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 CHANGED
@@ -1,8 +1,8 @@
1
1
  # FTP Workspace MCP
2
2
 
3
- A local stdio MCP server for AI coding work on projects reachable through **FTP or SFTP**. Explicit and implicit FTPS are also supported. It works with any project language or framework and exposes four file-level tools: `remote_list`, `remote_download`, `remote_preview_upload`, and `remote_upload`.
3
+ A local stdio MCP server for AI coding work on projects reachable through **FTP or SFTP**. Explicit and implicit FTPS are also supported. It works with any project language or framework and exposes four file-level tools: `remote_list`, `remote_download`, `remote_preview_upload`, and `remote_upload`. Two more, `remote_preview_delete` and `remote_delete`, appear only when `REMOTE_ALLOW_DELETE=true`.
4
4
 
5
- The server has no recursive sync, remote delete, or shell execution tool. In version 0.2, the tool names changed from `ftp_*` to `remote_*` to reflect SFTP support.
5
+ The server has no recursive sync, directory deletion, or shell execution tool. Deleting single files is off by default. In version 0.2, the tool names changed from `ftp_*` to `remote_*` to reflect SFTP support.
6
6
 
7
7
  ## Requirements
8
8
 
@@ -18,6 +18,8 @@ Install the public `@jwjp/ftp-mcp` package globally. Its executable is `ftp-work
18
18
  npm install -g @jwjp/ftp-mcp
19
19
  ```
20
20
 
21
+ The package is also listed in the [official MCP Registry](https://registry.modelcontextprotocol.io/v0.1/servers?search=io.github.jwjp/ftp-mcp) as `io.github.jwjp/ftp-mcp`. Clients that install from the registry read the configuration variables from that entry.
22
+
21
23
  Recent npm versions may report that install scripts for `ssh2` and `cpu-features` were blocked. Those scripts only build optional native speedups; SFTP works without them, so you can leave them blocked.
22
24
 
23
25
  Or run it from a GitHub checkout:
@@ -48,6 +50,7 @@ Set the following variables in the environment that launches the MCP server. Kee
48
50
  | `REMOTE_EXCLUDE` | Optional comma-separated additional names or relative paths, such as `uploads,logs,cache` |
49
51
  | `REMOTE_MAX_FILE_BYTES` | Optional per-file limit; default 10 MiB, maximum 100 MiB |
50
52
  | `REMOTE_IDLE_TIMEOUT_MS` | Optional; how long an unused remote connection stays open for reuse, in milliseconds (default 30000; `0` connects for every tool call) |
53
+ | `REMOTE_ALLOW_DELETE` | Optional; `true` adds the single-file delete tools (default `false`) |
51
54
 
52
55
  SFTP is SSH File Transfer Protocol, not FTP over TLS. For SFTP, get the SSH host key fingerprint from your hosting provider or another trusted channel before connecting. The server rejects a mismatched host key. FTP sends credentials in plaintext; use SFTP or FTPS if available. The server prints a warning to stderr when it starts with plain FTP. FTPS certificate verification remains enabled.
53
56
 
@@ -106,7 +109,7 @@ The Codex desktop app, CLI, and IDE extension share MCP settings. Add the server
106
109
  [mcp_servers.remote_workspace]
107
110
  command = "node"
108
111
  args = ["C:/absolute/path/to/ftp-mcp/src/server.js"]
109
- env_vars = ["REMOTE_PROTOCOL", "REMOTE_HOST", "REMOTE_USER", "REMOTE_PASSWORD", "REMOTE_ROOT", "LOCAL_ROOT", "REMOTE_PORT", "SFTP_HOST_KEY_SHA256", "SFTP_PRIVATE_KEY_FILE", "SFTP_PASSPHRASE", "SFTP_TIMEOUT_MS", "REMOTE_EXCLUDE", "REMOTE_MAX_FILE_BYTES", "REMOTE_IDLE_TIMEOUT_MS"]
112
+ env_vars = ["REMOTE_PROTOCOL", "REMOTE_HOST", "REMOTE_USER", "REMOTE_PASSWORD", "REMOTE_ROOT", "LOCAL_ROOT", "REMOTE_PORT", "SFTP_HOST_KEY_SHA256", "SFTP_PRIVATE_KEY_FILE", "SFTP_PASSPHRASE", "SFTP_TIMEOUT_MS", "REMOTE_EXCLUDE", "REMOTE_MAX_FILE_BYTES", "REMOTE_IDLE_TIMEOUT_MS", "REMOTE_ALLOW_DELETE"]
110
113
  ```
111
114
 
112
115
  Replace the script path and set the required variables locally before starting Codex. `env_vars` forwards named values without storing them in TOML. Restart Codex after changing configuration. `codex mcp list` or `/mcp` shows the server. The same entry may instead go in a trusted project's `.codex/config.toml`. See the [Codex MCP guide](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
@@ -125,6 +128,15 @@ Upload tokens are single-use and held only in the MCP process. Restarting it req
125
128
 
126
129
  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.
127
130
 
131
+ ### Deleting a remote file
132
+
133
+ With `REMOTE_ALLOW_DELETE=true`, the server also offers:
134
+
135
+ 1. `remote_preview_delete({"path":"src/old.php"})` hashes the remote file and returns a `deleteToken`. It deletes nothing.
136
+ 2. `remote_delete({"path":"src/old.php","deleteToken":"..."})` within ten minutes. The file is read again, and it is deleted only if its SHA-256 still matches the preview. The listing must then no longer show it.
137
+
138
+ Only regular files within `REMOTE_MAX_FILE_BYTES` can be deleted. Directories, symlinks, and excluded paths cannot. Tokens are single-use, and the local copy is never touched. The server's instructions tell the agent to delete only when the user asked for it, but an agent can still call the tools on its own. Turn deletion on only for projects where a lost remote file can be restored, and leave it off otherwise. Another writer can change the file between the final check and the deletion.
139
+
128
140
  ## Boundaries
129
141
 
130
142
  - Paths stay beneath fixed local and remote roots. Parent traversal, absolute paths, control characters, excluded entries, and discovered symlinks are rejected. Colons and trailing dots are rejected everywhere, and reserved device names such as `NUL` or `con.php` on Windows, so Windows aliases (`.env::$DATA`, `.mcp.json.`) cannot reach an excluded file. Existing local paths are also checked under their resolved name, which catches 8.3 short names such as `NODE_M~1`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jwjp/ftp-mcp",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "A guarded FTP/SFTP MCP server for local AI coding workflows",
5
5
  "mcpName": "io.github.jwjp/ftp-mcp",
6
6
  "repository": {
package/src/config.js CHANGED
@@ -54,6 +54,9 @@ export function loadConfig(env = process.env) {
54
54
  throw new UserError('REMOTE_IDLE_TIMEOUT_MS must be an integer between 0 and 2147483647.');
55
55
  }
56
56
 
57
+ const allowDelete = { true: true, false: false, undefined: false }[env.REMOTE_ALLOW_DELETE?.trim().toLowerCase()];
58
+ if (allowDelete === undefined) throw new UserError('REMOTE_ALLOW_DELETE must be true or false.');
59
+
57
60
  let sftpPrivateKeyFile = null;
58
61
  let sftpHostKeySha256 = null;
59
62
  let sftpTimeoutMs = DEFAULT_SFTP_TIMEOUT_MS;
@@ -81,7 +84,7 @@ export function loadConfig(env = process.env) {
81
84
  return {
82
85
  protocol, host, user, password, port,
83
86
  secure: protocol === 'ftps' ? true : protocol === 'ftps-implicit' ? 'implicit' : false,
84
- remoteRoot: root, localRoot, extra, maxBytes, idleTimeoutMs,
87
+ remoteRoot: root, localRoot, extra, maxBytes, idleTimeoutMs, allowDelete,
85
88
  sftpPrivateKeyFile, sftpPassphrase: env.SFTP_PASSPHRASE,
86
89
  sftpHostKeySha256, sftpTimeoutMs, warnings
87
90
  };
package/src/server.js CHANGED
@@ -45,6 +45,18 @@ const previewOutput = z.object({
45
45
  createDirectories: z.array(z.string()),
46
46
  uploadToken: z.string().nullable()
47
47
  });
48
+ const deletePreviewOutput = z.object({
49
+ path: z.string(),
50
+ sha256,
51
+ bytes: z.number(),
52
+ deleteToken: z.string()
53
+ });
54
+ const deleteOutput = z.object({
55
+ path: z.string(),
56
+ status: z.literal('deleted'),
57
+ sha256,
58
+ bytes: z.number()
59
+ });
48
60
  const uploadOutput = z.object({
49
61
  path: z.string(),
50
62
  status: z.literal('uploaded'),
@@ -80,7 +92,10 @@ function tool(name, workspace, fn) {
80
92
 
81
93
  export function createServer(workspace) {
82
94
  const server = new McpServer({ name: 'ftp-workspace-mcp', version }, {
83
- instructions: 'Use relative paths beneath the configured roots. List or download only needed files. Call remote_preview_upload before remote_upload. There are no delete or recursive sync tools.'
95
+ instructions: 'Use relative paths beneath the configured roots. List or download only needed files. Call remote_preview_upload before remote_upload. '
96
+ + (workspace.config?.allowDelete
97
+ ? 'Delete a remote file only when the user asked for it: call remote_preview_delete, show the user the path, then call remote_delete. There is no recursive sync or directory deletion.'
98
+ : 'There are no delete or recursive sync tools.')
84
99
  });
85
100
  server.registerTool('remote_list', {
86
101
  description: `List up to ${LIST_LIMIT} allowed entries in one remote directory, sorted by name. Use an empty path for the configured root. If truncated is true, pass nextCursor as cursor with the same path.`,
@@ -106,6 +121,22 @@ export function createServer(workspace) {
106
121
  outputSchema: uploadOutput,
107
122
  annotations: { readOnlyHint: false, destructiveHint: true }
108
123
  }, tool('remote_upload', workspace, ({ path, uploadToken }) => workspace.upload(path, uploadToken)));
124
+ // Registered only when REMOTE_ALLOW_DELETE=true, so a client never sees
125
+ // the tools unless the user turned deletion on.
126
+ if (workspace.config?.allowDelete) {
127
+ server.registerTool('remote_preview_delete', {
128
+ description: 'Hash one remote file and issue a short-lived token for deleting exactly that version. Deletes nothing.',
129
+ inputSchema: z.object({ path: relativeInput }),
130
+ outputSchema: deletePreviewOutput,
131
+ annotations: { readOnlyHint: true }
132
+ }, tool('remote_preview_delete', workspace, ({ path }) => workspace.previewDelete(path)));
133
+ server.registerTool('remote_delete', {
134
+ description: 'Delete exactly one remote file after remote_preview_delete, only if its content still matches the preview. Use only when the user asked for the deletion. Directories are never deleted.',
135
+ inputSchema: z.object({ path: relativeInput, deleteToken: z.string().uuid() }),
136
+ outputSchema: deleteOutput,
137
+ annotations: { readOnlyHint: false, destructiveHint: true }
138
+ }, tool('remote_delete', workspace, ({ path, deleteToken }) => workspace.delete(path, deleteToken)));
139
+ }
109
140
  return server;
110
141
  }
111
142
 
package/src/workspace.js CHANGED
@@ -30,11 +30,16 @@ export class FtpWorkspace {
30
30
  #clientQueue = Promise.resolve();
31
31
  #idle = null;
32
32
  #closed = false;
33
+ // Parent directories already checked during the current operation, per
34
+ // connection. Checking each once saves a LIST per level on every lookup;
35
+ // a server-side change between checks was never excluded anyway.
36
+ #verified = new WeakMap();
33
37
 
34
38
  constructor(config, clientFactory = () => createTransport(config)) {
35
39
  this.config = config;
36
40
  this.clientFactory = clientFactory;
37
41
  this.previews = new Map();
42
+ this.deletions = new Map();
38
43
  this.pendingWrite = Promise.resolve();
39
44
  }
40
45
 
@@ -55,15 +60,18 @@ export class FtpWorkspace {
55
60
 
56
61
  async #useClient(action) {
57
62
  const client = await this.#acquire();
63
+ this.#verified.set(client, new Set());
58
64
  let result;
59
65
  try {
60
66
  result = await action(client);
61
67
  } catch (error) {
68
+ this.#verified.delete(client);
62
69
  // A failed operation can leave a transfer half done or the connection
63
70
  // in an unknown state. Never hand that connection to the next caller.
64
71
  await closeQuietly(client);
65
72
  throw error;
66
73
  }
74
+ this.#verified.delete(client);
67
75
  await this.#release(client);
68
76
  return result;
69
77
  }
@@ -120,7 +128,10 @@ export class FtpWorkspace {
120
128
 
121
129
  async entry(client, relative) {
122
130
  const parts = relative.split('/');
131
+ const verified = this.#verified.get(client);
123
132
  for (let i = 0; i < parts.length; i++) {
133
+ const directory = parts.slice(0, i + 1).join('/');
134
+ if (i < parts.length - 1 && verified?.has(directory)) continue;
124
135
  const parent = parts.slice(0, i).join('/') || '.';
125
136
  const entries = await client.list(parent);
126
137
  const found = entries.find(item => item.name === parts[i]);
@@ -131,6 +142,7 @@ export class FtpWorkspace {
131
142
  if (found.type === FileType.SymbolicLink) throw new UserError('Remote symlink paths are not allowed.');
132
143
  if (i < parts.length - 1 && found.type !== FileType.Directory) throw new UserError('Remote parent is not a directory.');
133
144
  if (i === parts.length - 1) return found;
145
+ verified?.add(directory);
134
146
  }
135
147
  }
136
148
 
@@ -138,12 +150,16 @@ export class FtpWorkspace {
138
150
  // An existing parent must be a real directory.
139
151
  async #missingDirectories(client, relative) {
140
152
  const parts = relative.split('/').slice(0, -1);
153
+ const verified = this.#verified.get(client);
141
154
  for (let i = 0; i < parts.length; i++) {
155
+ const directory = parts.slice(0, i + 1).join('/');
156
+ if (verified?.has(directory)) continue;
142
157
  const parent = parts.slice(0, i).join('/') || '.';
143
158
  const found = (await client.list(parent)).find(item => item.name === parts[i]);
144
159
  if (!found) return parts.slice(i).map((_, j) => parts.slice(0, i + j + 1).join('/'));
145
160
  if (found.type === FileType.SymbolicLink) throw new UserError('Remote symlink paths are not allowed.');
146
161
  if (found.type !== FileType.Directory) throw new UserError('Remote parent is not a directory.');
162
+ verified?.add(directory);
147
163
  }
148
164
  return [];
149
165
  }
@@ -318,6 +334,43 @@ export class FtpWorkspace {
318
334
  return this.#withWrite(() => this.#commitUpload(relative, token));
319
335
  }
320
336
 
337
+ // Deletion is off unless REMOTE_ALLOW_DELETE is set. The preview hashes the
338
+ // remote file, and the token deletes only that version of it.
339
+ async previewDelete(relative) {
340
+ if (!this.config.allowDelete) throw new UserError('Remote deletion is disabled; set REMOTE_ALLOW_DELETE=true to enable it.');
341
+ relative = safePath(relative, this.config.extra);
342
+ return this.withClient(async client => {
343
+ const remote = await this.readRemote(client, relative);
344
+ if (!remote) throw new UserError('Remote file does not exist.');
345
+ const token = randomUUID();
346
+ if (this.deletions.size >= 100) this.deletions.delete(this.deletions.keys().next().value);
347
+ this.deletions.set(token, { relative, ...remote, expires: Date.now() + 10 * 60_000 });
348
+ return { path: relative, ...remote, deleteToken: token };
349
+ });
350
+ }
351
+
352
+ async delete(relative, token) {
353
+ if (!this.config.allowDelete) throw new UserError('Remote deletion is disabled; set REMOTE_ALLOW_DELETE=true to enable it.');
354
+ relative = safePath(relative, this.config.extra);
355
+ return this.#withWrite(() => {
356
+ const preview = this.deletions.get(token);
357
+ if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_delete again; its token is missing or expired.');
358
+ this.deletions.delete(token);
359
+ return this.withClient(async client => {
360
+ // Delete only the version the preview showed. Another writer can
361
+ // still change the file between this check and the deletion.
362
+ const current = await this.readRemote(client, relative);
363
+ if (current?.sha256 !== preview.sha256) throw new UserError('Remote file changed since the preview.');
364
+ await client.remove(relative);
365
+ let remaining;
366
+ try { remaining = await this.entry(client, relative); }
367
+ catch { throw new UserError('Delete was sent, but it could not be confirmed; list the directory before retrying.'); }
368
+ if (remaining) throw new UserError('Remote file is still present after the delete; inspect it before retrying.');
369
+ return { path: relative, status: 'deleted', sha256: preview.sha256, bytes: preview.bytes };
370
+ });
371
+ });
372
+ }
373
+
321
374
  async #commitUpload(relative, token) {
322
375
  const preview = this.previews.get(token);
323
376
  if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_upload again; its token is missing or expired.');
@@ -336,6 +389,7 @@ export class FtpWorkspace {
336
389
  for (const directory of missing) {
337
390
  await client.mkdir(directory);
338
391
  created.push(directory);
392
+ this.#verified.get(client)?.add(directory);
339
393
  }
340
394
  } catch (error) {
341
395
  throw await this.#removeCreated(client, created, error);
@@ -378,6 +432,7 @@ export class FtpWorkspace {
378
432
  // rmdir remove only an empty directory, so another writer's files are kept.
379
433
  async #removeCreated(client, created, error) {
380
434
  for (const directory of created.toReversed()) {
435
+ this.#verified.get(client)?.delete(directory);
381
436
  try { await client.rmdir(directory); }
382
437
  catch {
383
438
  const reason = error instanceof UserError ? error.message : 'Upload failed.';