@jwjp/ftp-mcp 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +134 -3
- package/package.json +38 -4
- package/src/config.js +56 -0
- package/src/paths.js +50 -0
- package/src/server.js +57 -0
- package/src/transports.js +97 -0
- package/src/workspace.js +192 -0
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,134 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# FTP Workspace MCP
|
|
2
|
+
|
|
3
|
+
A local stdio MCP server for AI coding work on projects reachable through **FTP or SFTP**. Explicit and implicit FTPS are also supported. It works with any project language or framework and exposes four file-level tools: `remote_list`, `remote_download`, `remote_preview_upload`, and `remote_upload`.
|
|
4
|
+
|
|
5
|
+
The server has no recursive sync, remote delete, or shell execution tool. In version 0.2, the tool names changed from `ftp_*` to `remote_*` to reflect SFTP support.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Node.js 22.12 or newer
|
|
10
|
+
- FTP, SFTP, or FTPS access to the project
|
|
11
|
+
- An MCP client that can start a local stdio server
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
Once the npm release is available, install the public `@jwjp/ftp-mcp` package globally. Its executable remains `ftp-workspace-mcp` to avoid a command name collision with the existing unscoped `ftp-mcp` package:
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npm install -g @jwjp/ftp-mcp
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Until that release, install from GitHub:
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
git clone https://github.com/jwjp/ftp-mcp.git
|
|
25
|
+
cd ftp-mcp
|
|
26
|
+
npm ci
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
The MCP examples below use the GitHub checkout. After a global npm install, set the MCP command to `ftp-workspace-mcp` and omit the script path and `node` argument.
|
|
30
|
+
|
|
31
|
+
Set the following variables in the environment that launches the MCP server. Keep passwords, private keys, and passphrases out of the project, chat, Git, `CLAUDE.md`, and shared MCP configuration. `.env.example` is a reference only; this server does not load `.env` files.
|
|
32
|
+
|
|
33
|
+
| Variable | Meaning |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| `REMOTE_PROTOCOL` | `ftp`, `sftp`, `ftps`, or `ftps-implicit`; set explicitly |
|
|
36
|
+
| `REMOTE_HOST` | Remote server hostname, without a URL scheme |
|
|
37
|
+
| `REMOTE_USER` | Remote username |
|
|
38
|
+
| `REMOTE_PASSWORD` | FTP/FTPS password, or SFTP password if not using a private key |
|
|
39
|
+
| `REMOTE_ROOT` | Absolute remote project directory, for example `/site` |
|
|
40
|
+
| `LOCAL_ROOT` | Existing absolute local project directory |
|
|
41
|
+
| `REMOTE_PORT` | Optional; defaults to 21 for FTP/explicit FTPS, 22 for SFTP, 990 for implicit FTPS |
|
|
42
|
+
| `SFTP_HOST_KEY_SHA256` | Required for SFTP; trusted SSH host key fingerprint in `SHA256:...` format |
|
|
43
|
+
| `SFTP_PRIVATE_KEY_FILE` | Optional SFTP private key file path; use instead of a password |
|
|
44
|
+
| `SFTP_PASSPHRASE` | Optional passphrase for an encrypted SFTP private key |
|
|
45
|
+
| `REMOTE_EXCLUDE` | Optional comma-separated additional names or relative paths, such as `uploads,logs,cache` |
|
|
46
|
+
| `REMOTE_MAX_FILE_BYTES` | Optional per-file limit; default 10 MiB, maximum 100 MiB |
|
|
47
|
+
|
|
48
|
+
SFTP is SSH File Transfer Protocol, not FTP over TLS. For SFTP, get the SSH host key fingerprint from your hosting provider or another trusted channel before connecting. The server rejects a mismatched host key. FTP sends credentials in plaintext; use SFTP or FTPS if available. FTPS certificate verification remains enabled.
|
|
49
|
+
|
|
50
|
+
The former `FTP_*` variables still work for existing FTP/FTPS configurations. A missing `REMOTE_PROTOCOL` follows the old `FTP_SECURE` setting (`true` → `ftps`, `false` → `ftp`, `implicit` → `ftps-implicit`). New configurations should use the `REMOTE_*` names and explicitly set the protocol.
|
|
51
|
+
|
|
52
|
+
The built-in exclusion list blocks `.git`, `.env` and `.env.*`, `.mcp.json`, `vendor`, and `node_modules` anywhere in the path. Extra entries match a name segment or an exact relative path and its descendants, case-insensitively. Review exclusions for each project. Install dependencies or build generated files locally when appropriate.
|
|
53
|
+
|
|
54
|
+
### VS Code with GitHub Copilot
|
|
55
|
+
|
|
56
|
+
Use **Chat: Open Customizations → MCP Servers → Add Server → Command (stdio) → Global → Copilot Global**, or edit your personal `~/.copilot/mcp-config.json`. Current VS Code Copilot uses `mcpServers` in this personal file; `.vscode/mcp.json` is the older editor-managed format. See the [VS Code MCP configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration).
|
|
57
|
+
|
|
58
|
+
Example personal configuration for SFTP (replace the paths and set the referenced user environment variables):
|
|
59
|
+
|
|
60
|
+
```json
|
|
61
|
+
{
|
|
62
|
+
"mcpServers": {
|
|
63
|
+
"remote-workspace": {
|
|
64
|
+
"type": "stdio",
|
|
65
|
+
"command": "node",
|
|
66
|
+
"args": ["/absolute/path/to/ftp-mcp/src/server.js"],
|
|
67
|
+
"env": {
|
|
68
|
+
"REMOTE_PROTOCOL": "sftp",
|
|
69
|
+
"REMOTE_HOST": "${MY_REMOTE_HOST}",
|
|
70
|
+
"REMOTE_USER": "${MY_REMOTE_USER}",
|
|
71
|
+
"REMOTE_PASSWORD": "${MY_REMOTE_PASSWORD}",
|
|
72
|
+
"REMOTE_ROOT": "/site",
|
|
73
|
+
"LOCAL_ROOT": "/absolute/path/to/my-project",
|
|
74
|
+
"SFTP_HOST_KEY_SHA256": "${MY_SFTP_HOST_KEY_SHA256}"
|
|
75
|
+
},
|
|
76
|
+
"tools": ["*"]
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
The `${NAME}` syntax is resolved by the Copilot harness. For key authentication, replace `REMOTE_PASSWORD` with `SFTP_PRIVATE_KEY_FILE` (and `SFTP_PASSPHRASE` if needed). For FTP, set `REMOTE_PROTOCOL` to `ftp`, omit `SFTP_HOST_KEY_SHA256`, and provide `REMOTE_PASSWORD`. On Windows, use absolute paths with JSON-escaped backslashes or forward slashes.
|
|
83
|
+
|
|
84
|
+
### Claude Code
|
|
85
|
+
|
|
86
|
+
Claude Code can launch this same stdio server. Set the environment variables from the table above in the environment that starts Claude Code. From the **local project directory you want to edit**, register the server at local scope:
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
claude mcp add --scope local --transport stdio remote-workspace -- node /absolute/path/to/ftp-mcp/src/server.js
|
|
90
|
+
claude mcp get remote-workspace
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
On Windows, use a path such as `C:/path/to/ftp-mcp/src/server.js`. Local scope keeps the definition private to that project. Do not pass passwords through `--env` in a shell command, because shell history and MCP configuration may retain them. Restart Claude Code after changing user environment variables. Run `/mcp` to check the connection. See the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp).
|
|
94
|
+
|
|
95
|
+
For a team-shared setup, Claude Code also reads `.mcp.json` in the project root. Use environment-variable references such as `${REMOTE_PASSWORD}` and never commit a literal password. This server excludes `.mcp.json` from transfers by default.
|
|
96
|
+
|
|
97
|
+
### Codex
|
|
98
|
+
|
|
99
|
+
The Codex desktop app, CLI, and IDE extension share MCP settings. Add the server through **Settings → MCP servers → Add server → STDIO**, or add this entry to your personal `~/.codex/config.toml` (on Windows, `%USERPROFILE%\.codex\config.toml`):
|
|
100
|
+
|
|
101
|
+
```toml
|
|
102
|
+
[mcp_servers.remote_workspace]
|
|
103
|
+
command = "node"
|
|
104
|
+
args = ["C:/absolute/path/to/ftp-mcp/src/server.js"]
|
|
105
|
+
env_vars = ["REMOTE_PROTOCOL", "REMOTE_HOST", "REMOTE_USER", "REMOTE_PASSWORD", "REMOTE_ROOT", "LOCAL_ROOT", "REMOTE_PORT", "SFTP_HOST_KEY_SHA256", "SFTP_PRIVATE_KEY_FILE", "SFTP_PASSPHRASE", "REMOTE_EXCLUDE", "REMOTE_MAX_FILE_BYTES"]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Replace the script path and set the required variables locally before starting Codex. `env_vars` forwards named values without storing them in TOML. Restart Codex after changing configuration. `codex mcp list` or `/mcp` shows the server. The same entry may instead go in a trusted project's `.codex/config.toml`. See the [Codex MCP guide](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
|
|
109
|
+
|
|
110
|
+
## File workflow
|
|
111
|
+
|
|
112
|
+
1. `remote_list({"path":""})`, then list only relevant subdirectories.
|
|
113
|
+
2. `remote_download({"path":"src/example.php"})`. If a local copy differs, the tool returns its SHA-256; compare it before replacing it with `expectedLocalSha256`.
|
|
114
|
+
3. Edit and test locally.
|
|
115
|
+
4. `remote_preview_upload({"path":"src/example.php"})`. Review the path and both hashes. It returns an `uploadToken` when content differs.
|
|
116
|
+
5. `remote_upload({"path":"src/example.php","uploadToken":"..."})` within ten minutes. A changed local or remote file invalidates the preview.
|
|
117
|
+
|
|
118
|
+
Upload tokens are single-use and held only in the MCP process. Restarting it requires a fresh preview. Uploads first write and verify a temporary remote file, then rename it into place. For FTP replacement, the old file is briefly moved to a backup name because some servers refuse to rename over an existing file. If the final rename fails, the server attempts to restore the old file. For SFTP replacement, the server must support the `posix-rename@openssh.com` extension. The tool verifies remote bytes after the rename. A crash, lost connection, or server failure can still leave a temporary or backup file, and FTP replacement has a brief interval when the target name is absent. A replacement may also change file permissions. Use a separate deployment or backup process when interruption cannot be tolerated.
|
|
119
|
+
|
|
120
|
+
## Boundaries
|
|
121
|
+
|
|
122
|
+
- Paths stay beneath fixed local and remote roots. Parent traversal, absolute paths, control characters, excluded entries, and discovered symlinks are rejected.
|
|
123
|
+
- Each read and upload is limited by `REMOTE_MAX_FILE_BYTES`. Reads stop when the limit is exceeded, even if the server reports an incorrect size. A transfer may still buffer up to the configured limit in memory.
|
|
124
|
+
- Remote symlink detection depends on the server listing and cannot prevent a server-side path change between validation and transfer.
|
|
125
|
+
- No remote credentials or project files are stored in this repository. Reads and previews use memory. Downloads create a temporary file beside the local target before renaming it; uploads create a temporary file beside the remote target and may briefly create a backup on FTP replacement. Cleanup is attempted after failure, but a connection loss can prevent it.
|
|
126
|
+
|
|
127
|
+
## Development
|
|
128
|
+
|
|
129
|
+
```sh
|
|
130
|
+
npm test
|
|
131
|
+
npm audit --omit=dev
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Tests cover path restrictions, FTP and SFTP transport behavior, upload previews, and legacy and current MCP stdio handshakes. Test against your own server before relying on a production upload. Contributions are welcome under the MIT license.
|
package/package.json
CHANGED
|
@@ -1,6 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jwjp/ftp-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
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,56 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { relativePath, UserError } from './paths.js';
|
|
4
|
+
|
|
5
|
+
export function loadConfig(env = process.env) {
|
|
6
|
+
const get = (name, legacy) => env[name] ?? env[legacy];
|
|
7
|
+
const legacyProtocol = env.FTP_SECURE === 'false' ? 'ftp' : env.FTP_SECURE === 'implicit' ? 'ftps-implicit' : 'ftps';
|
|
8
|
+
const protocol = env.REMOTE_PROTOCOL ?? legacyProtocol;
|
|
9
|
+
if (!['ftp', 'ftps', 'ftps-implicit', 'sftp'].includes(protocol)) {
|
|
10
|
+
throw new UserError('REMOTE_PROTOCOL must be ftp, ftps, ftps-implicit, or sftp.');
|
|
11
|
+
}
|
|
12
|
+
const host = get('REMOTE_HOST', 'FTP_HOST');
|
|
13
|
+
const user = get('REMOTE_USER', 'FTP_USER');
|
|
14
|
+
const password = get('REMOTE_PASSWORD', 'FTP_PASS');
|
|
15
|
+
const root = get('REMOTE_ROOT', 'FTP_REMOTE_ROOT');
|
|
16
|
+
const local = get('LOCAL_ROOT', 'FTP_LOCAL_ROOT');
|
|
17
|
+
for (const [name, value] of [['REMOTE_HOST', host], ['REMOTE_USER', user], ['REMOTE_ROOT', root], ['LOCAL_ROOT', local]]) {
|
|
18
|
+
if (!value) throw new UserError(`Missing ${name}.`);
|
|
19
|
+
}
|
|
20
|
+
if (/[\x00-\x1f\x7f]/u.test(host) || /[\x00-\x1f\x7f]/u.test(user)) throw new UserError('Invalid remote host or user.');
|
|
21
|
+
if (!root.startsWith('/') || root.includes('\\') || /[\x00-\x1f\x7f]/u.test(root)) throw new UserError('REMOTE_ROOT must be an absolute POSIX path.');
|
|
22
|
+
for (const part of root.split('/').filter(Boolean)) relativePath(part);
|
|
23
|
+
const localRoot = path.resolve(local);
|
|
24
|
+
if (!fs.statSync(localRoot, { throwIfNoEntry: false })?.isDirectory()) throw new UserError('LOCAL_ROOT must exist and be a directory.');
|
|
25
|
+
|
|
26
|
+
const defaultPort = protocol === 'sftp' ? 22 : protocol === 'ftps-implicit' ? 990 : 21;
|
|
27
|
+
const port = Number(get('REMOTE_PORT', 'FTP_PORT') || defaultPort);
|
|
28
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new UserError('REMOTE_PORT must be 1–65535.');
|
|
29
|
+
const extra = (get('REMOTE_EXCLUDE', 'FTP_EXCLUDE') || '').split(',').map(s => s.trim()).filter(Boolean);
|
|
30
|
+
for (const item of extra) relativePath(item);
|
|
31
|
+
const maxBytes = Number(get('REMOTE_MAX_FILE_BYTES', 'FTP_MAX_FILE_BYTES') || 10 * 1024 * 1024);
|
|
32
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > 100 * 1024 * 1024) throw new UserError('REMOTE_MAX_FILE_BYTES must be between 1 and 104857600.');
|
|
33
|
+
|
|
34
|
+
let sftpPrivateKeyFile = null;
|
|
35
|
+
let sftpHostKeySha256 = null;
|
|
36
|
+
if (protocol === 'sftp') {
|
|
37
|
+
if (env.SFTP_PRIVATE_KEY_FILE) {
|
|
38
|
+
sftpPrivateKeyFile = path.resolve(env.SFTP_PRIVATE_KEY_FILE);
|
|
39
|
+
if (!fs.statSync(sftpPrivateKeyFile, { throwIfNoEntry: false })?.isFile()) throw new UserError('SFTP_PRIVATE_KEY_FILE must be an existing file.');
|
|
40
|
+
}
|
|
41
|
+
if (!password && !sftpPrivateKeyFile) throw new UserError('Set REMOTE_PASSWORD or SFTP_PRIVATE_KEY_FILE for SFTP.');
|
|
42
|
+
const fingerprint = env.SFTP_HOST_KEY_SHA256?.replace(/^SHA256:/u, '').replace(/=$/u, '');
|
|
43
|
+
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.');
|
|
44
|
+
sftpHostKeySha256 = fingerprint;
|
|
45
|
+
} else if (!password) {
|
|
46
|
+
throw new UserError('Missing REMOTE_PASSWORD.');
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return {
|
|
50
|
+
protocol, host, user, password, port,
|
|
51
|
+
secure: protocol === 'ftps' ? true : protocol === 'ftps-implicit' ? 'implicit' : false,
|
|
52
|
+
remoteRoot: root, localRoot, extra, maxBytes,
|
|
53
|
+
sftpPrivateKeyFile, sftpPassphrase: env.SFTP_PASSPHRASE,
|
|
54
|
+
sftpHostKeySha256
|
|
55
|
+
};
|
|
56
|
+
}
|
package/src/paths.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
|
|
4
|
+
const DEFAULT_EXCLUDES = ['.git', '.env', '.mcp.json', 'node_modules', 'vendor'];
|
|
5
|
+
|
|
6
|
+
export class UserError extends Error {}
|
|
7
|
+
|
|
8
|
+
export function relativePath(value, { allowRoot = false } = {}) {
|
|
9
|
+
if (allowRoot && (value === '' || value === '.')) return '';
|
|
10
|
+
if (typeof value !== 'string' || !value || value.startsWith('/') || value.includes('\\') || /[\x00-\x1f\x7f]/u.test(value)) {
|
|
11
|
+
throw new UserError('Use a relative POSIX path without control characters.');
|
|
12
|
+
}
|
|
13
|
+
const parts = value.split('/');
|
|
14
|
+
if (parts.some(part => !part || part === '.' || part === '..' || part.trim() !== part)) {
|
|
15
|
+
throw new UserError('Path contains an empty, dot, parent, or padded component.');
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function excluded(value, extra = []) {
|
|
21
|
+
const lower = value.toLowerCase();
|
|
22
|
+
const parts = lower.split('/');
|
|
23
|
+
if (parts.some(part => part === '.env' || part.startsWith('.env.'))) return true;
|
|
24
|
+
return [...DEFAULT_EXCLUDES, ...extra].some(item => {
|
|
25
|
+
const rule = item.toLowerCase();
|
|
26
|
+
return rule.includes('/') ? lower === rule || lower.startsWith(`${rule}/`) : parts.includes(rule);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function safePath(value, extra = [], options = {}) {
|
|
31
|
+
const relative = relativePath(value, options);
|
|
32
|
+
if (relative && excluded(relative, extra)) throw new UserError('This path is excluded by the workspace policy.');
|
|
33
|
+
return relative;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function localPath(root, relative) {
|
|
37
|
+
const base = await fs.realpath(root);
|
|
38
|
+
const parts = relative.split('/');
|
|
39
|
+
let current = base;
|
|
40
|
+
for (const part of parts) {
|
|
41
|
+
current = path.join(current, part);
|
|
42
|
+
const stat = await fs.lstat(current).catch(error => {
|
|
43
|
+
if (error.code === 'ENOENT') return null;
|
|
44
|
+
throw error;
|
|
45
|
+
});
|
|
46
|
+
if (stat?.isSymbolicLink()) throw new UserError('Local symlink paths are not allowed.');
|
|
47
|
+
}
|
|
48
|
+
if (!current.startsWith(base + path.sep)) throw new UserError('Path escapes the local root.');
|
|
49
|
+
return current;
|
|
50
|
+
}
|
package/src/server.js
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { McpServer } from '@modelcontextprotocol/server';
|
|
3
|
+
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import * as z from 'zod/v4';
|
|
7
|
+
import { loadConfig } from './config.js';
|
|
8
|
+
import { UserError } from './paths.js';
|
|
9
|
+
import { FtpWorkspace } from './workspace.js';
|
|
10
|
+
|
|
11
|
+
function result(value) { return { content: [{ type: 'text', text: JSON.stringify(value) }] }; }
|
|
12
|
+
function tool(fn) {
|
|
13
|
+
return async args => {
|
|
14
|
+
try { return result(await fn(args)); }
|
|
15
|
+
catch (error) {
|
|
16
|
+
const message = error instanceof UserError ? error.message : 'Remote operation failed. Check connectivity and server settings.';
|
|
17
|
+
return { content: [{ type: 'text', text: message }], isError: true };
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function createServer(workspace) {
|
|
23
|
+
const server = new McpServer({ name: 'ftp-workspace-mcp', version: '0.2.1' }, {
|
|
24
|
+
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
|
+
});
|
|
26
|
+
server.registerTool('remote_list', {
|
|
27
|
+
description: 'List up to 200 allowed entries in one remote directory. Use an empty path for the configured root.',
|
|
28
|
+
inputSchema: z.object({ path: z.string().default('') }),
|
|
29
|
+
annotations: { readOnlyHint: true }
|
|
30
|
+
}, tool(({ path }) => workspace.list(path)));
|
|
31
|
+
server.registerTool('remote_download', {
|
|
32
|
+
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: z.string(), expectedLocalSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }),
|
|
34
|
+
annotations: { readOnlyHint: false }
|
|
35
|
+
}, tool(({ path, expectedLocalSha256 }) => workspace.download(path, expectedLocalSha256)));
|
|
36
|
+
server.registerTool('remote_preview_upload', {
|
|
37
|
+
description: 'Compare one local file with its remote counterpart and issue a short-lived token if upload is needed.',
|
|
38
|
+
inputSchema: z.object({ path: z.string() }),
|
|
39
|
+
annotations: { readOnlyHint: true }
|
|
40
|
+
}, tool(({ path }) => workspace.previewUpload(path)));
|
|
41
|
+
server.registerTool('remote_upload', {
|
|
42
|
+
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: z.string(), uploadToken: z.string().uuid() }),
|
|
44
|
+
annotations: { readOnlyHint: false, destructiveHint: true }
|
|
45
|
+
}, tool(({ path, uploadToken }) => workspace.upload(path, uploadToken)));
|
|
46
|
+
return server;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
|
|
50
|
+
try {
|
|
51
|
+
const workspace = new FtpWorkspace(loadConfig());
|
|
52
|
+
await serveStdio(() => createServer(workspace));
|
|
53
|
+
} catch (error) {
|
|
54
|
+
console.error(error instanceof UserError ? error.message : 'Failed to start remote MCP server.');
|
|
55
|
+
process.exitCode = 1;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { Client as FtpClient, FileType } from 'basic-ftp';
|
|
6
|
+
import SftpClient from 'ssh2-sftp-client';
|
|
7
|
+
import { UserError } from './paths.js';
|
|
8
|
+
|
|
9
|
+
export class FtpTransport {
|
|
10
|
+
constructor(config, client = new FtpClient(30_000)) {
|
|
11
|
+
this.config = config;
|
|
12
|
+
this.client = client;
|
|
13
|
+
}
|
|
14
|
+
async access() {
|
|
15
|
+
await this.client.access({
|
|
16
|
+
host: this.config.host, port: this.config.port, user: this.config.user,
|
|
17
|
+
password: this.config.password, secure: this.config.secure
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async cd(root) { await this.client.cd(root); }
|
|
21
|
+
async list(relative) { return this.client.list(relative); }
|
|
22
|
+
async downloadTo(local, relative) { await this.client.downloadTo(local, relative); }
|
|
23
|
+
async uploadFrom(data, relative) { await this.client.uploadFrom(Readable.from([data]), relative); }
|
|
24
|
+
async rename(from, to, replace) {
|
|
25
|
+
if (!replace) {
|
|
26
|
+
await this.client.rename(from, to);
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
// FTP RNTO often refuses an existing destination. Keep the original under
|
|
30
|
+
// a backup name until the staged file takes its place.
|
|
31
|
+
const parent = path.posix.dirname(to);
|
|
32
|
+
const backup = path.posix.join(parent === '.' ? '' : parent, `.mcp-backup-${randomUUID()}.tmp`);
|
|
33
|
+
await this.client.rename(to, backup);
|
|
34
|
+
try {
|
|
35
|
+
await this.client.rename(from, to);
|
|
36
|
+
} catch (error) {
|
|
37
|
+
try { await this.client.rename(backup, to); }
|
|
38
|
+
catch { throw new UserError(`Upload replacement failed; original may remain at ${backup}.`); }
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
try { await this.client.remove(backup); }
|
|
42
|
+
catch { return `Upload succeeded, but the previous version remains at ${backup}; remove it manually.`; }
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
async remove(relative) { await this.client.remove(relative); }
|
|
46
|
+
async close() { this.client.close(); }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class SftpTransport {
|
|
50
|
+
constructor(config, client = new SftpClient()) {
|
|
51
|
+
this.config = config;
|
|
52
|
+
this.client = client;
|
|
53
|
+
this.root = null;
|
|
54
|
+
}
|
|
55
|
+
async access() {
|
|
56
|
+
const config = {
|
|
57
|
+
host: this.config.host, port: this.config.port, username: this.config.user,
|
|
58
|
+
readyTimeout: 30_000,
|
|
59
|
+
hostVerifier: key => createHash('sha256').update(key).digest('base64').replace(/=+$/u, '') === this.config.sftpHostKeySha256
|
|
60
|
+
};
|
|
61
|
+
if (this.config.password) config.password = this.config.password;
|
|
62
|
+
if (this.config.sftpPrivateKeyFile) {
|
|
63
|
+
config.privateKey = await fs.readFile(this.config.sftpPrivateKeyFile);
|
|
64
|
+
if (this.config.sftpPassphrase) config.passphrase = this.config.sftpPassphrase;
|
|
65
|
+
}
|
|
66
|
+
await this.client.connect(config);
|
|
67
|
+
}
|
|
68
|
+
async cd(root) {
|
|
69
|
+
if (await this.client.exists(root) !== 'd') throw new UserError('Remote root is not a directory.');
|
|
70
|
+
this.root = root;
|
|
71
|
+
}
|
|
72
|
+
remote(relative) {
|
|
73
|
+
if (!this.root) throw new Error('SFTP root is not set.');
|
|
74
|
+
return path.posix.join(this.root, relative);
|
|
75
|
+
}
|
|
76
|
+
async list(relative) {
|
|
77
|
+
return (await this.client.list(this.remote(relative))).map(item => ({
|
|
78
|
+
name: item.name,
|
|
79
|
+
type: item.type === 'd' ? FileType.Directory : item.type === '-' ? FileType.File : FileType.SymbolicLink,
|
|
80
|
+
size: item.size,
|
|
81
|
+
modifiedAt: item.modifyTime ? new Date(item.modifyTime) : undefined
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
async downloadTo(local, relative) { await this.client.get(this.remote(relative), local); }
|
|
85
|
+
async uploadFrom(data, relative) { await this.client.put(data, this.remote(relative)); }
|
|
86
|
+
async rename(from, to, replace) {
|
|
87
|
+
if (replace) await this.client.posixRename(this.remote(from), this.remote(to));
|
|
88
|
+
else await this.client.rename(this.remote(from), this.remote(to));
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
async remove(relative) { await this.client.delete(this.remote(relative), true); }
|
|
92
|
+
async close() { await this.client.end(); }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function createTransport(config) {
|
|
96
|
+
return config.protocol === 'sftp' ? new SftpTransport(config) : new FtpTransport(config);
|
|
97
|
+
}
|
package/src/workspace.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Writable } from 'node:stream';
|
|
5
|
+
import { FileType } from 'basic-ftp';
|
|
6
|
+
import { localPath, safePath, UserError } from './paths.js';
|
|
7
|
+
import { createTransport } from './transports.js';
|
|
8
|
+
|
|
9
|
+
const sha256 = data => createHash('sha256').update(data).digest('hex');
|
|
10
|
+
|
|
11
|
+
export class FtpWorkspace {
|
|
12
|
+
constructor(config, clientFactory = () => createTransport(config)) {
|
|
13
|
+
this.config = config;
|
|
14
|
+
this.clientFactory = clientFactory;
|
|
15
|
+
this.previews = new Map();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async withClient(action) {
|
|
19
|
+
const client = this.clientFactory();
|
|
20
|
+
try {
|
|
21
|
+
await client.access();
|
|
22
|
+
await client.cd(this.config.remoteRoot);
|
|
23
|
+
return await action(client);
|
|
24
|
+
} finally {
|
|
25
|
+
// Closing a connection cannot undo a completed transfer. Do not turn a
|
|
26
|
+
// successful upload into a failure that prompts an unsafe retry.
|
|
27
|
+
try { await client.close(); }
|
|
28
|
+
catch { /* The operation result is more useful than a close error. */ }
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async entry(client, relative) {
|
|
33
|
+
const parts = relative.split('/');
|
|
34
|
+
for (let i = 0; i < parts.length; i++) {
|
|
35
|
+
const parent = parts.slice(0, i).join('/') || '.';
|
|
36
|
+
const entries = await client.list(parent);
|
|
37
|
+
const found = entries.find(item => item.name === parts[i]);
|
|
38
|
+
if (!found) {
|
|
39
|
+
if (i === parts.length - 1) return null;
|
|
40
|
+
throw new UserError('Remote parent directory does not exist.');
|
|
41
|
+
}
|
|
42
|
+
if (found.type === FileType.SymbolicLink) throw new UserError('Remote symlink paths are not allowed.');
|
|
43
|
+
if (i < parts.length - 1 && found.type !== FileType.Directory) throw new UserError('Remote parent is not a directory.');
|
|
44
|
+
if (i === parts.length - 1) return found;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async list(relative = '') {
|
|
49
|
+
relative = safePath(relative, this.config.extra, { allowRoot: true });
|
|
50
|
+
return this.withClient(async client => {
|
|
51
|
+
if (relative) {
|
|
52
|
+
const entry = await this.entry(client, relative);
|
|
53
|
+
if (!entry || entry.type !== FileType.Directory) throw new UserError('Remote directory does not exist.');
|
|
54
|
+
}
|
|
55
|
+
const entries = await client.list(relative || '.');
|
|
56
|
+
return entries.filter(item => !item.name.includes('/') && !safeExcluded(relative, item.name, this.config.extra) && item.type !== FileType.SymbolicLink)
|
|
57
|
+
.slice(0, 200).map(item => ({ name: item.name, type: item.type === FileType.Directory ? 'directory' : 'file', size: item.size, modifiedAt: item.modifiedAt?.toISOString() ?? null }));
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async readRemote(client, relative) {
|
|
62
|
+
const entry = await this.entry(client, relative);
|
|
63
|
+
if (!entry) return null;
|
|
64
|
+
if (entry.type !== FileType.File) throw new UserError('Remote path is not a regular file.');
|
|
65
|
+
if (entry.size > this.config.maxBytes) throw new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.');
|
|
66
|
+
const chunks = [];
|
|
67
|
+
let bytes = 0;
|
|
68
|
+
const limit = this.config.maxBytes;
|
|
69
|
+
const sink = new Writable({
|
|
70
|
+
write(chunk, _encoding, callback) {
|
|
71
|
+
bytes += chunk.length;
|
|
72
|
+
if (bytes > limit) return callback(new UserError('Remote file exceeds REMOTE_MAX_FILE_BYTES.'));
|
|
73
|
+
chunks.push(chunk);
|
|
74
|
+
callback();
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
await client.downloadTo(sink, relative);
|
|
78
|
+
return Buffer.concat(chunks, bytes);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async localFile(relative) {
|
|
82
|
+
const file = await localPath(this.config.localRoot, relative);
|
|
83
|
+
const stat = await fs.stat(file).catch(error => {
|
|
84
|
+
if (error.code === 'ENOENT') return null;
|
|
85
|
+
throw error;
|
|
86
|
+
});
|
|
87
|
+
if (!stat) return { file, data: null };
|
|
88
|
+
if (!stat.isFile()) throw new UserError('Local path is not a regular file.');
|
|
89
|
+
if (stat.size > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
|
|
90
|
+
const data = await fs.readFile(file);
|
|
91
|
+
if (data.length > this.config.maxBytes) throw new UserError('Local file exceeds REMOTE_MAX_FILE_BYTES.');
|
|
92
|
+
return { file, data };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async download(relative, expectedLocalSha256) {
|
|
96
|
+
relative = safePath(relative, this.config.extra);
|
|
97
|
+
return this.withClient(async client => {
|
|
98
|
+
const remote = await this.readRemote(client, relative);
|
|
99
|
+
if (!remote) throw new UserError('Remote file does not exist.');
|
|
100
|
+
const local = await this.localFile(relative);
|
|
101
|
+
const remoteSha256 = sha256(remote);
|
|
102
|
+
const localSha256 = local.data === null ? null : sha256(local.data);
|
|
103
|
+
if (localSha256 === remoteSha256) return { path: relative, status: 'unchanged', sha256: remoteSha256, bytes: remote.length };
|
|
104
|
+
if (localSha256 !== null && expectedLocalSha256 !== localSha256) {
|
|
105
|
+
throw new UserError(`Local file differs. Its SHA-256 is ${localSha256}; supply expectedLocalSha256 to replace it.`);
|
|
106
|
+
}
|
|
107
|
+
await fs.mkdir(path.dirname(local.file), { recursive: true });
|
|
108
|
+
await localPath(this.config.localRoot, relative);
|
|
109
|
+
const temp = `${local.file}.${randomUUID()}.tmp`;
|
|
110
|
+
try {
|
|
111
|
+
await fs.writeFile(temp, remote, { flag: 'wx' });
|
|
112
|
+
const latest = await this.localFile(relative);
|
|
113
|
+
if ((latest.data === null ? null : sha256(latest.data)) !== localSha256) {
|
|
114
|
+
throw new UserError('Local file changed during download; retry after reviewing it.');
|
|
115
|
+
}
|
|
116
|
+
await fs.rename(temp, local.file);
|
|
117
|
+
} finally {
|
|
118
|
+
await fs.rm(temp, { force: true });
|
|
119
|
+
}
|
|
120
|
+
return { path: relative, status: 'downloaded', sha256: remoteSha256, bytes: remote.length };
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async previewUpload(relative) {
|
|
125
|
+
relative = safePath(relative, this.config.extra);
|
|
126
|
+
const local = await this.localFile(relative);
|
|
127
|
+
if (!local.data) throw new UserError('Local file does not exist.');
|
|
128
|
+
return this.withClient(async client => {
|
|
129
|
+
const remote = await this.readRemote(client, relative);
|
|
130
|
+
const localSha256 = sha256(local.data);
|
|
131
|
+
const remoteSha256 = remote === null ? null : sha256(remote);
|
|
132
|
+
const changed = localSha256 !== remoteSha256;
|
|
133
|
+
const token = changed ? randomUUID() : null;
|
|
134
|
+
if (token) {
|
|
135
|
+
if (this.previews.size >= 100) this.previews.delete(this.previews.keys().next().value);
|
|
136
|
+
this.previews.set(token, { relative, localSha256, remoteSha256, expires: Date.now() + 10 * 60_000 });
|
|
137
|
+
}
|
|
138
|
+
return { path: relative, changed, localSha256, remoteSha256, localBytes: local.data.length, remoteBytes: remote?.length ?? null, uploadToken: token };
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async upload(relative, token) {
|
|
143
|
+
relative = safePath(relative, this.config.extra);
|
|
144
|
+
const preview = this.previews.get(token);
|
|
145
|
+
if (!preview || preview.relative !== relative || preview.expires < Date.now()) throw new UserError('Run remote_preview_upload again; its token is missing or expired.');
|
|
146
|
+
this.previews.delete(token);
|
|
147
|
+
const local = await this.localFile(relative);
|
|
148
|
+
if (!local.data || sha256(local.data) !== preview.localSha256) throw new UserError('Local file changed since the preview.');
|
|
149
|
+
return this.withClient(async client => {
|
|
150
|
+
const remote = await this.readRemote(client, relative);
|
|
151
|
+
if ((remote === null ? null : sha256(remote)) !== preview.remoteSha256) throw new UserError('Remote file changed since the preview.');
|
|
152
|
+
const parent = path.posix.dirname(relative);
|
|
153
|
+
const staged = path.posix.join(parent === '.' ? '' : parent, `.mcp-upload-${randomUUID()}.tmp`);
|
|
154
|
+
let committed = false;
|
|
155
|
+
let stageAttempted = false;
|
|
156
|
+
let warning = null;
|
|
157
|
+
try {
|
|
158
|
+
stageAttempted = true;
|
|
159
|
+
await client.uploadFrom(local.data, staged);
|
|
160
|
+
const stagedData = await this.readRemote(client, staged);
|
|
161
|
+
if (!stagedData || sha256(stagedData) !== preview.localSha256) throw new UserError('Staged upload verification failed.');
|
|
162
|
+
const latestLocal = await this.localFile(relative);
|
|
163
|
+
if (!latestLocal.data || sha256(latestLocal.data) !== preview.localSha256) throw new UserError('Local file changed during upload.');
|
|
164
|
+
const latestRemote = await this.readRemote(client, relative);
|
|
165
|
+
if ((latestRemote === null ? null : sha256(latestRemote)) !== preview.remoteSha256) throw new UserError('Remote file changed during upload.');
|
|
166
|
+
warning = await client.rename(staged, relative, latestRemote !== null);
|
|
167
|
+
committed = true;
|
|
168
|
+
} finally {
|
|
169
|
+
if (!committed && stageAttempted) {
|
|
170
|
+
try {
|
|
171
|
+
if (await this.entry(client, staged)) await client.remove(staged);
|
|
172
|
+
}
|
|
173
|
+
catch { throw new UserError(`Upload failed and temporary remote file may remain at ${staged}.`); }
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
let uploaded;
|
|
177
|
+
try { uploaded = await this.readRemote(client, relative); }
|
|
178
|
+
catch { throw new UserError('Upload rename completed, but verification failed; inspect the remote file before retrying.'); }
|
|
179
|
+
if (!uploaded || sha256(uploaded) !== preview.localSha256) throw new UserError('Upload verification failed; inspect the remote file before retrying.');
|
|
180
|
+
return { path: relative, status: 'uploaded', sha256: preview.localSha256, bytes: local.data.length, ...(warning ? { warning } : {}) };
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function safeExcluded(parent, name, extra) {
|
|
186
|
+
try {
|
|
187
|
+
safePath(parent ? `${parent}/${name}` : name, extra);
|
|
188
|
+
return false;
|
|
189
|
+
} catch {
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
}
|