@jwjp/ftp-mcp 0.2.1 → 0.3.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/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 jwjp
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jwjp
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,134 +1,153 @@
1
- # FTP Workspace MCP
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`.
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.
6
-
7
- ## Requirements
8
-
9
- - Node.js 22.12 or newer
10
- - FTP, SFTP, or FTPS access to the project
11
- - An MCP client that can start a local stdio server
12
-
13
- ## Install
14
-
15
- Once the npm release is available, install the public `@jwjp/ftp-mcp` package globally. Its executable remains `ftp-workspace-mcp` to avoid a command name collision with the existing unscoped `ftp-mcp` package:
16
-
17
- ```sh
18
- npm install -g @jwjp/ftp-mcp
19
- ```
20
-
21
- Until that release, install from GitHub:
22
-
23
- ```sh
24
- git clone https://github.com/jwjp/ftp-mcp.git
25
- cd ftp-mcp
26
- npm ci
27
- ```
28
-
29
- The MCP examples below use the GitHub checkout. After a global npm install, set the MCP command to `ftp-workspace-mcp` and omit the script path and `node` argument.
30
-
31
- Set the following variables in the environment that launches the MCP server. Keep passwords, private keys, and passphrases out of the project, chat, Git, `CLAUDE.md`, and shared MCP configuration. `.env.example` is a reference only; this server does not load `.env` files.
32
-
33
- | Variable | Meaning |
34
- | --- | --- |
35
- | `REMOTE_PROTOCOL` | `ftp`, `sftp`, `ftps`, or `ftps-implicit`; set explicitly |
36
- | `REMOTE_HOST` | Remote server hostname, without a URL scheme |
37
- | `REMOTE_USER` | Remote username |
38
- | `REMOTE_PASSWORD` | FTP/FTPS password, or SFTP password if not using a private key |
39
- | `REMOTE_ROOT` | Absolute remote project directory, for example `/site` |
40
- | `LOCAL_ROOT` | Existing absolute local project directory |
41
- | `REMOTE_PORT` | Optional; defaults to 21 for FTP/explicit FTPS, 22 for SFTP, 990 for implicit FTPS |
42
- | `SFTP_HOST_KEY_SHA256` | Required for SFTP; trusted SSH host key fingerprint in `SHA256:...` format |
43
- | `SFTP_PRIVATE_KEY_FILE` | Optional SFTP private key file path; use instead of a password |
44
- | `SFTP_PASSPHRASE` | Optional passphrase for an encrypted SFTP private key |
45
- | `REMOTE_EXCLUDE` | Optional comma-separated additional names or relative paths, such as `uploads,logs,cache` |
46
- | `REMOTE_MAX_FILE_BYTES` | Optional per-file limit; default 10 MiB, maximum 100 MiB |
47
-
48
- 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. FTPS certificate verification remains enabled.
49
-
50
- The former `FTP_*` variables still work for existing FTP/FTPS configurations. A missing `REMOTE_PROTOCOL` follows the old `FTP_SECURE` setting (`true` → `ftps`, `false` → `ftp`, `implicit` → `ftps-implicit`). New configurations should use the `REMOTE_*` names and explicitly set the protocol.
51
-
52
- The built-in exclusion list blocks `.git`, `.env` and `.env.*`, `.mcp.json`, `vendor`, and `node_modules` anywhere in the path. Extra entries match a name segment or an exact relative path and its descendants, case-insensitively. Review exclusions for each project. Install dependencies or build generated files locally when appropriate.
53
-
54
- ### VS Code with GitHub Copilot
55
-
56
- Use **Chat: Open Customizations → MCP Servers → Add Server → Command (stdio) → Global → Copilot Global**, or edit your personal `~/.copilot/mcp-config.json`. Current VS Code Copilot uses `mcpServers` in this personal file; `.vscode/mcp.json` is the older editor-managed format. See the [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration).
57
-
58
- Example personal configuration for SFTP (replace the paths and set the referenced user environment variables):
59
-
60
- ```json
61
- {
62
- "mcpServers": {
63
- "remote-workspace": {
64
- "type": "stdio",
65
- "command": "node",
66
- "args": ["/absolute/path/to/ftp-mcp/src/server.js"],
67
- "env": {
68
- "REMOTE_PROTOCOL": "sftp",
69
- "REMOTE_HOST": "${MY_REMOTE_HOST}",
70
- "REMOTE_USER": "${MY_REMOTE_USER}",
71
- "REMOTE_PASSWORD": "${MY_REMOTE_PASSWORD}",
72
- "REMOTE_ROOT": "/site",
73
- "LOCAL_ROOT": "/absolute/path/to/my-project",
74
- "SFTP_HOST_KEY_SHA256": "${MY_SFTP_HOST_KEY_SHA256}"
75
- },
76
- "tools": ["*"]
77
- }
78
- }
79
- }
80
- ```
81
-
82
- The `${NAME}` syntax is resolved by the Copilot harness. For key authentication, replace `REMOTE_PASSWORD` with `SFTP_PRIVATE_KEY_FILE` (and `SFTP_PASSPHRASE` if needed). For FTP, set `REMOTE_PROTOCOL` to `ftp`, omit `SFTP_HOST_KEY_SHA256`, and provide `REMOTE_PASSWORD`. On Windows, use absolute paths with JSON-escaped backslashes or forward slashes.
83
-
84
- ### Claude Code
85
-
86
- Claude Code can launch this same stdio server. Set the environment variables from the table above in the environment that starts Claude Code. From the **local project directory you want to edit**, register the server at local scope:
87
-
88
- ```sh
89
- claude mcp add --scope local --transport stdio remote-workspace -- node /absolute/path/to/ftp-mcp/src/server.js
90
- claude mcp get remote-workspace
91
- ```
92
-
93
- On Windows, use a path such as `C:/path/to/ftp-mcp/src/server.js`. Local scope keeps the definition private to that project. Do not pass passwords through `--env` in a shell command, because shell history and MCP configuration may retain them. Restart Claude Code after changing user environment variables. Run `/mcp` to check the connection. See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp).
94
-
95
- For a team-shared setup, Claude Code also reads `.mcp.json` in the project root. Use environment-variable references such as `${REMOTE_PASSWORD}` and never commit a literal password. This server excludes `.mcp.json` from transfers by default.
96
-
97
- ### Codex
98
-
99
- The Codex desktop app, CLI, and IDE extension share MCP settings. Add the server through **Settings → MCP servers → Add server → STDIO**, or add this entry to your personal `~/.codex/config.toml` (on Windows, `%USERPROFILE%\.codex\config.toml`):
100
-
101
- ```toml
102
- [mcp_servers.remote_workspace]
103
- command = "node"
104
- args = ["C:/absolute/path/to/ftp-mcp/src/server.js"]
105
- 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", "REMOTE_EXCLUDE", "REMOTE_MAX_FILE_BYTES"]
106
- ```
107
-
108
- 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).
109
-
110
- ## File workflow
111
-
112
- 1. `remote_list({"path":""})`, then list only relevant subdirectories.
113
- 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`.
114
- 3. Edit and test locally.
115
- 4. `remote_preview_upload({"path":"src/example.php"})`. Review the path and both hashes. It returns an `uploadToken` when content differs.
116
- 5. `remote_upload({"path":"src/example.php","uploadToken":"..."})` within ten minutes. A changed local or remote file invalidates the preview.
117
-
118
- Upload tokens are single-use and held only in the MCP process. Restarting it requires a fresh preview. Uploads first write and verify a temporary remote file, then rename it into place. For FTP replacement, the old file is briefly moved to a backup name because some servers refuse to rename over an existing file. If the final rename fails, the server attempts to restore the old file. For SFTP replacement, the server must support the `posix-rename@openssh.com` extension. The tool verifies remote bytes after the rename. A crash, lost connection, or server failure can still leave a temporary or backup file, and FTP replacement has a brief interval when the target name is absent. A replacement may also change file permissions. Use a separate deployment or backup process when interruption cannot be tolerated.
119
-
120
- ## Boundaries
121
-
122
- - Paths stay beneath fixed local and remote roots. Parent traversal, absolute paths, control characters, excluded entries, and discovered symlinks are rejected.
123
- - Each read and upload is limited by `REMOTE_MAX_FILE_BYTES`. Reads stop when the limit is exceeded, even if the server reports an incorrect size. A transfer may still buffer up to the configured limit in memory.
124
- - Remote symlink detection depends on the server listing and cannot prevent a server-side path change between validation and transfer.
125
- - No remote credentials or project files are stored in this repository. Reads and previews use memory. Downloads create a temporary file beside the local target before renaming it; uploads create a temporary file beside the remote target and may briefly create a backup on FTP replacement. Cleanup is attempted after failure, but a connection loss can prevent it.
126
-
127
- ## Development
128
-
129
- ```sh
130
- npm test
131
- npm audit --omit=dev
132
- ```
133
-
134
- Tests cover path restrictions, FTP and SFTP transport behavior, upload previews, and legacy and current MCP stdio handshakes. Test against your own server before relying on a production upload. Contributions are welcome under the MIT license.
1
+ # FTP Workspace MCP
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`.
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.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 22.12 or newer
10
+ - FTP, SFTP, or FTPS access to the project
11
+ - An MCP client that can start a local stdio server
12
+
13
+ ## Install
14
+
15
+ Install the public `@jwjp/ftp-mcp` package globally. Its executable is `ftp-workspace-mcp`, which avoids a command name collision with the existing unscoped `ftp-mcp` package:
16
+
17
+ ```sh
18
+ npm install -g @jwjp/ftp-mcp
19
+ ```
20
+
21
+ 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
+
23
+ Or run it from a GitHub checkout:
24
+
25
+ ```sh
26
+ git clone https://github.com/jwjp/ftp-mcp.git
27
+ cd ftp-mcp
28
+ npm ci
29
+ ```
30
+
31
+ The MCP examples below use the GitHub checkout. After a global npm install, set the MCP command to `ftp-workspace-mcp` and omit the script path and `node` argument.
32
+
33
+ Set the following variables in the environment that launches the MCP server. Keep passwords, private keys, and passphrases out of the project, chat, Git, `CLAUDE.md`, and shared MCP configuration. `.env.example` is a reference only; this server does not load `.env` files. An empty or whitespace-only value counts as unset, so an unresolved `${NAME}` reference falls back to the former `FTP_*` name or the default instead of overriding it.
34
+
35
+ | Variable | Meaning |
36
+ | --- | --- |
37
+ | `REMOTE_PROTOCOL` | `ftp`, `sftp`, `ftps`, or `ftps-implicit`; set explicitly |
38
+ | `REMOTE_HOST` | Remote server hostname, without a URL scheme |
39
+ | `REMOTE_USER` | Remote username |
40
+ | `REMOTE_PASSWORD` | FTP/FTPS password, or SFTP password if not using a private key |
41
+ | `REMOTE_ROOT` | Absolute remote project directory, for example `/site` |
42
+ | `LOCAL_ROOT` | Existing absolute local project directory |
43
+ | `REMOTE_PORT` | Optional; defaults to 21 for FTP/explicit FTPS, 22 for SFTP, 990 for implicit FTPS |
44
+ | `SFTP_HOST_KEY_SHA256` | Required for SFTP; trusted SSH host key fingerprint in `SHA256:...` format |
45
+ | `SFTP_PRIVATE_KEY_FILE` | Optional SFTP private key file path outside `LOCAL_ROOT`; use instead of a password |
46
+ | `SFTP_PASSPHRASE` | Optional passphrase for an encrypted SFTP private key |
47
+ | `SFTP_TIMEOUT_MS` | Optional SFTP timeout in milliseconds (default 30000) for connecting, for each remote request, and for a download or upload that makes no progress |
48
+ | `REMOTE_EXCLUDE` | Optional comma-separated additional names or relative paths, such as `uploads,logs,cache` |
49
+ | `REMOTE_MAX_FILE_BYTES` | Optional per-file limit; default 10 MiB, maximum 100 MiB |
50
+ | `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) |
51
+
52
+ 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
+
54
+ The former `FTP_*` variables still work for existing FTP/FTPS configurations. A missing `REMOTE_PROTOCOL` follows the old `FTP_SECURE` setting (`true` → `ftps`, `false` → `ftp`, `implicit` → `ftps-implicit`). If neither is set, the server uses `ftps` and prints a warning to stderr at startup. New configurations should use the `REMOTE_*` names and explicitly set the protocol.
55
+
56
+ The built-in exclusion list blocks these names anywhere in the path: `.git`, `.env` and `.env.*`, `vendor`, `node_modules`, credential files (`.ssh`, `.netrc`, `.git-credentials`, `.htpasswd`), and agent or MCP configuration (`.mcp.json`, `.claude`, `.codex`). Agent configuration is excluded because a downloaded settings file could make a local agent run commands. Extra entries match a name segment or an exact relative path and its descendants, case-insensitively. Review exclusions for each project. Install dependencies or build generated files locally when appropriate.
57
+
58
+ ### VS Code with GitHub Copilot
59
+
60
+ Use **Chat: Open Customizations → MCP Servers → Add Server → Command (stdio) → Global → Copilot Global**, or edit your personal `~/.copilot/mcp-config.json`. Current VS Code Copilot uses `mcpServers` in this personal file; `.vscode/mcp.json` is the older editor-managed format. See the [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration).
61
+
62
+ Example personal configuration for SFTP (replace the paths and set the referenced user environment variables):
63
+
64
+ ```json
65
+ {
66
+ "mcpServers": {
67
+ "remote-workspace": {
68
+ "type": "stdio",
69
+ "command": "node",
70
+ "args": ["/absolute/path/to/ftp-mcp/src/server.js"],
71
+ "env": {
72
+ "REMOTE_PROTOCOL": "sftp",
73
+ "REMOTE_HOST": "${MY_REMOTE_HOST}",
74
+ "REMOTE_USER": "${MY_REMOTE_USER}",
75
+ "REMOTE_PASSWORD": "${MY_REMOTE_PASSWORD}",
76
+ "REMOTE_ROOT": "/site",
77
+ "LOCAL_ROOT": "/absolute/path/to/my-project",
78
+ "SFTP_HOST_KEY_SHA256": "${MY_SFTP_HOST_KEY_SHA256}"
79
+ },
80
+ "tools": ["*"]
81
+ }
82
+ }
83
+ }
84
+ ```
85
+
86
+ The `${NAME}` syntax is resolved by the Copilot harness. For key authentication, replace `REMOTE_PASSWORD` with `SFTP_PRIVATE_KEY_FILE` (and `SFTP_PASSPHRASE` if needed). For FTP, set `REMOTE_PROTOCOL` to `ftp`, omit `SFTP_HOST_KEY_SHA256`, and provide `REMOTE_PASSWORD`. On Windows, use absolute paths with JSON-escaped backslashes or forward slashes.
87
+
88
+ ### Claude Code
89
+
90
+ Claude Code can launch this same stdio server. Set the environment variables from the table above in the environment that starts Claude Code. From the **local project directory you want to edit**, register the server at local scope:
91
+
92
+ ```sh
93
+ claude mcp add --scope local --transport stdio remote-workspace -- node /absolute/path/to/ftp-mcp/src/server.js
94
+ claude mcp get remote-workspace
95
+ ```
96
+
97
+ On Windows, use a path such as `C:/path/to/ftp-mcp/src/server.js`. Local scope keeps the definition private to that project. Do not pass passwords through `--env` in a shell command, because shell history and MCP configuration may retain them. Restart Claude Code after changing user environment variables. Run `/mcp` to check the connection. See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp).
98
+
99
+ For a team-shared setup, Claude Code also reads `.mcp.json` in the project root. Use environment-variable references such as `${REMOTE_PASSWORD}` and never commit a literal password. This server excludes `.mcp.json` from transfers by default.
100
+
101
+ ### Codex
102
+
103
+ The Codex desktop app, CLI, and IDE extension share MCP settings. Add the server through **Settings → MCP servers → Add server → STDIO**, or add this entry to your personal `~/.codex/config.toml` (on Windows, `%USERPROFILE%\.codex\config.toml`):
104
+
105
+ ```toml
106
+ [mcp_servers.remote_workspace]
107
+ command = "node"
108
+ 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"]
110
+ ```
111
+
112
+ 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).
113
+
114
+ ## File workflow
115
+
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
+ 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
+ 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.
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.
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 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
+
126
+ ## Boundaries
127
+
128
+ - 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`.
129
+ - Each read and upload is limited by `REMOTE_MAX_FILE_BYTES`. Reads stop when the limit is exceeded, even if the server reports an incorrect size. File data is hashed and transferred in chunks. The server rejects a transfer that ends before the file size reported by the directory listing.
130
+ - An SFTP connection or request that exceeds `SFTP_TIMEOUT_MS`, or a transfer that moves no data for that long, closes its connection. A large file that keeps transferring is not cut off. If a rename times out, inspect the remote target before retrying because the server may have completed the rename.
131
+ - Remote symlink detection depends on the server listing and cannot prevent a server-side path change between validation and transfer.
132
+ - The MCP tools exclude their reserved temporary and backup names. Configure access to these files separately if the remote directory is served over HTTP.
133
+ - On Unix-like systems, new downloads are created with owner-only permissions, and replacing an existing file preserves its read, write, and execute permission bits.
134
+ - Unexpected transport errors return only an error code to the MCP client, such as `550` or `ECONNREFUSED`. The full message goes to stderr, the client's server log, with the configured password and passphrase redacted.
135
+ - No remote credentials or project files are stored in this repository. Previews stream file contents to compute hashes. Downloads stream to a temporary file beside the local target before renaming it. Uploads stream to a temporary file beside the remote target and may briefly create a backup on FTP replacement. Cleanup is attempted after failure, but a connection loss can prevent it.
136
+
137
+ ## Development
138
+
139
+ ```sh
140
+ npm test
141
+ npm audit --omit=dev
142
+ ```
143
+
144
+ Tests cover path restrictions, FTP and SFTP transport behavior, upload previews, and legacy and current MCP stdio handshakes. The integration suite starts temporary loopback servers and checks downloads, verified replacements, and server identity validation through the stdio MCP tools. Run it with Python 3.14 and Node.js on your PATH:
145
+
146
+ ```sh
147
+ python -m pip install -r integration/requirements.txt
148
+ python integration/run.py
149
+ ```
150
+
151
+ To release, bump the version in `package.json` and `package-lock.json` through a pull request, then publish a GitHub release tagged `v<version>` on the merge commit. The `Publish` workflow checks that the tag matches `package.json`, runs the tests, and publishes to npm through trusted publishing, so no npm token is stored in the repository.
152
+
153
+ Test against your own server before relying on a production upload. Contributions are welcome under the MIT license.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jwjp/ftp-mcp",
3
- "version": "0.2.1",
3
+ "version": "0.3.1",
4
4
  "description": "A guarded FTP/SFTP MCP server for local AI coding workflows",
5
5
  "repository": {
6
6
  "type": "git",
package/src/config.js CHANGED
@@ -1,14 +1,32 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
- import { relativePath, UserError } from './paths.js';
3
+ import { relativePath, UserError, withinRoot } from './paths.js';
4
+
5
+ export const DEFAULT_SFTP_TIMEOUT_MS = 30_000;
6
+ export const DEFAULT_IDLE_TIMEOUT_MS = 30_000;
4
7
 
5
8
  export function loadConfig(env = process.env) {
9
+ // MCP clients often substitute an unset variable reference such as
10
+ // "${MY_REMOTE_HOST}" with an empty string, and a hand-edited value may be
11
+ // only spaces. Treat blank values as unset so they fall back to legacy names
12
+ // and defaults instead of overriding them. Other values keep their spaces,
13
+ // which a password may contain.
14
+ env = Object.fromEntries(Object.entries(env).filter(([, value]) => typeof value !== 'string' || value.trim() !== ''));
6
15
  const get = (name, legacy) => env[name] ?? env[legacy];
7
16
  const legacyProtocol = env.FTP_SECURE === 'false' ? 'ftp' : env.FTP_SECURE === 'implicit' ? 'ftps-implicit' : 'ftps';
8
17
  const protocol = env.REMOTE_PROTOCOL ?? legacyProtocol;
9
18
  if (!['ftp', 'ftps', 'ftps-implicit', 'sftp'].includes(protocol)) {
10
19
  throw new UserError('REMOTE_PROTOCOL must be ftp, ftps, ftps-implicit, or sftp.');
11
20
  }
21
+ const warnings = [];
22
+ // Older configurations relied on FTPS as the default. Keep that behavior,
23
+ // but say so: an SFTP or plain FTP server would otherwise fail confusingly.
24
+ if (env.REMOTE_PROTOCOL === undefined && env.FTP_SECURE === undefined) {
25
+ warnings.push('REMOTE_PROTOCOL is not set; using explicit FTPS (ftps). Set REMOTE_PROTOCOL to ftp, ftps, ftps-implicit, or sftp.');
26
+ }
27
+ if (protocol === 'ftp') {
28
+ warnings.push('plain FTP sends the password and files unencrypted. Use sftp or ftps if the server supports it.');
29
+ }
12
30
  const host = get('REMOTE_HOST', 'FTP_HOST');
13
31
  const user = get('REMOTE_USER', 'FTP_USER');
14
32
  const password = get('REMOTE_PASSWORD', 'FTP_PASS');
@@ -18,10 +36,11 @@ export function loadConfig(env = process.env) {
18
36
  if (!value) throw new UserError(`Missing ${name}.`);
19
37
  }
20
38
  if (/[\x00-\x1f\x7f]/u.test(host) || /[\x00-\x1f\x7f]/u.test(user)) throw new UserError('Invalid remote host or user.');
39
+ if (/[\s/@]/u.test(host)) throw new UserError('REMOTE_HOST must be a hostname or IP address, without a scheme, user, or path.');
21
40
  if (!root.startsWith('/') || root.includes('\\') || /[\x00-\x1f\x7f]/u.test(root)) throw new UserError('REMOTE_ROOT must be an absolute POSIX path.');
22
41
  for (const part of root.split('/').filter(Boolean)) relativePath(part);
23
- const localRoot = path.resolve(local);
24
- if (!fs.statSync(localRoot, { throwIfNoEntry: false })?.isDirectory()) throw new UserError('LOCAL_ROOT must exist and be a directory.');
42
+ if (!fs.statSync(local, { throwIfNoEntry: false })?.isDirectory()) throw new UserError('LOCAL_ROOT must exist and be a directory.');
43
+ const localRoot = fs.realpathSync.native(local);
25
44
 
26
45
  const defaultPort = protocol === 'sftp' ? 22 : protocol === 'ftps-implicit' ? 990 : 21;
27
46
  const port = Number(get('REMOTE_PORT', 'FTP_PORT') || defaultPort);
@@ -30,13 +49,24 @@ export function loadConfig(env = process.env) {
30
49
  for (const item of extra) relativePath(item);
31
50
  const maxBytes = Number(get('REMOTE_MAX_FILE_BYTES', 'FTP_MAX_FILE_BYTES') || 10 * 1024 * 1024);
32
51
  if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 100 * 1024 * 1024) throw new UserError('REMOTE_MAX_FILE_BYTES must be between 1 and 104857600.');
52
+ const idleTimeoutMs = Number(env.REMOTE_IDLE_TIMEOUT_MS || DEFAULT_IDLE_TIMEOUT_MS);
53
+ if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || idleTimeoutMs > 2_147_483_647) {
54
+ throw new UserError('REMOTE_IDLE_TIMEOUT_MS must be an integer between 0 and 2147483647.');
55
+ }
33
56
 
34
57
  let sftpPrivateKeyFile = null;
35
58
  let sftpHostKeySha256 = null;
59
+ let sftpTimeoutMs = DEFAULT_SFTP_TIMEOUT_MS;
36
60
  if (protocol === 'sftp') {
61
+ sftpTimeoutMs = Number(env.SFTP_TIMEOUT_MS || DEFAULT_SFTP_TIMEOUT_MS);
62
+ if (!Number.isSafeInteger(sftpTimeoutMs) || sftpTimeoutMs < 1 || sftpTimeoutMs > 2_147_483_647) {
63
+ throw new UserError('SFTP_TIMEOUT_MS must be an integer between 1 and 2147483647.');
64
+ }
37
65
  if (env.SFTP_PRIVATE_KEY_FILE) {
38
66
  sftpPrivateKeyFile = path.resolve(env.SFTP_PRIVATE_KEY_FILE);
39
67
  if (!fs.statSync(sftpPrivateKeyFile, { throwIfNoEntry: false })?.isFile()) throw new UserError('SFTP_PRIVATE_KEY_FILE must be an existing file.');
68
+ sftpPrivateKeyFile = fs.realpathSync.native(sftpPrivateKeyFile);
69
+ if (withinRoot(localRoot, sftpPrivateKeyFile)) throw new UserError('Keep SFTP_PRIVATE_KEY_FILE outside LOCAL_ROOT.');
40
70
  }
41
71
  if (!password && !sftpPrivateKeyFile) throw new UserError('Set REMOTE_PASSWORD or SFTP_PRIVATE_KEY_FILE for SFTP.');
42
72
  const fingerprint = env.SFTP_HOST_KEY_SHA256?.replace(/^SHA256:/u, '').replace(/=$/u, '');
@@ -44,13 +74,15 @@ export function loadConfig(env = process.env) {
44
74
  sftpHostKeySha256 = fingerprint;
45
75
  } else if (!password) {
46
76
  throw new UserError('Missing REMOTE_PASSWORD.');
77
+ } else if (/[\r\n\x00]/u.test(password)) {
78
+ throw new UserError('REMOTE_PASSWORD contains a character unsupported by FTP.');
47
79
  }
48
80
 
49
81
  return {
50
82
  protocol, host, user, password, port,
51
83
  secure: protocol === 'ftps' ? true : protocol === 'ftps-implicit' ? 'implicit' : false,
52
- remoteRoot: root, localRoot, extra, maxBytes,
84
+ remoteRoot: root, localRoot, extra, maxBytes, idleTimeoutMs,
53
85
  sftpPrivateKeyFile, sftpPassphrase: env.SFTP_PASSPHRASE,
54
- sftpHostKeySha256
86
+ sftpHostKeySha256, sftpTimeoutMs, warnings
55
87
  };
56
88
  }
package/src/paths.js CHANGED
@@ -1,11 +1,21 @@
1
1
  import fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
 
4
- const DEFAULT_EXCLUDES = ['.git', '.env', '.mcp.json', 'node_modules', 'vendor'];
4
+ // Version control, secrets, dependency trees, and agent or MCP configuration
5
+ // that a downloaded file could use to run commands on this machine.
6
+ const DEFAULT_EXCLUDES = [
7
+ '.git', '.env', 'node_modules', 'vendor',
8
+ '.ssh', '.netrc', '.git-credentials', '.htpasswd',
9
+ '.mcp.json', '.claude', '.codex'
10
+ ];
11
+ const TRANSFER_TEMP = /^\.mcp-(?:upload|backup|download)-[0-9a-f-]{36}\.tmp$/iu;
12
+
13
+ // Windows device names refer to devices, not files, with or without an extension.
14
+ const WINDOWS_DEVICE = /^(con|prn|aux|nul|conin\$|conout\$|com[0-9¹²³]|lpt[0-9¹²³])(\.|$)/iu;
5
15
 
6
16
  export class UserError extends Error {}
7
17
 
8
- export function relativePath(value, { allowRoot = false } = {}) {
18
+ export function relativePath(value, { allowRoot = false, platform = process.platform } = {}) {
9
19
  if (allowRoot && (value === '' || value === '.')) return '';
10
20
  if (typeof value !== 'string' || !value || value.startsWith('/') || value.includes('\\') || /[\x00-\x1f\x7f]/u.test(value)) {
11
21
  throw new UserError('Use a relative POSIX path without control characters.');
@@ -14,13 +24,21 @@ export function relativePath(value, { allowRoot = false } = {}) {
14
24
  if (parts.some(part => !part || part === '.' || part === '..' || part.trim() !== part)) {
15
25
  throw new UserError('Path contains an empty, dot, parent, or padded component.');
16
26
  }
27
+ // Windows resolves "name::$DATA" (alternate data streams) and "name." or
28
+ // "name " to "name", which would slip past the exclusion list.
29
+ if (parts.some(part => part.includes(':') || part.endsWith('.'))) {
30
+ throw new UserError('Path contains a colon or a trailing dot.');
31
+ }
32
+ if (platform === 'win32' && parts.some(part => WINDOWS_DEVICE.test(part))) {
33
+ throw new UserError('Path contains a reserved Windows device name.');
34
+ }
17
35
  return value;
18
36
  }
19
37
 
20
38
  export function excluded(value, extra = []) {
21
39
  const lower = value.toLowerCase();
22
40
  const parts = lower.split('/');
23
- if (parts.some(part => part === '.env' || part.startsWith('.env.'))) return true;
41
+ if (parts.some(part => part.startsWith('.env.') || TRANSFER_TEMP.test(part))) return true;
24
42
  return [...DEFAULT_EXCLUDES, ...extra].some(item => {
25
43
  const rule = item.toLowerCase();
26
44
  return rule.includes('/') ? lower === rule || lower.startsWith(`${rule}/`) : parts.includes(rule);
@@ -33,10 +51,17 @@ export function safePath(value, extra = [], options = {}) {
33
51
  return relative;
34
52
  }
35
53
 
36
- export async function localPath(root, relative) {
54
+ export function withinRoot(root, file) {
55
+ const relative = path.relative(root, file);
56
+ return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
57
+ }
58
+
59
+ export async function localPath(root, relative, extra = []) {
60
+ relative = safePath(relative, extra);
37
61
  const base = await fs.realpath(root);
38
62
  const parts = relative.split('/');
39
63
  let current = base;
64
+ let existing = base;
40
65
  for (const part of parts) {
41
66
  current = path.join(current, part);
42
67
  const stat = await fs.lstat(current).catch(error => {
@@ -44,7 +69,16 @@ export async function localPath(root, relative) {
44
69
  throw error;
45
70
  });
46
71
  if (stat?.isSymbolicLink()) throw new UserError('Local symlink paths are not allowed.');
72
+ if (stat) existing = current;
73
+ }
74
+ // The file system may map a different spelling, such as a Windows 8.3 short
75
+ // name (NODE_M~1), to an excluded entry. Check the name it actually uses.
76
+ if (existing !== base) {
77
+ const real = await fs.realpath(existing);
78
+ if (!withinRoot(base, real)) throw new UserError('Path escapes the local root.');
79
+ if (excluded(path.relative(base, real).split(path.sep).join('/'), extra)) {
80
+ throw new UserError('This path is excluded by the workspace policy.');
81
+ }
47
82
  }
48
- if (!current.startsWith(base + path.sep)) throw new UserError('Path escapes the local root.');
49
83
  return current;
50
84
  }