@jwjp/ftp-mcp 0.0.0-stage → 0.3.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/LICENSE ADDED
@@ -0,0 +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.
package/README.md CHANGED
@@ -1,3 +1,149 @@
1
- # Temporary Holding Version
1
+ # FTP Workspace MCP
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+ Or run it from a GitHub checkout:
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. An empty value counts as unset, so an unresolved `${NAME}` reference falls back to the former `FTP_*` name or the default instead of overriding it.
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 outside `LOCAL_ROOT`; use instead of a password |
44
+ | `SFTP_PASSPHRASE` | Optional passphrase for an encrypted SFTP private key |
45
+ | `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 |
46
+ | `REMOTE_EXCLUDE` | Optional comma-separated additional names or relative paths, such as `uploads,logs,cache` |
47
+ | `REMOTE_MAX_FILE_BYTES` | Optional per-file limit; default 10 MiB, maximum 100 MiB |
48
+ | `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) |
49
+
50
+ 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.
51
+
52
+ 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.
53
+
54
+ 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.
55
+
56
+ ### VS Code with GitHub Copilot
57
+
58
+ 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).
59
+
60
+ Example personal configuration for SFTP (replace the paths and set the referenced user environment variables):
61
+
62
+ ```json
63
+ {
64
+ "mcpServers": {
65
+ "remote-workspace": {
66
+ "type": "stdio",
67
+ "command": "node",
68
+ "args": ["/absolute/path/to/ftp-mcp/src/server.js"],
69
+ "env": {
70
+ "REMOTE_PROTOCOL": "sftp",
71
+ "REMOTE_HOST": "${MY_REMOTE_HOST}",
72
+ "REMOTE_USER": "${MY_REMOTE_USER}",
73
+ "REMOTE_PASSWORD": "${MY_REMOTE_PASSWORD}",
74
+ "REMOTE_ROOT": "/site",
75
+ "LOCAL_ROOT": "/absolute/path/to/my-project",
76
+ "SFTP_HOST_KEY_SHA256": "${MY_SFTP_HOST_KEY_SHA256}"
77
+ },
78
+ "tools": ["*"]
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ 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.
85
+
86
+ ### Claude Code
87
+
88
+ 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:
89
+
90
+ ```sh
91
+ claude mcp add --scope local --transport stdio remote-workspace -- node /absolute/path/to/ftp-mcp/src/server.js
92
+ claude mcp get remote-workspace
93
+ ```
94
+
95
+ 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).
96
+
97
+ 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.
98
+
99
+ ### Codex
100
+
101
+ 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`):
102
+
103
+ ```toml
104
+ [mcp_servers.remote_workspace]
105
+ command = "node"
106
+ args = ["C:/absolute/path/to/ftp-mcp/src/server.js"]
107
+ 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"]
108
+ ```
109
+
110
+ 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).
111
+
112
+ ## File workflow
113
+
114
+ 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.
115
+ 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`.
116
+ 3. Edit and test locally.
117
+ 4. `remote_preview_upload({"path":"src/example.php"})`. Review the path and both hashes. It returns an `uploadToken` when content differs.
118
+ 5. `remote_upload({"path":"src/example.php","uploadToken":"..."})` within ten minutes. A changed local or remote file invalidates the preview.
119
+
120
+ 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 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.
121
+
122
+ 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.
123
+
124
+ ## Boundaries
125
+
126
+ - 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`.
127
+ - 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.
128
+ - 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.
129
+ - Remote symlink detection depends on the server listing and cannot prevent a server-side path change between validation and transfer.
130
+ - The MCP tools exclude their reserved temporary and backup names. Configure access to these files separately if the remote directory is served over HTTP.
131
+ - 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.
132
+ - 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.
133
+ - 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.
134
+
135
+ ## Development
136
+
137
+ ```sh
138
+ npm test
139
+ npm audit --omit=dev
140
+ ```
141
+
142
+ 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:
143
+
144
+ ```sh
145
+ python -m pip install -r integration/requirements.txt
146
+ python integration/run.py
147
+ ```
148
+
149
+ 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,40 @@
1
1
  {
2
2
  "name": "@jwjp/ftp-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.0",
4
+ "description": "A guarded FTP/SFTP MCP server for local AI coding workflows",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/jwjp/ftp-mcp.git"
8
+ },
9
+ "homepage": "https://github.com/jwjp/ftp-mcp#readme",
10
+ "bugs": "https://github.com/jwjp/ftp-mcp/issues",
11
+ "type": "module",
12
+ "bin": {
13
+ "ftp-workspace-mcp": "src/server.js"
14
+ },
15
+ "files": [
16
+ "src/",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "start": "node src/server.js",
22
+ "test": "node --test"
23
+ },
24
+ "engines": {
25
+ "node": ">=22.12"
26
+ },
27
+ "dependencies": {
28
+ "@modelcontextprotocol/server": "^2.4.0",
29
+ "basic-ftp": "^6.2.6",
30
+ "ssh2-sftp-client": "^13.0.1",
31
+ "zod": "^4.6.7"
32
+ },
33
+ "license": "MIT",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "devDependencies": {
38
+ "@modelcontextprotocol/client": "^2.4.0"
39
+ }
40
+ }
package/src/config.js ADDED
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
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;
7
+
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. Treat empty values as unset so
11
+ // they fall back to legacy names and defaults instead of overriding them.
12
+ env = Object.fromEntries(Object.entries(env).filter(([, value]) => value !== ''));
13
+ const get = (name, legacy) => env[name] ?? env[legacy];
14
+ const legacyProtocol = env.FTP_SECURE === 'false' ? 'ftp' : env.FTP_SECURE === 'implicit' ? 'ftps-implicit' : 'ftps';
15
+ const protocol = env.REMOTE_PROTOCOL ?? legacyProtocol;
16
+ if (!['ftp', 'ftps', 'ftps-implicit', 'sftp'].includes(protocol)) {
17
+ throw new UserError('REMOTE_PROTOCOL must be ftp, ftps, ftps-implicit, or sftp.');
18
+ }
19
+ const warnings = [];
20
+ // Older configurations relied on FTPS as the default. Keep that behavior,
21
+ // but say so: an SFTP or plain FTP server would otherwise fail confusingly.
22
+ if (env.REMOTE_PROTOCOL === undefined && env.FTP_SECURE === undefined) {
23
+ warnings.push('REMOTE_PROTOCOL is not set; using explicit FTPS (ftps). Set REMOTE_PROTOCOL to ftp, ftps, ftps-implicit, or sftp.');
24
+ }
25
+ if (protocol === 'ftp') {
26
+ warnings.push('plain FTP sends the password and files unencrypted. Use sftp or ftps if the server supports it.');
27
+ }
28
+ const host = get('REMOTE_HOST', 'FTP_HOST');
29
+ const user = get('REMOTE_USER', 'FTP_USER');
30
+ const password = get('REMOTE_PASSWORD', 'FTP_PASS');
31
+ const root = get('REMOTE_ROOT', 'FTP_REMOTE_ROOT');
32
+ const local = get('LOCAL_ROOT', 'FTP_LOCAL_ROOT');
33
+ for (const [name, value] of [['REMOTE_HOST', host], ['REMOTE_USER', user], ['REMOTE_ROOT', root], ['LOCAL_ROOT', local]]) {
34
+ if (!value) throw new UserError(`Missing ${name}.`);
35
+ }
36
+ if (/[\x00-\x1f\x7f]/u.test(host) || /[\x00-\x1f\x7f]/u.test(user)) throw new UserError('Invalid remote host or user.');
37
+ if (/[\s/@]/u.test(host)) throw new UserError('REMOTE_HOST must be a hostname or IP address, without a scheme, user, or path.');
38
+ if (!root.startsWith('/') || root.includes('\\') || /[\x00-\x1f\x7f]/u.test(root)) throw new UserError('REMOTE_ROOT must be an absolute POSIX path.');
39
+ for (const part of root.split('/').filter(Boolean)) relativePath(part);
40
+ if (!fs.statSync(local, { throwIfNoEntry: false })?.isDirectory()) throw new UserError('LOCAL_ROOT must exist and be a directory.');
41
+ const localRoot = fs.realpathSync.native(local);
42
+
43
+ const defaultPort = protocol === 'sftp' ? 22 : protocol === 'ftps-implicit' ? 990 : 21;
44
+ const port = Number(get('REMOTE_PORT', 'FTP_PORT') || defaultPort);
45
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new UserError('REMOTE_PORT must be 1–65535.');
46
+ const extra = (get('REMOTE_EXCLUDE', 'FTP_EXCLUDE') || '').split(',').map(s => s.trim()).filter(Boolean);
47
+ for (const item of extra) relativePath(item);
48
+ const maxBytes = Number(get('REMOTE_MAX_FILE_BYTES', 'FTP_MAX_FILE_BYTES') || 10 * 1024 * 1024);
49
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 100 * 1024 * 1024) throw new UserError('REMOTE_MAX_FILE_BYTES must be between 1 and 104857600.');
50
+ const idleTimeoutMs = Number(env.REMOTE_IDLE_TIMEOUT_MS || DEFAULT_IDLE_TIMEOUT_MS);
51
+ if (!Number.isSafeInteger(idleTimeoutMs) || idleTimeoutMs < 0 || idleTimeoutMs > 2_147_483_647) {
52
+ throw new UserError('REMOTE_IDLE_TIMEOUT_MS must be an integer between 0 and 2147483647.');
53
+ }
54
+
55
+ let sftpPrivateKeyFile = null;
56
+ let sftpHostKeySha256 = null;
57
+ let sftpTimeoutMs = DEFAULT_SFTP_TIMEOUT_MS;
58
+ if (protocol === 'sftp') {
59
+ sftpTimeoutMs = Number(env.SFTP_TIMEOUT_MS || DEFAULT_SFTP_TIMEOUT_MS);
60
+ if (!Number.isSafeInteger(sftpTimeoutMs) || sftpTimeoutMs < 1 || sftpTimeoutMs > 2_147_483_647) {
61
+ throw new UserError('SFTP_TIMEOUT_MS must be an integer between 1 and 2147483647.');
62
+ }
63
+ if (env.SFTP_PRIVATE_KEY_FILE) {
64
+ sftpPrivateKeyFile = path.resolve(env.SFTP_PRIVATE_KEY_FILE);
65
+ if (!fs.statSync(sftpPrivateKeyFile, { throwIfNoEntry: false })?.isFile()) throw new UserError('SFTP_PRIVATE_KEY_FILE must be an existing file.');
66
+ sftpPrivateKeyFile = fs.realpathSync.native(sftpPrivateKeyFile);
67
+ if (withinRoot(localRoot, sftpPrivateKeyFile)) throw new UserError('Keep SFTP_PRIVATE_KEY_FILE outside LOCAL_ROOT.');
68
+ }
69
+ if (!password && !sftpPrivateKeyFile) throw new UserError('Set REMOTE_PASSWORD or SFTP_PRIVATE_KEY_FILE for SFTP.');
70
+ const fingerprint = env.SFTP_HOST_KEY_SHA256?.replace(/^SHA256:/u, '').replace(/=$/u, '');
71
+ if (!fingerprint || !/^[A-Za-z0-9+/]{43}$/u.test(fingerprint)) throw new UserError('Set SFTP_HOST_KEY_SHA256 to the trusted SSH host key SHA-256 fingerprint.');
72
+ sftpHostKeySha256 = fingerprint;
73
+ } else if (!password) {
74
+ throw new UserError('Missing REMOTE_PASSWORD.');
75
+ } else if (/[\r\n\x00]/u.test(password)) {
76
+ throw new UserError('REMOTE_PASSWORD contains a character unsupported by FTP.');
77
+ }
78
+
79
+ return {
80
+ protocol, host, user, password, port,
81
+ secure: protocol === 'ftps' ? true : protocol === 'ftps-implicit' ? 'implicit' : false,
82
+ remoteRoot: root, localRoot, extra, maxBytes, idleTimeoutMs,
83
+ sftpPrivateKeyFile, sftpPassphrase: env.SFTP_PASSPHRASE,
84
+ sftpHostKeySha256, sftpTimeoutMs, warnings
85
+ };
86
+ }
package/src/paths.js ADDED
@@ -0,0 +1,84 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+
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;
15
+
16
+ export class UserError extends Error {}
17
+
18
+ export function relativePath(value, { allowRoot = false, platform = process.platform } = {}) {
19
+ if (allowRoot && (value === '' || value === '.')) return '';
20
+ if (typeof value !== 'string' || !value || value.startsWith('/') || value.includes('\\') || /[\x00-\x1f\x7f]/u.test(value)) {
21
+ throw new UserError('Use a relative POSIX path without control characters.');
22
+ }
23
+ const parts = value.split('/');
24
+ if (parts.some(part => !part || part === '.' || part === '..' || part.trim() !== part)) {
25
+ throw new UserError('Path contains an empty, dot, parent, or padded component.');
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
+ }
35
+ return value;
36
+ }
37
+
38
+ export function excluded(value, extra = []) {
39
+ const lower = value.toLowerCase();
40
+ const parts = lower.split('/');
41
+ if (parts.some(part => part.startsWith('.env.') || TRANSFER_TEMP.test(part))) return true;
42
+ return [...DEFAULT_EXCLUDES, ...extra].some(item => {
43
+ const rule = item.toLowerCase();
44
+ return rule.includes('/') ? lower === rule || lower.startsWith(`${rule}/`) : parts.includes(rule);
45
+ });
46
+ }
47
+
48
+ export function safePath(value, extra = [], options = {}) {
49
+ const relative = relativePath(value, options);
50
+ if (relative && excluded(relative, extra)) throw new UserError('This path is excluded by the workspace policy.');
51
+ return relative;
52
+ }
53
+
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);
61
+ const base = await fs.realpath(root);
62
+ const parts = relative.split('/');
63
+ let current = base;
64
+ let existing = base;
65
+ for (const part of parts) {
66
+ current = path.join(current, part);
67
+ const stat = await fs.lstat(current).catch(error => {
68
+ if (error.code === 'ENOENT') return null;
69
+ throw error;
70
+ });
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
+ }
82
+ }
83
+ return current;
84
+ }
package/src/server.js ADDED
@@ -0,0 +1,79 @@
1
+ #!/usr/bin/env node
2
+ import { McpServer } from '@modelcontextprotocol/server';
3
+ import { serveStdio } from '@modelcontextprotocol/server/stdio';
4
+ import { existsSync, readFileSync, realpathSync } from 'node:fs';
5
+ import * as z from 'zod/v4';
6
+ import { loadConfig } from './config.js';
7
+ import { UserError } from './paths.js';
8
+ import { FtpWorkspace, LIST_LIMIT } from './workspace.js';
9
+
10
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
11
+ const relativeInput = z.string().max(4096);
12
+
13
+ function result(value) { return { content: [{ type: 'text', text: JSON.stringify(value) }] }; }
14
+
15
+ // Error codes such as 550 or ECONNREFUSED help the caller without exposing
16
+ // server text, which may echo paths or account details.
17
+ export function failureMessage(error) {
18
+ const code = typeof error?.code === 'number' || /^[A-Z][A-Z0-9_]{1,31}$/u.test(error?.code ?? '') ? ` (${error.code})` : '';
19
+ return `Remote operation failed${code}. Check connectivity and server settings.`;
20
+ }
21
+
22
+ export function redact(text, secrets) {
23
+ return secrets.filter(Boolean).reduce((value, secret) => value.split(secret).join('[redacted]'), String(text));
24
+ }
25
+
26
+ function tool(name, workspace, fn) {
27
+ return async args => {
28
+ try { return result(await fn(args)); }
29
+ catch (error) {
30
+ if (error instanceof UserError) return { content: [{ type: 'text', text: error.message }], isError: true };
31
+ // stderr is the MCP client's log, not the conversation.
32
+ const { password, sftpPassphrase } = workspace.config ?? {};
33
+ console.error(`[ftp-workspace-mcp] ${name}: ${redact(error?.message ?? error, [password, sftpPassphrase])}`);
34
+ return { content: [{ type: 'text', text: failureMessage(error) }], isError: true };
35
+ }
36
+ };
37
+ }
38
+
39
+ export function createServer(workspace) {
40
+ const server = new McpServer({ name: 'ftp-workspace-mcp', version }, {
41
+ 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.'
42
+ });
43
+ server.registerTool('remote_list', {
44
+ 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.`,
45
+ inputSchema: z.object({ path: relativeInput.default(''), cursor: relativeInput.optional() }),
46
+ annotations: { readOnlyHint: true }
47
+ }, tool('remote_list', workspace, ({ path, cursor }) => workspace.list(path, cursor)));
48
+ server.registerTool('remote_download', {
49
+ description: 'Download one remote file into the configured local root. Existing differing files require their current SHA-256 as expectedLocalSha256.',
50
+ inputSchema: z.object({ path: relativeInput, expectedLocalSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }),
51
+ annotations: { readOnlyHint: false }
52
+ }, tool('remote_download', workspace, ({ path, expectedLocalSha256 }) => workspace.download(path, expectedLocalSha256)));
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.',
55
+ inputSchema: z.object({ path: relativeInput }),
56
+ annotations: { readOnlyHint: true }
57
+ }, tool('remote_preview_upload', workspace, ({ path }) => workspace.previewUpload(path)));
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.',
60
+ inputSchema: z.object({ path: relativeInput, uploadToken: z.string().uuid() }),
61
+ annotations: { readOnlyHint: false, destructiveHint: true }
62
+ }, tool('remote_upload', workspace, ({ path, uploadToken }) => workspace.upload(path, uploadToken)));
63
+ return server;
64
+ }
65
+
66
+ if (process.argv[1] && existsSync(process.argv[1]) && realpathSync.native(import.meta.filename) === realpathSync.native(process.argv[1])) {
67
+ try {
68
+ const config = loadConfig();
69
+ for (const warning of config.warnings) console.error(`[ftp-workspace-mcp] Warning: ${warning}`);
70
+ const workspace = new FtpWorkspace(config);
71
+ // The client closes stdin to end the session. Close the idle remote
72
+ // connection then, or its socket would keep the process running.
73
+ for (const event of ['end', 'close']) process.stdin.once(event, () => { workspace.close(); });
74
+ await serveStdio(() => createServer(workspace));
75
+ } catch (error) {
76
+ console.error(error instanceof UserError ? error.message : 'Failed to start remote MCP server.');
77
+ process.exitCode = 1;
78
+ }
79
+ }
@@ -0,0 +1,198 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import { isIP } from 'node:net';
4
+ import path from 'node:path';
5
+ import { Readable, Transform } from 'node:stream';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { Client as FtpClient, FileType } from 'basic-ftp';
8
+ import SftpClient from 'ssh2-sftp-client';
9
+ import { DEFAULT_SFTP_TIMEOUT_MS } from './config.js';
10
+ import { UserError } from './paths.js';
11
+
12
+ export class FtpTransport {
13
+ constructor(config, client = new FtpClient(30_000)) {
14
+ this.config = config;
15
+ this.client = client;
16
+ }
17
+ async access() {
18
+ const { host, port, user, password, secure } = this.config;
19
+ await this.client.access({
20
+ host, port, user, password, secure,
21
+ secureOptions: secure ? { rejectUnauthorized: true, ...(isIP(host) ? {} : { servername: host }) } : undefined
22
+ });
23
+ }
24
+ async cd(root) { await this.client.cd(root); }
25
+ async ping() {
26
+ if (this.client.closed) throw new Error('FTP connection is closed.');
27
+ await this.client.send('NOOP');
28
+ }
29
+ async list(relative) { return this.client.list(relative); }
30
+ async downloadTo(local, relative) { await this.client.downloadTo(local, relative); }
31
+ async uploadFrom(source, relative) { await this.client.uploadFrom(source, relative); }
32
+ async rename(from, to, replace) {
33
+ if (!replace) {
34
+ await this.client.rename(from, to);
35
+ return null;
36
+ }
37
+ // FTP RNTO often refuses an existing destination. Keep the original under
38
+ // a backup name until the staged file takes its place.
39
+ const parent = path.posix.dirname(to);
40
+ const backup = path.posix.join(parent === '.' ? '' : parent, `.mcp-backup-${randomUUID()}.tmp`);
41
+ try { await this.client.rename(to, backup); }
42
+ catch (error) {
43
+ // A lost reply can leave the original under its backup name.
44
+ throw new UserError(`Could not confirm the FTP backup move; check ${to} and ${backup} before retrying.`, { cause: error });
45
+ }
46
+ try {
47
+ await this.client.rename(from, to);
48
+ } catch (error) {
49
+ let targetPresent;
50
+ try {
51
+ const destination = path.posix.basename(to).toLowerCase();
52
+ const entries = await this.client.list(parent);
53
+ // The rename reply may have been lost, or another writer may have
54
+ // created the target. Preserve both files if the target is present.
55
+ targetPresent = entries.some(entry => entry.name.toLowerCase() === destination);
56
+ if (!targetPresent) await this.client.rename(backup, to);
57
+ } catch {
58
+ throw new UserError(`Upload replacement failed; inspect ${to} and ${backup} before retrying.`, { cause: error });
59
+ }
60
+ if (targetPresent) {
61
+ throw new UserError(`Upload replacement could not be confirmed; inspect ${to} and ${backup} before retrying.`, { cause: error });
62
+ }
63
+ throw error;
64
+ }
65
+ return backup;
66
+ }
67
+ async remove(relative) { await this.client.remove(relative); }
68
+ async close() { this.client.close(); }
69
+ }
70
+
71
+ export class SftpTransport {
72
+ #timeoutError = null;
73
+
74
+ constructor(config, client = new SftpClient('ftp-workspace-mcp', { error() {}, end() {}, close() {} })) {
75
+ this.config = config;
76
+ this.client = client;
77
+ this.root = null;
78
+ }
79
+
80
+ // The timeout measures inactivity. A transfer passes `progress` a callback
81
+ // to call for each chunk, so a large file that keeps moving is not cut off
82
+ // while a stalled request still is.
83
+ async #run(operation, action) {
84
+ if (this.#timeoutError) throw this.#timeoutError;
85
+ const timeoutMs = this.config.sftpTimeoutMs ?? DEFAULT_SFTP_TIMEOUT_MS;
86
+ let timer;
87
+ let settled = false;
88
+ let expire;
89
+ const deadline = new Promise((_, reject) => { expire = reject; });
90
+ const progress = () => {
91
+ if (settled) return;
92
+ clearTimeout(timer);
93
+ timer = setTimeout(() => {
94
+ this.#timeoutError = new UserError(`SFTP ${operation} timed out after ${timeoutMs} ms without progress. The connection was closed.`);
95
+ expire(this.#timeoutError);
96
+ // ssh2-sftp-client.end() waits for the close event. Destroy the
97
+ // underlying SSH connection so a stalled request cannot keep it open.
98
+ this.client.client.destroy();
99
+ }, timeoutMs);
100
+ };
101
+ progress();
102
+ try { return await Promise.race([deadline, action(progress)]); }
103
+ finally {
104
+ settled = true;
105
+ clearTimeout(timer);
106
+ }
107
+ }
108
+
109
+ async access() {
110
+ const config = {
111
+ host: this.config.host, port: this.config.port, username: this.config.user,
112
+ readyTimeout: this.config.sftpTimeoutMs ?? DEFAULT_SFTP_TIMEOUT_MS,
113
+ hostVerifier: key => createHash('sha256').update(key).digest('base64').replace(/=+$/u, '') === this.config.sftpHostKeySha256
114
+ };
115
+ if (this.config.password) config.password = this.config.password;
116
+ if (this.config.sftpPrivateKeyFile) {
117
+ config.privateKey = await fs.readFile(this.config.sftpPrivateKeyFile);
118
+ if (this.config.sftpPassphrase) config.passphrase = this.config.sftpPassphrase;
119
+ }
120
+ await this.#run('connection', () => this.client.connect(config));
121
+ }
122
+ async cd(root) {
123
+ if (await this.#run('root check', () => this.client.exists(root)) !== 'd') throw new UserError('Remote root is not a directory.');
124
+ this.root = root;
125
+ }
126
+ async ping() { await this.#run('keepalive check', () => this.client.cwd()); }
127
+ remote(relative) {
128
+ if (!this.root) throw new Error('SFTP root is not set.');
129
+ return path.posix.join(this.root, relative);
130
+ }
131
+ async list(relative) {
132
+ const entries = await this.#run('listing', () => this.client.list(this.remote(relative)));
133
+ return entries.map(item => ({
134
+ name: item.name,
135
+ type: item.type === 'd' ? FileType.Directory : item.type === '-' ? FileType.File : FileType.SymbolicLink,
136
+ size: item.size,
137
+ modifiedAt: item.modifyTime ? new Date(item.modifyTime) : undefined
138
+ }));
139
+ }
140
+ async downloadTo(local, relative) {
141
+ let counted;
142
+ try {
143
+ await this.#run('download', async progress => {
144
+ counted = new Transform({ transform(chunk, _encoding, callback) { progress(); callback(null, chunk); } });
145
+ const delivered = pipeline(counted, local);
146
+ const received = Promise.resolve().then(() => this.client.get(this.remote(relative), counted)).catch(error => {
147
+ counted.destroy(error);
148
+ throw local.errored ?? error;
149
+ });
150
+ await Promise.all([delivered, received]);
151
+ });
152
+ } finally {
153
+ counted?.destroy();
154
+ }
155
+ }
156
+ async uploadFrom(source, relative) {
157
+ let counted;
158
+ try {
159
+ await this.#run('upload', progress => {
160
+ counted = Readable.from((async function* () {
161
+ for await (const chunk of source) {
162
+ progress();
163
+ yield chunk;
164
+ }
165
+ })(), { objectMode: false });
166
+ return this.client.put(counted, this.remote(relative));
167
+ });
168
+ } catch (error) {
169
+ throw source.errored ?? error;
170
+ } finally {
171
+ counted?.destroy();
172
+ }
173
+ }
174
+ async rename(from, to, replace) {
175
+ const source = this.remote(from);
176
+ const target = this.remote(to);
177
+ try {
178
+ await this.#run('rename', () => replace ? this.client.posixRename(source, target) : this.client.rename(source, target));
179
+ } catch (error) {
180
+ if (error === this.#timeoutError) {
181
+ throw new UserError(`${error.message} Inspect ${to} before retrying because the rename may have completed.`, { cause: error });
182
+ }
183
+ if (replace && (error?.code === 8 || error?.message === 'Server does not support this extended request')) {
184
+ throw new UserError('SFTP server lacks posix-rename@openssh.com support required to replace an existing file.');
185
+ }
186
+ throw error;
187
+ }
188
+ return null;
189
+ }
190
+ async remove(relative) { await this.#run('cleanup', () => this.client.delete(this.remote(relative), true)); }
191
+ async close() {
192
+ if (!this.#timeoutError) await this.#run('disconnect', () => this.client.end());
193
+ }
194
+ }
195
+
196
+ export function createTransport(config) {
197
+ return config.protocol === 'sftp' ? new SftpTransport(config) : new FtpTransport(config);
198
+ }
@@ -0,0 +1,362 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { Readable, Writable } from 'node:stream';
5
+ import { FileType } from 'basic-ftp';
6
+ import { DEFAULT_IDLE_TIMEOUT_MS } from './config.js';
7
+ import { localPath, safePath, UserError } from './paths.js';
8
+ import { createTransport } from './transports.js';
9
+
10
+ const CHUNK_BYTES = 64 * 1024;
11
+ const LOCAL_HASH_CHUNK_BYTES = 1024 * 1024;
12
+ export const LIST_LIMIT = 200;
13
+
14
+ // Closing a connection cannot undo a completed transfer. Do not turn a
15
+ // successful upload into a failure that prompts an unsafe retry.
16
+ async function closeQuietly(client) {
17
+ try { await client.close(); }
18
+ catch { /* The operation result is more useful than a close error. */ }
19
+ }
20
+
21
+ // FileHandle.write() may write fewer bytes than asked; finish the chunk.
22
+ async function writeAll(handle, chunk) {
23
+ for (let offset = 0; offset < chunk.length;) {
24
+ const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset);
25
+ offset += bytesWritten;
26
+ }
27
+ }
28
+
29
+ export class FtpWorkspace {
30
+ #clientQueue = Promise.resolve();
31
+ #idle = null;
32
+ #closed = false;
33
+
34
+ constructor(config, clientFactory = () => createTransport(config)) {
35
+ this.config = config;
36
+ this.clientFactory = clientFactory;
37
+ this.previews = new Map();
38
+ this.pendingWrite = Promise.resolve();
39
+ }
40
+
41
+ #withWrite(action) {
42
+ const operation = this.pendingWrite.then(action);
43
+ this.pendingWrite = operation.catch(() => {});
44
+ return operation;
45
+ }
46
+
47
+ // One remote connection serves one operation at a time: an FTP control
48
+ // connection cannot run two commands at once, and a shared SFTP session
49
+ // would interleave a listing with an upload's verification.
50
+ withClient(action) {
51
+ const operation = this.#clientQueue.then(() => this.#useClient(action));
52
+ this.#clientQueue = operation.catch(() => {});
53
+ return operation;
54
+ }
55
+
56
+ async #useClient(action) {
57
+ const client = await this.#acquire();
58
+ let result;
59
+ try {
60
+ result = await action(client);
61
+ } catch (error) {
62
+ // A failed operation can leave a transfer half done or the connection
63
+ // in an unknown state. Never hand that connection to the next caller.
64
+ await closeQuietly(client);
65
+ throw error;
66
+ }
67
+ await this.#release(client);
68
+ return result;
69
+ }
70
+
71
+ async #acquire() {
72
+ const idle = this.#idle;
73
+ this.#idle = null;
74
+ if (idle) {
75
+ clearTimeout(idle.timer);
76
+ // The server may have closed an idle connection. Check before reuse so
77
+ // the caller's operation does not fail on a stale connection.
78
+ try {
79
+ await idle.client.ping();
80
+ return idle.client;
81
+ } catch {
82
+ await closeQuietly(idle.client);
83
+ }
84
+ }
85
+ const client = this.clientFactory();
86
+ try {
87
+ await client.access();
88
+ await client.cd(this.config.remoteRoot);
89
+ } catch (error) {
90
+ await closeQuietly(client);
91
+ throw error;
92
+ }
93
+ return client;
94
+ }
95
+
96
+ async #release(client) {
97
+ const idleMs = this.config.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
98
+ if (this.#closed || idleMs === 0) return closeQuietly(client);
99
+ const timer = setTimeout(() => {
100
+ if (this.#idle?.client !== client) return;
101
+ this.#idle = null;
102
+ closeQuietly(client);
103
+ }, idleMs);
104
+ // An idle connection must not keep the process alive on its own timer.
105
+ timer.unref();
106
+ this.#idle = { client, timer };
107
+ }
108
+
109
+ // Close the idle connection and stop keeping new ones. An operation in
110
+ // progress finishes and then closes its connection.
111
+ async close() {
112
+ this.#closed = true;
113
+ const idle = this.#idle;
114
+ this.#idle = null;
115
+ if (idle) {
116
+ clearTimeout(idle.timer);
117
+ await closeQuietly(idle.client);
118
+ }
119
+ }
120
+
121
+ async entry(client, relative) {
122
+ const parts = relative.split('/');
123
+ for (let i = 0; i < parts.length; i++) {
124
+ const parent = parts.slice(0, i).join('/') || '.';
125
+ const entries = await client.list(parent);
126
+ const found = entries.find(item => item.name === parts[i]);
127
+ if (!found) {
128
+ if (i === parts.length - 1) return null;
129
+ throw new UserError('Remote parent directory does not exist.');
130
+ }
131
+ if (found.type === FileType.SymbolicLink) throw new UserError('Remote symlink paths are not allowed.');
132
+ if (i < parts.length - 1 && found.type !== FileType.Directory) throw new UserError('Remote parent is not a directory.');
133
+ if (i === parts.length - 1) return found;
134
+ }
135
+ }
136
+
137
+ async list(relative = '', cursor = '') {
138
+ relative = safePath(relative, this.config.extra, { allowRoot: true });
139
+ return this.withClient(async client => {
140
+ if (relative) {
141
+ const entry = await this.entry(client, relative);
142
+ if (!entry || entry.type !== FileType.Directory) throw new UserError('Remote directory does not exist.');
143
+ }
144
+ const allowed = (await client.list(relative || '.'))
145
+ .filter(item => item.name > cursor && !item.name.includes('/') && !safeExcluded(relative, item.name, this.config.extra) && item.type !== FileType.SymbolicLink)
146
+ .sort((a, b) => a.name < b.name ? -1 : Number(a.name > b.name));
147
+ const page = allowed.slice(0, LIST_LIMIT);
148
+ const truncated = allowed.length > LIST_LIMIT;
149
+ return {
150
+ entries: page.map(item => ({ name: item.name, type: item.type === FileType.Directory ? 'directory' : 'file', size: item.size, modifiedAt: item.modifiedAt?.toISOString() ?? null })),
151
+ truncated,
152
+ nextCursor: truncated ? page.at(-1).name : null
153
+ };
154
+ });
155
+ }
156
+
157
+ async #remoteEntry(client, relative) {
158
+ const entry = await this.entry(client, relative);
159
+ if (!entry) return null;
160
+ if (entry.type !== FileType.File) throw new UserError('Remote path is not a regular file.');
161
+ if (entry.size > this.config.maxBytes) throw new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.');
162
+ return entry;
163
+ }
164
+
165
+ async #readRemote(client, relative, entry, destination) {
166
+ const hash = createHash('sha256');
167
+ let bytes = 0;
168
+ const limit = this.config.maxBytes;
169
+ const sink = new Writable({
170
+ write(chunk, _encoding, callback) {
171
+ bytes += chunk.length;
172
+ if (bytes > limit) return callback(new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.'));
173
+ hash.update(chunk);
174
+ if (destination) writeAll(destination, chunk).then(() => callback(), callback);
175
+ else callback();
176
+ }
177
+ });
178
+ try { await client.downloadTo(sink, relative); }
179
+ finally { sink.destroy(); }
180
+ if (Number.isSafeInteger(entry.size) && bytes < entry.size) {
181
+ throw new UserError('Remote transfer ended before the listed file size; inspect it before retrying.');
182
+ }
183
+ return { sha256: hash.digest('hex'), bytes };
184
+ }
185
+
186
+ async readRemote(client, relative) {
187
+ const entry = await this.#remoteEntry(client, relative);
188
+ return entry ? this.#readRemote(client, relative, entry) : null;
189
+ }
190
+
191
+ async #openLocal(relative) {
192
+ const file = await localPath(this.config.localRoot, relative, this.config.extra);
193
+ const stat = await fs.stat(file).catch(error => {
194
+ if (error.code === 'ENOENT') return null;
195
+ throw error;
196
+ });
197
+ if (!stat) return { file, handle: null };
198
+ if (!stat.isFile()) throw new UserError('Local path is not a regular file.');
199
+ if (stat.size > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
200
+ return { file, handle: await fs.open(file, 'r'), mode: stat.mode & 0o777 };
201
+ }
202
+
203
+ async *#localChunks(handle, { reuseBuffer = false } = {}) {
204
+ let remaining = this.config.maxBytes;
205
+ const chunkBytes = reuseBuffer ? LOCAL_HASH_CHUNK_BYTES : CHUNK_BYTES;
206
+ const scratch = reuseBuffer ? Buffer.allocUnsafe(Math.min(chunkBytes, remaining + 1)) : null;
207
+ for (;;) {
208
+ const length = Math.min(chunkBytes, remaining + 1);
209
+ const chunk = scratch ?? Buffer.allocUnsafe(length);
210
+ const { bytesRead } = await handle.read(chunk, 0, length);
211
+ if (bytesRead === 0) return;
212
+ if (bytesRead > remaining) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
213
+ remaining -= bytesRead;
214
+ yield chunk.subarray(0, bytesRead);
215
+ }
216
+ }
217
+
218
+ async localFile(relative) {
219
+ const { file, handle, mode } = await this.#openLocal(relative);
220
+ if (!handle) return { file, sha256: null };
221
+ const hash = createHash('sha256');
222
+ let bytes = 0;
223
+ try {
224
+ for await (const chunk of this.#localChunks(handle, { reuseBuffer: true })) {
225
+ hash.update(chunk);
226
+ bytes += chunk.length;
227
+ }
228
+ } finally {
229
+ await handle.close();
230
+ }
231
+ return { file, sha256: hash.digest('hex'), bytes, mode };
232
+ }
233
+
234
+ async download(relative, expectedLocalSha256) {
235
+ relative = safePath(relative, this.config.extra);
236
+ return this.#withWrite(() => this.withClient(async client => {
237
+ const entry = await this.#remoteEntry(client, relative);
238
+ if (!entry) throw new UserError('Remote file does not exist.');
239
+ const local = await this.localFile(relative);
240
+ if (local.sha256 !== null && expectedLocalSha256 !== local.sha256) {
241
+ const remote = await this.#readRemote(client, relative, entry);
242
+ const latest = await this.localFile(relative);
243
+ if (latest.sha256 === remote.sha256) return { path: relative, status: 'unchanged', ...remote };
244
+ if (latest.sha256 === null) throw new UserError('Local file changed during download; retry after reviewing it.');
245
+ throw new UserError(`Local file differs. Its SHA-256 is ${latest.sha256}; supply expectedLocalSha256 to replace it.`);
246
+ }
247
+ await fs.mkdir(path.dirname(local.file), { recursive: true });
248
+ await localPath(this.config.localRoot, relative, this.config.extra);
249
+ const temp = path.join(path.dirname(local.file), `.mcp-download-${randomUUID()}.tmp`);
250
+ const handle = await fs.open(temp, 'wx', 0o600);
251
+ let unchanged;
252
+ try {
253
+ let remote;
254
+ try { remote = await this.#readRemote(client, relative, entry, handle); }
255
+ finally { await handle.close(); }
256
+ const latest = await this.localFile(relative);
257
+ if (latest.sha256 === remote.sha256) {
258
+ unchanged = { path: relative, status: 'unchanged', ...remote };
259
+ } else {
260
+ if (latest.sha256 !== local.sha256) {
261
+ throw new UserError('Local file changed during download; retry after reviewing it.');
262
+ }
263
+ if (latest.mode !== undefined && process.platform !== 'win32') await fs.chmod(temp, latest.mode);
264
+ await fs.rename(temp, local.file);
265
+ return { path: relative, status: 'downloaded', ...remote };
266
+ }
267
+ } catch (error) {
268
+ try { await fs.rm(temp, { force: true }); }
269
+ catch { throw new UserError(`Download failed and temporary local file may remain at ${path.basename(temp)}.`); }
270
+ throw error;
271
+ }
272
+ // The local file already matches. A leftover copy does not change that
273
+ // result, so report it instead of failing the call.
274
+ try { await fs.rm(temp, { force: true }); }
275
+ catch { return { ...unchanged, warning: `Temporary local file may remain at ${path.basename(temp)}; remove it manually.` }; }
276
+ return unchanged;
277
+ }));
278
+ }
279
+
280
+ async previewUpload(relative) {
281
+ relative = safePath(relative, this.config.extra);
282
+ const local = await this.localFile(relative);
283
+ if (local.sha256 === null) throw new UserError('Local file does not exist.');
284
+ return this.withClient(async client => {
285
+ const remote = await this.readRemote(client, relative);
286
+ const localSha256 = local.sha256;
287
+ const remoteSha256 = remote?.sha256 ?? null;
288
+ const changed = localSha256 !== remoteSha256;
289
+ const token = changed ? randomUUID() : null;
290
+ if (token) {
291
+ if (this.previews.size >= 100) this.previews.delete(this.previews.keys().next().value);
292
+ this.previews.set(token, { relative, localSha256, remoteSha256, expires: Date.now() + 10 * 60_000 });
293
+ }
294
+ return { path: relative, changed, localSha256, remoteSha256, localBytes: local.bytes, remoteBytes: remote?.bytes ?? null, uploadToken: token };
295
+ });
296
+ }
297
+
298
+ async upload(relative, token) {
299
+ relative = safePath(relative, this.config.extra);
300
+ return this.#withWrite(() => this.#commitUpload(relative, token));
301
+ }
302
+
303
+ async #commitUpload(relative, token) {
304
+ const preview = this.previews.get(token);
305
+ if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_upload again; its token is missing or expired.');
306
+ this.previews.delete(token);
307
+ const local = await this.localFile(relative);
308
+ if (local.sha256 !== preview.localSha256) throw new UserError('Local file changed since the preview.');
309
+ return this.withClient(async client => {
310
+ const remote = await this.readRemote(client, relative);
311
+ if ((remote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed since the preview.');
312
+ const parent = path.posix.dirname(relative);
313
+ const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
314
+ let backup = null;
315
+ try {
316
+ const { handle } = await this.#openLocal(relative);
317
+ if (!handle) throw new UserError('Local file changed during upload.');
318
+ const source = Readable.from(this.#localChunks(handle), { objectMode: false });
319
+ try { await client.uploadFrom(source, staged); }
320
+ finally {
321
+ source.destroy();
322
+ await handle.close();
323
+ }
324
+ const stagedFile = await this.readRemote(client, staged);
325
+ if (stagedFile?.sha256 !== preview.localSha256) throw new UserError('Staged upload verification failed.');
326
+ const latestLocal = await this.localFile(relative);
327
+ if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
328
+ const latestRemote = await this.readRemote(client, relative);
329
+ if ((latestRemote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
330
+ backup = await client.rename(staged, relative, latestRemote !== null);
331
+ } catch (error) {
332
+ try {
333
+ if (await this.entry(client, staged)) await client.remove(staged);
334
+ } catch {
335
+ const reason = error instanceof UserError ? error.message : 'Upload failed.';
336
+ throw new UserError(`${reason} Temporary remote file may remain at ${staged}.`);
337
+ }
338
+ throw error;
339
+ }
340
+ const recovery = backup ? ` The previous version remains at ${backup}.` : '';
341
+ let uploaded;
342
+ try { uploaded = await this.readRemote(client, relative); }
343
+ catch { throw new UserError(`Upload rename completed, but verification failed; inspect the remote file before retrying.${recovery}`); }
344
+ if (uploaded?.sha256 !== preview.localSha256) throw new UserError(`Upload verification failed; inspect the remote file before retrying.${recovery}`);
345
+ let warning;
346
+ if (backup) {
347
+ try { await client.remove(backup); }
348
+ catch { warning = `Upload succeeded, but the previous version remains at ${backup}; remove it manually.`; }
349
+ }
350
+ return { path: relative, status: 'uploaded', ...uploaded, ...(warning ? { warning } : {}) };
351
+ });
352
+ }
353
+ }
354
+
355
+ function safeExcluded(parent, name, extra) {
356
+ try {
357
+ safePath(parent ? `${parent}/${name}` : name, extra);
358
+ return false;
359
+ } catch {
360
+ return true;
361
+ }
362
+ }