@jwjp/ftp-mcp 0.2.1 → 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/README.md +149 -134
- package/package.json +1 -1
- package/src/config.js +35 -5
- package/src/paths.js +39 -5
- package/src/server.js +40 -18
- package/src/transports.js +122 -21
- package/src/workspace.js +239 -69
package/README.md
CHANGED
|
@@ -1,134 +1,149 @@
|
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
```sh
|
|
18
|
-
npm install -g @jwjp/ftp-mcp
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
|
|
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
|
|
44
|
-
| `SFTP_PASSPHRASE` | Optional passphrase for an encrypted SFTP private key |
|
|
45
|
-
| `
|
|
46
|
-
| `
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
The
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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
|
+
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
package/src/config.js
CHANGED
|
@@ -1,14 +1,30 @@
|
|
|
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. 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 !== ''));
|
|
6
13
|
const get = (name, legacy) => env[name] ?? env[legacy];
|
|
7
14
|
const legacyProtocol = env.FTP_SECURE === 'false' ? 'ftp' : env.FTP_SECURE === 'implicit' ? 'ftps-implicit' : 'ftps';
|
|
8
15
|
const protocol = env.REMOTE_PROTOCOL ?? legacyProtocol;
|
|
9
16
|
if (!['ftp', 'ftps', 'ftps-implicit', 'sftp'].includes(protocol)) {
|
|
10
17
|
throw new UserError('REMOTE_PROTOCOL must be ftp, ftps, ftps-implicit, or sftp.');
|
|
11
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
|
+
}
|
|
12
28
|
const host = get('REMOTE_HOST', 'FTP_HOST');
|
|
13
29
|
const user = get('REMOTE_USER', 'FTP_USER');
|
|
14
30
|
const password = get('REMOTE_PASSWORD', 'FTP_PASS');
|
|
@@ -18,10 +34,11 @@ export function loadConfig(env = process.env) {
|
|
|
18
34
|
if (!value) throw new UserError(`Missing ${name}.`);
|
|
19
35
|
}
|
|
20
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.');
|
|
21
38
|
if (!root.startsWith('/') || root.includes('\\') || /[\x00-\x1f\x7f]/u.test(root)) throw new UserError('REMOTE_ROOT must be an absolute POSIX path.');
|
|
22
39
|
for (const part of root.split('/').filter(Boolean)) relativePath(part);
|
|
23
|
-
|
|
24
|
-
|
|
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);
|
|
25
42
|
|
|
26
43
|
const defaultPort = protocol === 'sftp' ? 22 : protocol === 'ftps-implicit' ? 990 : 21;
|
|
27
44
|
const port = Number(get('REMOTE_PORT', 'FTP_PORT') || defaultPort);
|
|
@@ -30,13 +47,24 @@ export function loadConfig(env = process.env) {
|
|
|
30
47
|
for (const item of extra) relativePath(item);
|
|
31
48
|
const maxBytes = Number(get('REMOTE_MAX_FILE_BYTES', 'FTP_MAX_FILE_BYTES') || 10 * 1024 * 1024);
|
|
32
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
|
+
}
|
|
33
54
|
|
|
34
55
|
let sftpPrivateKeyFile = null;
|
|
35
56
|
let sftpHostKeySha256 = null;
|
|
57
|
+
let sftpTimeoutMs = DEFAULT_SFTP_TIMEOUT_MS;
|
|
36
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
|
+
}
|
|
37
63
|
if (env.SFTP_PRIVATE_KEY_FILE) {
|
|
38
64
|
sftpPrivateKeyFile = path.resolve(env.SFTP_PRIVATE_KEY_FILE);
|
|
39
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.');
|
|
40
68
|
}
|
|
41
69
|
if (!password && !sftpPrivateKeyFile) throw new UserError('Set REMOTE_PASSWORD or SFTP_PRIVATE_KEY_FILE for SFTP.');
|
|
42
70
|
const fingerprint = env.SFTP_HOST_KEY_SHA256?.replace(/^SHA256:/u, '').replace(/=$/u, '');
|
|
@@ -44,13 +72,15 @@ export function loadConfig(env = process.env) {
|
|
|
44
72
|
sftpHostKeySha256 = fingerprint;
|
|
45
73
|
} else if (!password) {
|
|
46
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.');
|
|
47
77
|
}
|
|
48
78
|
|
|
49
79
|
return {
|
|
50
80
|
protocol, host, user, password, port,
|
|
51
81
|
secure: protocol === 'ftps' ? true : protocol === 'ftps-implicit' ? 'implicit' : false,
|
|
52
|
-
remoteRoot: root, localRoot, extra, maxBytes,
|
|
82
|
+
remoteRoot: root, localRoot, extra, maxBytes, idleTimeoutMs,
|
|
53
83
|
sftpPrivateKeyFile, sftpPassphrase: env.SFTP_PASSPHRASE,
|
|
54
|
-
sftpHostKeySha256
|
|
84
|
+
sftpHostKeySha256, sftpTimeoutMs, warnings
|
|
55
85
|
};
|
|
56
86
|
}
|
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
|
-
|
|
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
|
|
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
|
|
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
|
}
|
package/src/server.js
CHANGED
|
@@ -1,54 +1,76 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { McpServer } from '@modelcontextprotocol/server';
|
|
3
3
|
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
|
4
|
-
import {
|
|
5
|
-
import path from 'node:path';
|
|
4
|
+
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
|
6
5
|
import * as z from 'zod/v4';
|
|
7
6
|
import { loadConfig } from './config.js';
|
|
8
7
|
import { UserError } from './paths.js';
|
|
9
|
-
import { FtpWorkspace } from './workspace.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);
|
|
10
12
|
|
|
11
13
|
function result(value) { return { content: [{ type: 'text', text: JSON.stringify(value) }] }; }
|
|
12
|
-
|
|
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) {
|
|
13
27
|
return async args => {
|
|
14
28
|
try { return result(await fn(args)); }
|
|
15
29
|
catch (error) {
|
|
16
|
-
|
|
17
|
-
|
|
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 };
|
|
18
35
|
}
|
|
19
36
|
};
|
|
20
37
|
}
|
|
21
38
|
|
|
22
39
|
export function createServer(workspace) {
|
|
23
|
-
const server = new McpServer({ name: 'ftp-workspace-mcp', version
|
|
40
|
+
const server = new McpServer({ name: 'ftp-workspace-mcp', version }, {
|
|
24
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.'
|
|
25
42
|
});
|
|
26
43
|
server.registerTool('remote_list', {
|
|
27
|
-
description:
|
|
28
|
-
inputSchema: z.object({ path:
|
|
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() }),
|
|
29
46
|
annotations: { readOnlyHint: true }
|
|
30
|
-
}, tool(({ path }) => workspace.list(path)));
|
|
47
|
+
}, tool('remote_list', workspace, ({ path, cursor }) => workspace.list(path, cursor)));
|
|
31
48
|
server.registerTool('remote_download', {
|
|
32
49
|
description: 'Download one remote file into the configured local root. Existing differing files require their current SHA-256 as expectedLocalSha256.',
|
|
33
|
-
inputSchema: z.object({ path:
|
|
50
|
+
inputSchema: z.object({ path: relativeInput, expectedLocalSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }),
|
|
34
51
|
annotations: { readOnlyHint: false }
|
|
35
|
-
}, tool(({ path, expectedLocalSha256 }) => workspace.download(path, expectedLocalSha256)));
|
|
52
|
+
}, tool('remote_download', workspace, ({ path, expectedLocalSha256 }) => workspace.download(path, expectedLocalSha256)));
|
|
36
53
|
server.registerTool('remote_preview_upload', {
|
|
37
54
|
description: 'Compare one local file with its remote counterpart and issue a short-lived token if upload is needed.',
|
|
38
|
-
inputSchema: z.object({ path:
|
|
55
|
+
inputSchema: z.object({ path: relativeInput }),
|
|
39
56
|
annotations: { readOnlyHint: true }
|
|
40
|
-
}, tool(({ path }) => workspace.previewUpload(path)));
|
|
57
|
+
}, tool('remote_preview_upload', workspace, ({ path }) => workspace.previewUpload(path)));
|
|
41
58
|
server.registerTool('remote_upload', {
|
|
42
59
|
description: 'Upload exactly one file after preview. Reject changed local or remote content and verify uploaded bytes. Replacement may not be atomic.',
|
|
43
|
-
inputSchema: z.object({ path:
|
|
60
|
+
inputSchema: z.object({ path: relativeInput, uploadToken: z.string().uuid() }),
|
|
44
61
|
annotations: { readOnlyHint: false, destructiveHint: true }
|
|
45
|
-
}, tool(({ path, uploadToken }) => workspace.upload(path, uploadToken)));
|
|
62
|
+
}, tool('remote_upload', workspace, ({ path, uploadToken }) => workspace.upload(path, uploadToken)));
|
|
46
63
|
return server;
|
|
47
64
|
}
|
|
48
65
|
|
|
49
|
-
if (process.argv[1] &&
|
|
66
|
+
if (process.argv[1] && existsSync(process.argv[1]) && realpathSync.native(import.meta.filename) === realpathSync.native(process.argv[1])) {
|
|
50
67
|
try {
|
|
51
|
-
const
|
|
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(); });
|
|
52
74
|
await serveStdio(() => createServer(workspace));
|
|
53
75
|
} catch (error) {
|
|
54
76
|
console.error(error instanceof UserError ? error.message : 'Failed to start remote MCP server.');
|
package/src/transports.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import fs from 'node:fs/promises';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
3
4
|
import path from 'node:path';
|
|
4
|
-
import { Readable } from 'node:stream';
|
|
5
|
+
import { Readable, Transform } from 'node:stream';
|
|
6
|
+
import { pipeline } from 'node:stream/promises';
|
|
5
7
|
import { Client as FtpClient, FileType } from 'basic-ftp';
|
|
6
8
|
import SftpClient from 'ssh2-sftp-client';
|
|
9
|
+
import { DEFAULT_SFTP_TIMEOUT_MS } from './config.js';
|
|
7
10
|
import { UserError } from './paths.js';
|
|
8
11
|
|
|
9
12
|
export class FtpTransport {
|
|
@@ -12,15 +15,20 @@ export class FtpTransport {
|
|
|
12
15
|
this.client = client;
|
|
13
16
|
}
|
|
14
17
|
async access() {
|
|
18
|
+
const { host, port, user, password, secure } = this.config;
|
|
15
19
|
await this.client.access({
|
|
16
|
-
host
|
|
17
|
-
|
|
20
|
+
host, port, user, password, secure,
|
|
21
|
+
secureOptions: secure ? { rejectUnauthorized: true, ...(isIP(host) ? {} : { servername: host }) } : undefined
|
|
18
22
|
});
|
|
19
23
|
}
|
|
20
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
|
+
}
|
|
21
29
|
async list(relative) { return this.client.list(relative); }
|
|
22
30
|
async downloadTo(local, relative) { await this.client.downloadTo(local, relative); }
|
|
23
|
-
async uploadFrom(
|
|
31
|
+
async uploadFrom(source, relative) { await this.client.uploadFrom(source, relative); }
|
|
24
32
|
async rename(from, to, replace) {
|
|
25
33
|
if (!replace) {
|
|
26
34
|
await this.client.rename(from, to);
|
|
@@ -30,32 +38,78 @@ export class FtpTransport {
|
|
|
30
38
|
// a backup name until the staged file takes its place.
|
|
31
39
|
const parent = path.posix.dirname(to);
|
|
32
40
|
const backup = path.posix.join(parent === '.' ? '' : parent, `.mcp-backup-${randomUUID()}.tmp`);
|
|
33
|
-
await this.client.rename(to, backup);
|
|
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
|
+
}
|
|
34
46
|
try {
|
|
35
47
|
await this.client.rename(from, to);
|
|
36
48
|
} catch (error) {
|
|
37
|
-
|
|
38
|
-
|
|
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
|
+
}
|
|
39
63
|
throw error;
|
|
40
64
|
}
|
|
41
|
-
|
|
42
|
-
catch { return `Upload succeeded, but the previous version remains at ${backup}; remove it manually.`; }
|
|
43
|
-
return null;
|
|
65
|
+
return backup;
|
|
44
66
|
}
|
|
45
67
|
async remove(relative) { await this.client.remove(relative); }
|
|
46
68
|
async close() { this.client.close(); }
|
|
47
69
|
}
|
|
48
70
|
|
|
49
71
|
export class SftpTransport {
|
|
50
|
-
|
|
72
|
+
#timeoutError = null;
|
|
73
|
+
|
|
74
|
+
constructor(config, client = new SftpClient('ftp-workspace-mcp', { error() {}, end() {}, close() {} })) {
|
|
51
75
|
this.config = config;
|
|
52
76
|
this.client = client;
|
|
53
77
|
this.root = null;
|
|
54
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
|
+
|
|
55
109
|
async access() {
|
|
56
110
|
const config = {
|
|
57
111
|
host: this.config.host, port: this.config.port, username: this.config.user,
|
|
58
|
-
readyTimeout:
|
|
112
|
+
readyTimeout: this.config.sftpTimeoutMs ?? DEFAULT_SFTP_TIMEOUT_MS,
|
|
59
113
|
hostVerifier: key => createHash('sha256').update(key).digest('base64').replace(/=+$/u, '') === this.config.sftpHostKeySha256
|
|
60
114
|
};
|
|
61
115
|
if (this.config.password) config.password = this.config.password;
|
|
@@ -63,33 +117,80 @@ export class SftpTransport {
|
|
|
63
117
|
config.privateKey = await fs.readFile(this.config.sftpPrivateKeyFile);
|
|
64
118
|
if (this.config.sftpPassphrase) config.passphrase = this.config.sftpPassphrase;
|
|
65
119
|
}
|
|
66
|
-
await this.client.connect(config);
|
|
120
|
+
await this.#run('connection', () => this.client.connect(config));
|
|
67
121
|
}
|
|
68
122
|
async cd(root) {
|
|
69
|
-
if (await this.client.exists(root) !== 'd') throw new UserError('Remote root is not a directory.');
|
|
123
|
+
if (await this.#run('root check', () => this.client.exists(root)) !== 'd') throw new UserError('Remote root is not a directory.');
|
|
70
124
|
this.root = root;
|
|
71
125
|
}
|
|
126
|
+
async ping() { await this.#run('keepalive check', () => this.client.cwd()); }
|
|
72
127
|
remote(relative) {
|
|
73
128
|
if (!this.root) throw new Error('SFTP root is not set.');
|
|
74
129
|
return path.posix.join(this.root, relative);
|
|
75
130
|
}
|
|
76
131
|
async list(relative) {
|
|
77
|
-
|
|
132
|
+
const entries = await this.#run('listing', () => this.client.list(this.remote(relative)));
|
|
133
|
+
return entries.map(item => ({
|
|
78
134
|
name: item.name,
|
|
79
135
|
type: item.type === 'd' ? FileType.Directory : item.type === '-' ? FileType.File : FileType.SymbolicLink,
|
|
80
136
|
size: item.size,
|
|
81
137
|
modifiedAt: item.modifyTime ? new Date(item.modifyTime) : undefined
|
|
82
138
|
}));
|
|
83
139
|
}
|
|
84
|
-
async downloadTo(local, relative) {
|
|
85
|
-
|
|
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
|
+
}
|
|
86
174
|
async rename(from, to, replace) {
|
|
87
|
-
|
|
88
|
-
|
|
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
|
+
}
|
|
89
188
|
return null;
|
|
90
189
|
}
|
|
91
|
-
async remove(relative) { await this.client.delete(this.remote(relative), true); }
|
|
92
|
-
async close() {
|
|
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
|
+
}
|
|
93
194
|
}
|
|
94
195
|
|
|
95
196
|
export function createTransport(config) {
|
package/src/workspace.js
CHANGED
|
@@ -1,31 +1,120 @@
|
|
|
1
1
|
import { createHash, randomUUID } from 'node:crypto';
|
|
2
2
|
import fs from 'node:fs/promises';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import { Writable } from 'node:stream';
|
|
4
|
+
import { Readable, Writable } from 'node:stream';
|
|
5
5
|
import { FileType } from 'basic-ftp';
|
|
6
|
+
import { DEFAULT_IDLE_TIMEOUT_MS } from './config.js';
|
|
6
7
|
import { localPath, safePath, UserError } from './paths.js';
|
|
7
8
|
import { createTransport } from './transports.js';
|
|
8
9
|
|
|
9
|
-
const
|
|
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
|
+
}
|
|
10
28
|
|
|
11
29
|
export class FtpWorkspace {
|
|
30
|
+
#clientQueue = Promise.resolve();
|
|
31
|
+
#idle = null;
|
|
32
|
+
#closed = false;
|
|
33
|
+
|
|
12
34
|
constructor(config, clientFactory = () => createTransport(config)) {
|
|
13
35
|
this.config = config;
|
|
14
36
|
this.clientFactory = clientFactory;
|
|
15
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;
|
|
16
69
|
}
|
|
17
70
|
|
|
18
|
-
async
|
|
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
|
+
}
|
|
19
85
|
const client = this.clientFactory();
|
|
20
86
|
try {
|
|
21
87
|
await client.access();
|
|
22
88
|
await client.cd(this.config.remoteRoot);
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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);
|
|
29
118
|
}
|
|
30
119
|
}
|
|
31
120
|
|
|
@@ -45,139 +134,220 @@ export class FtpWorkspace {
|
|
|
45
134
|
}
|
|
46
135
|
}
|
|
47
136
|
|
|
48
|
-
async list(relative = '') {
|
|
137
|
+
async list(relative = '', cursor = '') {
|
|
49
138
|
relative = safePath(relative, this.config.extra, { allowRoot: true });
|
|
50
139
|
return this.withClient(async client => {
|
|
51
140
|
if (relative) {
|
|
52
141
|
const entry = await this.entry(client, relative);
|
|
53
142
|
if (!entry || entry.type !== FileType.Directory) throw new UserError('Remote directory does not exist.');
|
|
54
143
|
}
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
.
|
|
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
|
+
};
|
|
58
154
|
});
|
|
59
155
|
}
|
|
60
156
|
|
|
61
|
-
async
|
|
157
|
+
async #remoteEntry(client, relative) {
|
|
62
158
|
const entry = await this.entry(client, relative);
|
|
63
159
|
if (!entry) return null;
|
|
64
160
|
if (entry.type !== FileType.File) throw new UserError('Remote path is not a regular file.');
|
|
65
161
|
if (entry.size > this.config.maxBytes) throw new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.');
|
|
66
|
-
|
|
162
|
+
return entry;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async #readRemote(client, relative, entry, destination) {
|
|
166
|
+
const hash = createHash('sha256');
|
|
67
167
|
let bytes = 0;
|
|
68
168
|
const limit = this.config.maxBytes;
|
|
69
169
|
const sink = new Writable({
|
|
70
170
|
write(chunk, _encoding, callback) {
|
|
71
171
|
bytes += chunk.length;
|
|
72
172
|
if (bytes > limit) return callback(new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.'));
|
|
73
|
-
|
|
74
|
-
callback();
|
|
173
|
+
hash.update(chunk);
|
|
174
|
+
if (destination) writeAll(destination, chunk).then(() => callback(), callback);
|
|
175
|
+
else callback();
|
|
75
176
|
}
|
|
76
177
|
});
|
|
77
|
-
await client.downloadTo(sink, relative);
|
|
78
|
-
|
|
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 };
|
|
79
184
|
}
|
|
80
185
|
|
|
81
|
-
async
|
|
82
|
-
const
|
|
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);
|
|
83
193
|
const stat = await fs.stat(file).catch(error => {
|
|
84
194
|
if (error.code === 'ENOENT') return null;
|
|
85
195
|
throw error;
|
|
86
196
|
});
|
|
87
|
-
if (!stat) return { file,
|
|
197
|
+
if (!stat) return { file, handle: null };
|
|
88
198
|
if (!stat.isFile()) throw new UserError('Local path is not a regular file.');
|
|
89
199
|
if (stat.size > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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 };
|
|
93
232
|
}
|
|
94
233
|
|
|
95
234
|
async download(relative, expectedLocalSha256) {
|
|
96
235
|
relative = safePath(relative, this.config.extra);
|
|
97
|
-
return this.withClient(async client => {
|
|
98
|
-
const
|
|
99
|
-
if (!
|
|
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.');
|
|
100
239
|
const local = await this.localFile(relative);
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
throw new UserError(
|
|
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.`);
|
|
106
246
|
}
|
|
107
247
|
await fs.mkdir(path.dirname(local.file), { recursive: true });
|
|
108
|
-
await localPath(this.config.localRoot, relative);
|
|
109
|
-
const temp =
|
|
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;
|
|
110
252
|
try {
|
|
111
|
-
|
|
253
|
+
let remote;
|
|
254
|
+
try { remote = await this.#readRemote(client, relative, entry, handle); }
|
|
255
|
+
finally { await handle.close(); }
|
|
112
256
|
const latest = await this.localFile(relative);
|
|
113
|
-
if (
|
|
114
|
-
|
|
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 };
|
|
115
266
|
}
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
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;
|
|
119
271
|
}
|
|
120
|
-
|
|
121
|
-
|
|
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
|
+
}));
|
|
122
278
|
}
|
|
123
279
|
|
|
124
280
|
async previewUpload(relative) {
|
|
125
281
|
relative = safePath(relative, this.config.extra);
|
|
126
282
|
const local = await this.localFile(relative);
|
|
127
|
-
if (
|
|
283
|
+
if (local.sha256 === null) throw new UserError('Local file does not exist.');
|
|
128
284
|
return this.withClient(async client => {
|
|
129
285
|
const remote = await this.readRemote(client, relative);
|
|
130
|
-
const localSha256 =
|
|
131
|
-
const remoteSha256 = remote
|
|
286
|
+
const localSha256 = local.sha256;
|
|
287
|
+
const remoteSha256 = remote?.sha256 ?? null;
|
|
132
288
|
const changed = localSha256 !== remoteSha256;
|
|
133
289
|
const token = changed ? randomUUID() : null;
|
|
134
290
|
if (token) {
|
|
135
291
|
if (this.previews.size >= 100) this.previews.delete(this.previews.keys().next().value);
|
|
136
292
|
this.previews.set(token, { relative, localSha256, remoteSha256, expires: Date.now() + 10 * 60_000 });
|
|
137
293
|
}
|
|
138
|
-
return { path: relative, changed, localSha256, remoteSha256, localBytes: local.
|
|
294
|
+
return { path: relative, changed, localSha256, remoteSha256, localBytes: local.bytes, remoteBytes: remote?.bytes ?? null, uploadToken: token };
|
|
139
295
|
});
|
|
140
296
|
}
|
|
141
297
|
|
|
142
298
|
async upload(relative, token) {
|
|
143
299
|
relative = safePath(relative, this.config.extra);
|
|
300
|
+
return this.#withWrite(() => this.#commitUpload(relative, token));
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async #commitUpload(relative, token) {
|
|
144
304
|
const preview = this.previews.get(token);
|
|
145
305
|
if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_upload again; its token is missing or expired.');
|
|
146
306
|
this.previews.delete(token);
|
|
147
307
|
const local = await this.localFile(relative);
|
|
148
|
-
if (
|
|
308
|
+
if (local.sha256 !== preview.localSha256) throw new UserError('Local file changed since the preview.');
|
|
149
309
|
return this.withClient(async client => {
|
|
150
310
|
const remote = await this.readRemote(client, relative);
|
|
151
|
-
if ((remote
|
|
311
|
+
if ((remote?.sha256 ?? null) !== preview.remoteSha256) throw new UserError('Remote file changed since the preview.');
|
|
152
312
|
const parent = path.posix.dirname(relative);
|
|
153
313
|
const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
|
|
154
|
-
let
|
|
155
|
-
let stageAttempted = false;
|
|
156
|
-
let warning = null;
|
|
314
|
+
let backup = null;
|
|
157
315
|
try {
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
const
|
|
161
|
-
|
|
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.');
|
|
162
326
|
const latestLocal = await this.localFile(relative);
|
|
163
|
-
if (
|
|
327
|
+
if (latestLocal.sha256 !== preview.localSha256) throw new UserError('Local file changed during upload.');
|
|
164
328
|
const latestRemote = await this.readRemote(client, relative);
|
|
165
|
-
if ((latestRemote
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
catch { throw new UserError(`Upload failed and temporary remote file may remain at ${staged}.`); }
|
|
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}.`);
|
|
174
337
|
}
|
|
338
|
+
throw error;
|
|
175
339
|
}
|
|
340
|
+
const recovery = backup ? ` The previous version remains at ${backup}.` : '';
|
|
176
341
|
let uploaded;
|
|
177
342
|
try { uploaded = await this.readRemote(client, relative); }
|
|
178
|
-
catch { throw new UserError(
|
|
179
|
-
if (
|
|
180
|
-
|
|
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 } : {}) };
|
|
181
351
|
});
|
|
182
352
|
}
|
|
183
353
|
}
|