@jwjp/ftp-mcp 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 { fileURLToPath } from 'node:url';
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
- function tool(fn) {
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
- const message = error instanceof UserError ? error.message : 'Remote operation failed. Check connectivity and server settings.';
17
- return { content: [{ type: 'text', text: message }], isError: true };
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: '0.2.1' }, {
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: '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('') }),
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: z.string(), expectedLocalSha256: z.string().regex(/^[a-f0-9]{64}$/).optional() }),
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: z.string() }),
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: z.string(), uploadToken: z.string().uuid() }),
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] && fileURLToPath(import.meta.url) === path.resolve(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 workspace = new FtpWorkspace(loadConfig());
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: this.config.host, port: this.config.port, user: this.config.user,
17
- password: this.config.password, secure: this.config.secure
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(data, relative) { await this.client.uploadFrom(Readable.from([data]), relative); }
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
- try { await this.client.rename(backup, to); }
38
- catch { throw new UserError(`Upload replacement failed; original may remain at ${backup}.`); }
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
- try { await this.client.remove(backup); }
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
- constructor(config, client = new SftpClient()) {
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: 30_000,
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
- return (await this.client.list(this.remote(relative))).map(item => ({
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) { await this.client.get(this.remote(relative), local); }
85
- async uploadFrom(data, relative) { await this.client.put(data, this.remote(relative)); }
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
- if (replace) await this.client.posixRename(this.remote(from), this.remote(to));
88
- else await this.client.rename(this.remote(from), this.remote(to));
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() { await this.client.end(); }
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) {