@yawlabs/ssh-mcp 0.1.0 → 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/dist/index.js CHANGED
@@ -10,16 +10,22 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
10
  import { z } from "zod";
11
11
 
12
12
  // src/diagnose.ts
13
- import { execSync } from "child_process";
14
- import { existsSync, readFileSync } from "fs";
13
+ import { execFileSync } from "child_process";
14
+ import { existsSync, readFileSync, readdirSync } from "fs";
15
15
  import { homedir } from "os";
16
16
  import { join } from "path";
17
- function run(cmd) {
17
+ function isValidHostname(host) {
18
+ return /^[a-zA-Z0-9._\-:[\]]+$/.test(host) && host.length <= 253;
19
+ }
20
+ function runArgs(cmd, args) {
18
21
  try {
19
- const stdout = execSync(cmd, { encoding: "utf8", timeout: 1e4, stdio: ["pipe", "pipe", "pipe"] });
22
+ const stdout = execFileSync(cmd, args, { encoding: "utf8", timeout: 1e4, stdio: ["pipe", "pipe", "pipe"] });
20
23
  return { stdout: stdout.trim(), ok: true };
21
24
  } catch (e) {
22
- return { stdout: e.stdout?.toString().trim() || e.message || "", ok: false };
25
+ const stdout = e.stdout?.toString().trim() || "";
26
+ const stderr = e.stderr?.toString().trim() || "";
27
+ const output = [stdout, stderr].filter(Boolean).join("\n") || e.message || "";
28
+ return { stdout: output, ok: false };
23
29
  }
24
30
  }
25
31
  function checkSshAgent() {
@@ -30,7 +36,7 @@ function checkSshAgent() {
30
36
  message: "SSH_AUTH_SOCK is not set. ssh-agent is not running or not exported to this shell."
31
37
  };
32
38
  }
33
- const { stdout, ok } = run("ssh-add -l");
39
+ const { stdout, ok } = runArgs("ssh-add", ["-l"]);
34
40
  if (!ok && stdout.includes("Could not open a connection")) {
35
41
  return {
36
42
  status: "error",
@@ -61,8 +67,9 @@ function checkSshKeys() {
61
67
  }
62
68
  }
63
69
  try {
64
- const { stdout } = run(`ls "${sshDir}"`);
65
- const allFiles = stdout.split("\n").filter((f) => !f.endsWith(".pub") && !["known_hosts", "config", "authorized_keys"].includes(f));
70
+ const allFiles = readdirSync(sshDir).filter(
71
+ (f) => !f.endsWith(".pub") && !["known_hosts", "known_hosts.old", "config", "authorized_keys"].includes(f)
72
+ );
66
73
  for (const f of allFiles) {
67
74
  if (!keyTypes.includes(f) && existsSync(join(sshDir, f))) {
68
75
  try {
@@ -92,19 +99,35 @@ function checkKnownHosts(host) {
92
99
  message: "~/.ssh/known_hosts does not exist. First connection to any host will prompt for verification."
93
100
  };
94
101
  }
95
- const { stdout, ok } = run(`ssh-keygen -F "${host}"`);
102
+ if (!isValidHostname(host)) {
103
+ return { status: "error", message: `Invalid hostname: "${host}"` };
104
+ }
105
+ const { stdout, ok } = runArgs("ssh-keygen", ["-F", host]);
96
106
  if (!ok || !stdout.trim()) {
97
107
  return {
98
108
  status: "warning",
99
- message: `Host "${host}" is not in known_hosts. First connection will prompt for host key verification. To add it: ssh-keyscan -H ${host} >> ~/.ssh/known_hosts`
109
+ message: `Host "${host}" is not in known_hosts. First connection will prompt for host key verification. To add it: ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts`
100
110
  };
101
111
  }
102
112
  return { status: "ok", message: `Host "${host}" found in known_hosts` };
103
113
  }
104
114
  function checkConnectivity(host, port = 22) {
105
- const { ok, stdout } = run(
106
- `ssh -o ConnectTimeout=5 -o BatchMode=yes -o StrictHostKeyChecking=no -p ${port} ${host} echo SSH_OK 2>&1`
107
- );
115
+ if (!isValidHostname(host)) {
116
+ return { status: "error", message: `Invalid hostname: "${host}"` };
117
+ }
118
+ const { ok, stdout } = runArgs("ssh", [
119
+ "-o",
120
+ "ConnectTimeout=5",
121
+ "-o",
122
+ "BatchMode=yes",
123
+ "-o",
124
+ "StrictHostKeyChecking=no",
125
+ "-p",
126
+ String(port),
127
+ host,
128
+ "echo",
129
+ "SSH_OK"
130
+ ]);
108
131
  if (ok && stdout.includes("SSH_OK")) {
109
132
  return { status: "ok", message: `SSH connection to ${host}:${port} succeeded` };
110
133
  }
@@ -129,7 +152,7 @@ function checkConnectivity(host, port = 22) {
129
152
  if (stdout.includes("Host key verification failed")) {
130
153
  return {
131
154
  status: "error",
132
- message: `Host key verification failed for ${host}. The host key changed (instance recreated?). Fix: ssh-keygen -R ${host} && ssh-keyscan -H ${host} >> ~/.ssh/known_hosts`
155
+ message: `Host key verification failed for ${host}. The host key changed (instance recreated?). Fix: ssh-keygen -R "${host}" && ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts`
133
156
  };
134
157
  }
135
158
  if (stdout.includes("Could not resolve hostname")) {
@@ -153,8 +176,16 @@ function checkSshConfig(host) {
153
176
  for (const line of lines) {
154
177
  const trimmed = line.trim();
155
178
  if (/^Host\s+/i.test(trimmed)) {
156
- const pattern = trimmed.replace(/^Host\s+/i, "").trim();
157
- inHostBlock = pattern === host || pattern === "*";
179
+ const patterns = trimmed.replace(/^Host\s+/i, "").trim().split(/\s+/);
180
+ inHostBlock = patterns.some((p) => {
181
+ if (p === "*") return true;
182
+ if (p === host) return true;
183
+ if (p.includes("*")) {
184
+ const regex = new RegExp("^" + p.replace(/\./g, "\\.").replace(/\*/g, ".*") + "$");
185
+ return regex.test(host);
186
+ }
187
+ return false;
188
+ });
158
189
  if (inHostBlock) hostConfig.push(trimmed);
159
190
  } else if (inHostBlock && trimmed) {
160
191
  hostConfig.push(trimmed);
@@ -174,6 +205,13 @@ ${hostConfig.join("\n")}` };
174
205
  function diagnose(host, port = 22) {
175
206
  const checks = [];
176
207
  const suggestions = [];
208
+ if (!isValidHostname(host)) {
209
+ return {
210
+ overall: "error",
211
+ checks: [{ name: "Input Validation", status: "error", message: `Invalid hostname: "${host}"` }],
212
+ suggestions: ["Provide a valid hostname (alphanumeric, dots, hyphens, colons, brackets only)"]
213
+ };
214
+ }
177
215
  const agent = checkSshAgent();
178
216
  checks.push({ name: "SSH Agent", ...agent });
179
217
  if (agent.status === "error") suggestions.push('Start ssh-agent: eval "$(ssh-agent -s)"');
@@ -185,12 +223,12 @@ function diagnose(host, port = 22) {
185
223
  checks.push({ name: "SSH Config", ...config });
186
224
  const known = checkKnownHosts(host);
187
225
  checks.push({ name: "Known Hosts", ...known });
188
- if (known.status === "warning") suggestions.push(`Add host key: ssh-keyscan -H ${host} >> ~/.ssh/known_hosts`);
226
+ if (known.status === "warning") suggestions.push(`Add host key: ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts`);
189
227
  const conn = checkConnectivity(host, port);
190
228
  checks.push({ name: "Connectivity", ...conn });
191
229
  if (conn.status === "error" && conn.message.includes("Host key verification")) {
192
- suggestions.push(`Remove stale host key: ssh-keygen -R ${host}`);
193
- suggestions.push(`Re-add host key: ssh-keyscan -H ${host} >> ~/.ssh/known_hosts`);
230
+ suggestions.push(`Remove stale host key: ssh-keygen -R "${host}"`);
231
+ suggestions.push(`Re-add host key: ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts`);
194
232
  }
195
233
  if (conn.status === "error" && conn.message.includes("Permission denied")) {
196
234
  suggestions.push("Check loaded keys: ssh-add -l");
@@ -200,10 +238,287 @@ function diagnose(host, port = 22) {
200
238
  return { overall, checks, suggestions };
201
239
  }
202
240
 
203
- // src/ssh.ts
204
- import { readFileSync as readFileSync2 } from "fs";
241
+ // src/env.ts
242
+ import { appendFileSync, existsSync as existsSync2, readFileSync as readFileSync2, readdirSync as readdirSync2, statSync } from "fs";
205
243
  import { homedir as homedir2 } from "os";
206
244
  import { join as join2 } from "path";
245
+ function ensureAgent() {
246
+ const sock = process.env.SSH_AUTH_SOCK;
247
+ if (sock) {
248
+ const { stdout: stdout2, ok: ok2 } = runArgs("ssh-add", ["-l"]);
249
+ const noIdentities = stdout2.includes("no identities") || stdout2.includes("The agent has no identities");
250
+ if (ok2 || noIdentities) {
251
+ const keys = ok2 && !noIdentities ? stdout2.split("\n").filter(Boolean) : [];
252
+ return {
253
+ running: true,
254
+ reachable: true,
255
+ socket: sock,
256
+ keys,
257
+ started: false,
258
+ message: keys.length > 0 ? `ssh-agent running with ${keys.length} key(s) loaded` : "ssh-agent running but no keys loaded. Use ssh_key_load to add one."
259
+ };
260
+ }
261
+ }
262
+ const { stdout, ok } = runArgs("ssh-agent", ["-s"]);
263
+ if (ok) {
264
+ const sockMatch = stdout.match(/SSH_AUTH_SOCK=([^;]+)/);
265
+ const pidMatch = stdout.match(/SSH_AGENT_PID=([^;]+)/);
266
+ if (sockMatch) {
267
+ process.env.SSH_AUTH_SOCK = sockMatch[1];
268
+ if (pidMatch) process.env.SSH_AGENT_PID = pidMatch[1];
269
+ return {
270
+ running: true,
271
+ reachable: true,
272
+ socket: sockMatch[1],
273
+ keys: [],
274
+ started: true,
275
+ env: { SSH_AUTH_SOCK: sockMatch[1], SSH_AGENT_PID: pidMatch?.[1] },
276
+ message: "Started new ssh-agent. No keys loaded yet \u2014 use ssh_key_load to add one."
277
+ };
278
+ }
279
+ }
280
+ return {
281
+ running: false,
282
+ reachable: false,
283
+ keys: [],
284
+ started: false,
285
+ message: 'Could not start ssh-agent. Run manually: eval "$(ssh-agent -s)"'
286
+ };
287
+ }
288
+ function detectKeyType(filePath, fileName) {
289
+ const pubPath = `${filePath}.pub`;
290
+ if (existsSync2(pubPath)) {
291
+ try {
292
+ const pub = readFileSync2(pubPath, "utf8");
293
+ if (pub.includes("ssh-ed25519")) return "ed25519";
294
+ if (pub.includes("ssh-rsa")) return "rsa";
295
+ if (pub.includes("ecdsa")) return "ecdsa";
296
+ if (pub.includes("ssh-dss")) return "dsa";
297
+ } catch {
298
+ }
299
+ }
300
+ if (fileName.includes("ed25519")) return "ed25519";
301
+ if (fileName.includes("rsa")) return "rsa";
302
+ if (fileName.includes("ecdsa")) return "ecdsa";
303
+ if (fileName.includes("dsa")) return "dsa";
304
+ try {
305
+ const content = readFileSync2(filePath, "utf8");
306
+ if (content.includes("RSA PRIVATE KEY")) return "rsa";
307
+ if (content.includes("EC PRIVATE KEY")) return "ecdsa";
308
+ if (content.includes("DSA PRIVATE KEY")) return "dsa";
309
+ } catch {
310
+ }
311
+ return "unknown";
312
+ }
313
+ function listSshKeys() {
314
+ const sshDir = join2(homedir2(), ".ssh");
315
+ if (!existsSync2(sshDir)) return [];
316
+ const loadedFingerprints = /* @__PURE__ */ new Set();
317
+ const { stdout: agentOut, ok: agentOk } = runArgs("ssh-add", ["-l"]);
318
+ if (agentOk && !agentOut.includes("no identities")) {
319
+ for (const line of agentOut.split("\n").filter(Boolean)) {
320
+ const match = line.match(/(\S+:\S+)/);
321
+ if (match) loadedFingerprints.add(match[1]);
322
+ }
323
+ }
324
+ const skipFiles = /* @__PURE__ */ new Set(["known_hosts", "known_hosts.old", "config", "authorized_keys", "environment"]);
325
+ const keys = [];
326
+ let files;
327
+ try {
328
+ files = readdirSync2(sshDir);
329
+ } catch {
330
+ return [];
331
+ }
332
+ for (const file of files) {
333
+ if (file.endsWith(".pub") || file.startsWith(".") || skipFiles.has(file)) continue;
334
+ const filePath = join2(sshDir, file);
335
+ try {
336
+ const stat = statSync(filePath);
337
+ if (!stat.isFile()) continue;
338
+ const content = readFileSync2(filePath, "utf8");
339
+ if (!content.includes("PRIVATE KEY")) continue;
340
+ const type = detectKeyType(filePath, file);
341
+ let fingerprint;
342
+ const { stdout: fpOut, ok: fpOk } = runArgs("ssh-keygen", ["-lf", filePath]);
343
+ if (fpOk) {
344
+ const match = fpOut.match(/(\S+:\S+)/);
345
+ fingerprint = match?.[1];
346
+ }
347
+ const loadedInAgent = fingerprint ? loadedFingerprints.has(fingerprint) : false;
348
+ keys.push({ name: file, path: filePath, type, fingerprint, loadedInAgent });
349
+ } catch {
350
+ }
351
+ }
352
+ return keys;
353
+ }
354
+ function loadKey(keyPath) {
355
+ const agent = ensureAgent();
356
+ if (!agent.reachable) {
357
+ return { status: "error", message: agent.message };
358
+ }
359
+ const resolved = keyPath.startsWith("~") ? join2(homedir2(), keyPath.slice(1)) : keyPath;
360
+ if (!existsSync2(resolved)) {
361
+ return { status: "error", message: `Key not found: ${resolved}` };
362
+ }
363
+ const { stdout, ok } = runArgs("ssh-add", [resolved]);
364
+ if (ok) {
365
+ return { status: "ok", message: `Key loaded: ${resolved}` };
366
+ }
367
+ if (stdout.includes("passphrase") || stdout.includes("incorrect") || stdout.includes("bad permissions")) {
368
+ if (stdout.includes("UNPROTECTED PRIVATE KEY")) {
369
+ return { status: "error", message: `Key ${resolved} has too-open permissions. Fix: chmod 600 ${resolved}` };
370
+ }
371
+ return { status: "error", message: `Key ${resolved} requires a passphrase. Add it manually: ssh-add ${resolved}` };
372
+ }
373
+ return { status: "error", message: `Failed to load key: ${stdout}` };
374
+ }
375
+ function configLookup(host) {
376
+ if (!isValidHostname(host)) {
377
+ return { error: `Invalid hostname: "${host}"` };
378
+ }
379
+ const { stdout, ok } = runArgs("ssh", ["-G", host]);
380
+ if (!ok) {
381
+ return { error: `Failed to resolve SSH config for ${host}: ${stdout}` };
382
+ }
383
+ const all = {};
384
+ const identityFiles = [];
385
+ for (const line of stdout.split("\n")) {
386
+ const spaceIdx = line.indexOf(" ");
387
+ if (spaceIdx > 0) {
388
+ const key = line.substring(0, spaceIdx);
389
+ const value = line.substring(spaceIdx + 1);
390
+ if (key === "identityfile") {
391
+ identityFiles.push(value);
392
+ } else {
393
+ all[key] = value;
394
+ }
395
+ }
396
+ }
397
+ return {
398
+ hostname: all.hostname || host,
399
+ user: all.user || "",
400
+ port: all.port || "22",
401
+ identityFile: identityFiles,
402
+ proxyJump: all.proxyjump !== "none" ? all.proxyjump : void 0,
403
+ proxyCommand: all.proxycommand !== "none" ? all.proxycommand : void 0,
404
+ all,
405
+ raw: stdout
406
+ };
407
+ }
408
+ function fixKnownHosts(host, port = 22) {
409
+ if (!isValidHostname(host)) {
410
+ return { status: "error", message: `Invalid hostname: "${host}"`, actions: [] };
411
+ }
412
+ const actions = [];
413
+ const { ok: removeOk } = runArgs("ssh-keygen", ["-R", host]);
414
+ if (removeOk) {
415
+ actions.push(`Removed old host key for ${host}`);
416
+ }
417
+ if (port !== 22) {
418
+ const { ok } = runArgs("ssh-keygen", ["-R", `[${host}]:${port}`]);
419
+ if (ok) actions.push(`Removed old host key for [${host}]:${port}`);
420
+ }
421
+ const scanArgs = port !== 22 ? ["-H", "-p", String(port), host] : ["-H", host];
422
+ const { stdout: scanOut, ok: scanOk } = runArgs("ssh-keyscan", scanArgs);
423
+ if (scanOk && scanOut.trim()) {
424
+ try {
425
+ const knownHostsPath = join2(homedir2(), ".ssh", "known_hosts");
426
+ appendFileSync(knownHostsPath, `
427
+ ${scanOut.trim()}
428
+ `);
429
+ actions.push(`Added new host key for ${host}`);
430
+ return { status: "ok", message: `Host key refreshed for ${host}`, actions };
431
+ } catch (e) {
432
+ const msg = e instanceof Error ? e.message : String(e);
433
+ return { status: "error", message: `Scanned key but failed to write known_hosts: ${msg}`, actions };
434
+ }
435
+ }
436
+ return { status: "error", message: `Could not scan host key for ${host}. Host may be unreachable.`, actions };
437
+ }
438
+ function checkGitSsh(host = "github.com", user = "git") {
439
+ if (!isValidHostname(host)) {
440
+ return { status: "error", message: `Invalid hostname: "${host}"` };
441
+ }
442
+ const { stdout } = runArgs("ssh", ["-T", "-o", "ConnectTimeout=5", "-o", "BatchMode=yes", `${user}@${host}`]);
443
+ const text = stdout;
444
+ if (text.includes("successfully authenticated") || text.includes("Welcome to GitLab") || text.includes("logged in as")) {
445
+ const userMatch = text.match(/Hi (\S+?)!/) || text.match(/@(\S+?)!/) || text.match(/logged in as (\S+)/);
446
+ return {
447
+ status: "ok",
448
+ message: `Git SSH authentication to ${host} succeeded${userMatch ? ` as ${userMatch[1]}` : ""}`,
449
+ authenticatedAs: userMatch?.[1]
450
+ };
451
+ }
452
+ if (text.includes("Permission denied")) {
453
+ return {
454
+ status: "error",
455
+ message: `Permission denied for ${host}. Either no key is loaded in the agent or your key isn't registered with ${host}. Run ssh_key_list to check, then ssh_key_load if needed.`
456
+ };
457
+ }
458
+ if (text.includes("Connection refused")) {
459
+ return { status: "error", message: `Connection refused by ${host}. SSH may not be available on this host.` };
460
+ }
461
+ if (text.includes("timed out") || text.includes("Connection timed out")) {
462
+ return { status: "error", message: `Connection to ${host} timed out. Check your network or firewall.` };
463
+ }
464
+ if (text.includes("Could not resolve")) {
465
+ return { status: "error", message: `Could not resolve hostname "${host}". Check DNS or spelling.` };
466
+ }
467
+ return { status: "error", message: `Git SSH check for ${host}: ${text || "no response (agent may not be running)"}` };
468
+ }
469
+ function testConnection(host, port = 22) {
470
+ if (!isValidHostname(host)) {
471
+ return { status: "error", message: `Invalid hostname: "${host}"` };
472
+ }
473
+ const start = Date.now();
474
+ const { ok, stdout } = runArgs("ssh", [
475
+ "-o",
476
+ "ConnectTimeout=5",
477
+ "-o",
478
+ "BatchMode=yes",
479
+ "-o",
480
+ "StrictHostKeyChecking=no",
481
+ "-p",
482
+ String(port),
483
+ host,
484
+ "echo",
485
+ "SSH_OK"
486
+ ]);
487
+ const elapsed = Date.now() - start;
488
+ if (ok && stdout.includes("SSH_OK")) {
489
+ return { status: "ok", message: `Connected to ${host}:${port} in ${elapsed}ms` };
490
+ }
491
+ if (stdout.includes("Permission denied")) {
492
+ return {
493
+ status: "error",
494
+ message: `Authentication failed to ${host}:${port} (${elapsed}ms). Key not authorized. Check: ssh-add -l, verify correct username, verify key is in remote authorized_keys.`
495
+ };
496
+ }
497
+ if (stdout.includes("Connection refused")) {
498
+ return {
499
+ status: "error",
500
+ message: `Connection refused at ${host}:${port}. SSH server not running or port blocked.`
501
+ };
502
+ }
503
+ if (stdout.includes("timed out")) {
504
+ return { status: "error", message: `Connection timed out to ${host}:${port}. Host down or firewall blocking.` };
505
+ }
506
+ if (stdout.includes("Host key verification failed")) {
507
+ return {
508
+ status: "error",
509
+ message: `Host key mismatch for ${host}. Instance was likely recreated. Fix with ssh_known_hosts_fix.`
510
+ };
511
+ }
512
+ if (stdout.includes("Could not resolve")) {
513
+ return { status: "error", message: `Could not resolve "${host}". Check DNS, /etc/hosts, or SSH config.` };
514
+ }
515
+ return { status: "error", message: `Connection failed to ${host}:${port}: ${stdout}` };
516
+ }
517
+
518
+ // src/ssh.ts
519
+ import { readFileSync as readFileSync3 } from "fs";
520
+ import { homedir as homedir3 } from "os";
521
+ import { join as join3 } from "path";
207
522
  import { Client } from "ssh2";
208
523
  function resolveConfig(config) {
209
524
  const connectConfig = {
@@ -212,18 +527,18 @@ function resolveConfig(config) {
212
527
  username: config.username || process.env.USER || process.env.USERNAME || "root"
213
528
  };
214
529
  if (config.privateKeyPath) {
215
- connectConfig.privateKey = readFileSync2(config.privateKeyPath);
530
+ connectConfig.privateKey = readFileSync3(config.privateKeyPath);
216
531
  } else if (config.password) {
217
532
  connectConfig.password = config.password;
218
533
  } else if (config.agent || process.env.SSH_AUTH_SOCK) {
219
534
  connectConfig.agent = config.agent || process.env.SSH_AUTH_SOCK;
220
535
  } else {
221
- const home = homedir2();
536
+ const home = homedir3();
222
537
  const defaultKeys = ["id_ed25519", "id_rsa", "id_ecdsa"];
223
538
  for (const keyName of defaultKeys) {
224
- const keyPath = join2(home, ".ssh", keyName);
539
+ const keyPath = join3(home, ".ssh", keyName);
225
540
  try {
226
- connectConfig.privateKey = readFileSync2(keyPath);
541
+ connectConfig.privateKey = readFileSync3(keyPath);
227
542
  break;
228
543
  } catch {
229
544
  }
@@ -231,90 +546,161 @@ function resolveConfig(config) {
231
546
  }
232
547
  return connectConfig;
233
548
  }
549
+ function formatDiagnostics(host) {
550
+ try {
551
+ const checks = [
552
+ { name: "SSH Agent", ...checkSshAgent() },
553
+ { name: "SSH Keys", ...checkSshKeys() },
554
+ { name: "SSH Config", ...checkSshConfig(host) },
555
+ { name: "Known Hosts", ...checkKnownHosts(host) }
556
+ ];
557
+ const parts = [];
558
+ const suggestions = [];
559
+ for (const check of checks) {
560
+ if (check.status !== "ok") {
561
+ parts.push(`[${check.status.toUpperCase()}] ${check.name}: ${check.message}`);
562
+ }
563
+ }
564
+ const agent = checks[0];
565
+ if (agent.status === "error") suggestions.push('Start ssh-agent: eval "$(ssh-agent -s)"');
566
+ if (agent.status === "warning") suggestions.push("Load a key: ssh-add ~/.ssh/id_ed25519");
567
+ const keys = checks[1];
568
+ if (keys.status === "error") suggestions.push('Generate a key: ssh-keygen -t ed25519 -C "your@email.com"');
569
+ const known = checks[3];
570
+ if (known.status === "warning") suggestions.push(`Add host key: ssh-keyscan -H "${host}" >> ~/.ssh/known_hosts`);
571
+ if (suggestions.length > 0) {
572
+ parts.push(`Suggested fixes: ${suggestions.join(" | ")}`);
573
+ }
574
+ return parts.length > 0 ? parts.join("\n") : "";
575
+ } catch {
576
+ return "";
577
+ }
578
+ }
234
579
  function connect(config) {
235
580
  return new Promise((resolve, reject) => {
236
581
  const client = new Client();
237
582
  const connectConfig = resolveConfig(config);
238
- client.on("ready", () => resolve(client)).on("error", (err) => reject(err)).connect(connectConfig);
583
+ client.on("ready", () => resolve(client)).on("error", (err) => {
584
+ const diag = formatDiagnostics(config.host);
585
+ if (diag) {
586
+ const enhanced = new Error(`${err.message}
587
+
588
+ SSH Diagnostics:
589
+ ${diag}`);
590
+ enhanced.cause = err;
591
+ reject(enhanced);
592
+ } else {
593
+ reject(err);
594
+ }
595
+ }).connect(connectConfig);
239
596
  });
240
597
  }
241
598
  function exec(client, command, timeoutMs = 3e4) {
242
599
  return new Promise((resolve, reject) => {
600
+ let settled = false;
601
+ const settle = (fn) => {
602
+ if (settled) return;
603
+ settled = true;
604
+ clearTimeout(timer);
605
+ fn();
606
+ };
243
607
  const timer = setTimeout(() => {
244
- reject(new Error(`Command timed out after ${timeoutMs}ms`));
608
+ settle(() => reject(new Error(`Command timed out after ${timeoutMs}ms`)));
245
609
  }, timeoutMs);
246
610
  client.exec(command, (err, stream) => {
247
611
  if (err) {
248
- clearTimeout(timer);
249
- return reject(err);
612
+ settle(() => reject(err));
613
+ return;
250
614
  }
251
615
  let stdout = "";
252
616
  let stderr = "";
253
617
  stream.on("close", (code) => {
254
- clearTimeout(timer);
255
- resolve({ stdout, stderr, code: code ?? 0 });
618
+ settle(() => resolve({ stdout, stderr, code: code ?? 0 }));
256
619
  }).on("data", (data) => {
257
620
  stdout += data.toString();
258
- }).stderr.on("data", (data) => {
621
+ }).on("error", (err2) => {
622
+ settle(() => reject(err2));
623
+ });
624
+ stream.stderr.on("data", (data) => {
259
625
  stderr += data.toString();
626
+ }).on("error", (err2) => {
627
+ settle(() => reject(err2));
260
628
  });
261
629
  });
262
630
  });
263
631
  }
264
- function readFile(client, remotePath) {
632
+ function getSftp(client) {
265
633
  return new Promise((resolve, reject) => {
266
634
  client.sftp((err, sftp) => {
267
635
  if (err) return reject(err);
268
- sftp.readFile(remotePath, (err2, data) => {
269
- if (err2) return reject(err2);
636
+ resolve(sftp);
637
+ });
638
+ });
639
+ }
640
+ async function readFile(client, remotePath) {
641
+ const sftp = await getSftp(client);
642
+ try {
643
+ return await new Promise((resolve, reject) => {
644
+ sftp.readFile(remotePath, (err, data) => {
645
+ if (err) return reject(err);
270
646
  resolve(data.toString("utf8"));
271
647
  });
272
648
  });
273
- });
649
+ } finally {
650
+ sftp.end();
651
+ }
274
652
  }
275
- function writeFile(client, remotePath, content) {
276
- return new Promise((resolve, reject) => {
277
- client.sftp((err, sftp) => {
278
- if (err) return reject(err);
279
- sftp.writeFile(remotePath, content, (err2) => {
280
- if (err2) return reject(err2);
653
+ async function writeFile(client, remotePath, content) {
654
+ const sftp = await getSftp(client);
655
+ try {
656
+ await new Promise((resolve, reject) => {
657
+ sftp.writeFile(remotePath, content, (err) => {
658
+ if (err) return reject(err);
281
659
  resolve();
282
660
  });
283
661
  });
284
- });
662
+ } finally {
663
+ sftp.end();
664
+ }
285
665
  }
286
- function uploadFile(client, localPath, remotePath) {
287
- return new Promise((resolve, reject) => {
288
- client.sftp((err, sftp) => {
289
- if (err) return reject(err);
290
- sftp.fastPut(localPath, remotePath, (err2) => {
291
- if (err2) return reject(err2);
666
+ async function uploadFile(client, localPath, remotePath) {
667
+ const sftp = await getSftp(client);
668
+ try {
669
+ await new Promise((resolve, reject) => {
670
+ sftp.fastPut(localPath, remotePath, (err) => {
671
+ if (err) return reject(err);
292
672
  resolve();
293
673
  });
294
674
  });
295
- });
675
+ } finally {
676
+ sftp.end();
677
+ }
296
678
  }
297
- function downloadFile(client, remotePath, localPath) {
298
- return new Promise((resolve, reject) => {
299
- client.sftp((err, sftp) => {
300
- if (err) return reject(err);
301
- sftp.fastGet(remotePath, localPath, (err2) => {
302
- if (err2) return reject(err2);
679
+ async function downloadFile(client, remotePath, localPath) {
680
+ const sftp = await getSftp(client);
681
+ try {
682
+ await new Promise((resolve, reject) => {
683
+ sftp.fastGet(remotePath, localPath, (err) => {
684
+ if (err) return reject(err);
303
685
  resolve();
304
686
  });
305
687
  });
306
- });
688
+ } finally {
689
+ sftp.end();
690
+ }
307
691
  }
308
- function listDir(client, remotePath) {
309
- return new Promise((resolve, reject) => {
310
- client.sftp((err, sftp) => {
311
- if (err) return reject(err);
312
- sftp.readdir(remotePath, (err2, list) => {
313
- if (err2) return reject(err2);
692
+ async function listDir(client, remotePath) {
693
+ const sftp = await getSftp(client);
694
+ try {
695
+ return await new Promise((resolve, reject) => {
696
+ sftp.readdir(remotePath, (err, list) => {
697
+ if (err) return reject(err);
314
698
  resolve(list.map((item) => item.filename));
315
699
  });
316
700
  });
317
- });
701
+ } finally {
702
+ sftp.end();
703
+ }
318
704
  }
319
705
 
320
706
  // src/tools.ts
@@ -471,13 +857,141 @@ ${result.stderr}`);
471
857
  return { content: [{ type: "text", text: lines.join("\n") }] };
472
858
  }
473
859
  );
860
+ server.tool(
861
+ "ssh_agent_ensure",
862
+ "Ensure ssh-agent is running and reachable. Starts a new agent if needed and sets environment variables so subsequent SSH operations work. Use this FIRST when SSH operations fail with agent-related errors.",
863
+ {},
864
+ async () => {
865
+ const result = ensureAgent();
866
+ const lines = [];
867
+ lines.push(result.message);
868
+ if (result.socket) lines.push(`Socket: ${result.socket}`);
869
+ if (result.keys.length > 0) {
870
+ lines.push("Loaded keys:");
871
+ for (const k of result.keys) lines.push(` ${k}`);
872
+ }
873
+ if (result.env) {
874
+ lines.push("Environment variables set in this session:");
875
+ if (result.env.SSH_AUTH_SOCK) lines.push(` SSH_AUTH_SOCK=${result.env.SSH_AUTH_SOCK}`);
876
+ if (result.env.SSH_AGENT_PID) lines.push(` SSH_AGENT_PID=${result.env.SSH_AGENT_PID}`);
877
+ }
878
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: !result.reachable };
879
+ }
880
+ );
881
+ server.tool(
882
+ "ssh_key_list",
883
+ "List all SSH private keys in ~/.ssh/ with their type, fingerprint, and whether they are loaded in the agent. Use this to find which keys are available and which ones need to be loaded.",
884
+ {},
885
+ async () => {
886
+ const keys = listSshKeys();
887
+ if (keys.length === 0) {
888
+ return {
889
+ content: [
890
+ {
891
+ type: "text",
892
+ text: 'No SSH private keys found in ~/.ssh/. Generate one: ssh-keygen -t ed25519 -C "your@email.com"'
893
+ }
894
+ ]
895
+ };
896
+ }
897
+ const lines = [`Found ${keys.length} SSH key(s):`, ""];
898
+ for (const key of keys) {
899
+ const status = key.loadedInAgent ? "LOADED" : "not loaded";
900
+ lines.push(`${key.name} (${key.type}) [${status}]`);
901
+ lines.push(` Path: ${key.path}`);
902
+ if (key.fingerprint) lines.push(` Fingerprint: ${key.fingerprint}`);
903
+ lines.push("");
904
+ }
905
+ return { content: [{ type: "text", text: lines.join("\n") }] };
906
+ }
907
+ );
908
+ server.tool(
909
+ "ssh_key_load",
910
+ "Load an SSH private key into the running agent. Ensures the agent is running first. Use this after ssh_key_list shows a key that is not loaded.",
911
+ {
912
+ keyPath: z.string().describe("Path to the SSH private key to load (e.g. ~/.ssh/id_ed25519)")
913
+ },
914
+ async ({ keyPath }) => {
915
+ const result = loadKey(keyPath);
916
+ return { content: [{ type: "text", text: result.message }], isError: result.status === "error" };
917
+ }
918
+ );
919
+ server.tool(
920
+ "ssh_config_lookup",
921
+ "Resolve the effective SSH configuration for a host. Shows hostname, user, port, identity files, proxy settings, and all other options from ~/.ssh/config. Use this to understand how SSH will connect to a host.",
922
+ {
923
+ host: HostSchema
924
+ },
925
+ async ({ host }) => {
926
+ const result = configLookup(host);
927
+ if ("error" in result) {
928
+ return { content: [{ type: "text", text: result.error }], isError: true };
929
+ }
930
+ const lines = [`SSH config for "${host}":`, ""];
931
+ lines.push(` Hostname: ${result.hostname}`);
932
+ lines.push(` User: ${result.user}`);
933
+ lines.push(` Port: ${result.port}`);
934
+ if (result.identityFile.length > 0) {
935
+ lines.push(` Identity files: ${result.identityFile.join(", ")}`);
936
+ }
937
+ if (result.proxyJump) lines.push(` ProxyJump: ${result.proxyJump}`);
938
+ if (result.proxyCommand) lines.push(` ProxyCommand: ${result.proxyCommand}`);
939
+ return { content: [{ type: "text", text: lines.join("\n") }] };
940
+ }
941
+ );
942
+ server.tool(
943
+ "ssh_known_hosts_fix",
944
+ "Remove a stale host key from known_hosts and re-scan the host to add the current key. Use this when you see 'Host key verification failed' errors, typically after a server has been recreated or reprovisioned.",
945
+ {
946
+ host: HostSchema,
947
+ port: PortSchema
948
+ },
949
+ async ({ host, port }) => {
950
+ const result = fixKnownHosts(host, port || 22);
951
+ const lines = [result.message];
952
+ if (result.actions.length > 0) {
953
+ lines.push("");
954
+ lines.push("Actions taken:");
955
+ for (const a of result.actions) lines.push(` - ${a}`);
956
+ }
957
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: result.status === "error" };
958
+ }
959
+ );
960
+ server.tool(
961
+ "ssh_test",
962
+ "Quick connectivity test to an SSH host. Reports success/failure with timing and actionable error details. Lighter and faster than ssh_diagnose \u2014 use this for a quick check before running operations.",
963
+ {
964
+ host: HostSchema,
965
+ port: PortSchema
966
+ },
967
+ async ({ host, port }) => {
968
+ const result = testConnection(host, port || 22);
969
+ return { content: [{ type: "text", text: result.message }], isError: result.status === "error" };
970
+ }
971
+ );
972
+ server.tool(
973
+ "ssh_git_check",
974
+ "Test Git-over-SSH authentication to a hosting provider (GitHub, GitLab, Bitbucket, etc). Verifies your SSH key is registered and working. Use this when git clone/pull/push fails with SSH errors.",
975
+ {
976
+ host: z.string().optional().describe('Git hosting hostname (default: "github.com")'),
977
+ user: z.string().optional().describe('SSH user for the git host (default: "git")')
978
+ },
979
+ async ({ host, user }) => {
980
+ const result = checkGitSsh(host || "github.com", user || "git");
981
+ const lines = [result.message];
982
+ if (result.authenticatedAs) {
983
+ lines.push(`Authenticated as: ${result.authenticatedAs}`);
984
+ }
985
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: result.status === "error" };
986
+ }
987
+ );
474
988
  }
475
989
 
476
990
  // src/server.ts
477
991
  function createServer() {
478
992
  const server = new McpServer({
479
993
  name: "ssh-mcp",
480
- version: "0.1.0"
994
+ version: "0.3.0"
481
995
  });
482
996
  registerTools(server);
483
997
  return server;