mcp-ssh-manager 3.6.4 → 3.6.5

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/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ All notable changes to MCP SSH Manager will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [3.6.5] - 2026-06-30
9
+
10
+ ### Security
11
+
12
+ - **`ssh_db_query` could execute arbitrary shell commands on the remote host** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77))
13
+ - The query builders interpolated the raw query into a **double-quoted** shell string (`mysql -e "${query}"`, `psql -c "${query}"`, `mongo --eval "${query}"`), so the remote shell evaluated backticks `` `…` `` and `$(…)`/`$VAR` **before** the database engine ever saw the query. The "SELECT-only" tool could therefore run shell commands on the target server (e.g. `` SELECT `id` `` / `SELECT '$(id)'`).
14
+ - The query is now delivered to `mysql`/`psql`/`mongo` on **stdin via a single-quoted heredoc** (`<<'__MCP_SQL_EOF__'`), so the remote shell never parses it — only the database engine interprets the SQL/JS. A shared `buildHeredoc()` helper keeps the existing `awk` JSON-wrapper pipe on the heredoc opening line (MySQL JSON output is byte-for-byte unchanged) and defensively rejects a delimiter collision. `isSafeQuery()` is intentionally left as-is, since the heredoc — not keyword filtering — closes the injection path.
15
+
16
+ ### Fixed
17
+
18
+ - **`ssh_db_query` (MySQL) silently corrupted backtick-quoted identifiers** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77))
19
+ - The same shell-evaluation bug meant any query using backtick identifiers — hyphenated database names, cross-database joins, reserved-word columns — was rewritten by the shell and returned empty/incorrect results **with no error**. The stdin heredoc fix above restores these queries verbatim.
20
+ - **`ssh_db_query` reported `row_count` off by one** ([#45](https://github.com/bvisible/mcp-ssh-manager/pull/45) — thanks [@technophile77](https://github.com/technophile77))
21
+ - The handler reported `output.split('\n').length`, which counted cosmetic lines (the leading `[` of the MySQL JSON wrapper, psql header/separator lines) rather than result rows: 1 row → `2`, 13 rows → `14`, 0 rows → `2`. A new `countQueryRows()` derives the count from each engine's actual output structure — MySQL JSON `{"row":N,…}` entries, MySQL `--batch` lines, psql's authoritative `(N rows)` footer (with a header/separator fallback), and MongoDB `printjson` documents — so empty output is `0` and the count tracks real rows.
22
+
23
+ ### Tests
24
+
25
+ - **New `tests/test-database-query-quoting.js`** (`test:dbquoting`) — verifies the SQL/JS query text is carried verbatim on stdin for all three builders (never via `-e "`/`-c "`/`--eval "`), that the `awk` pipe stays on the heredoc opening line with the terminator alone, that `buildHeredoc` rejects a delimiter collision, and a stochastic round-trip of 500 random shell-metacharacter queries.
26
+ - **New `tests/test-database-row-count.js`** (`test:dbrowcount`) — covers the exact issue cases (MySQL 0/1/13 rows), a look-alike `{"row":` value inside a cell, MySQL text format, psql `(N rows)`/`(1 row)`/`(0 rows)` footers and the no-footer fallback, MongoDB single/multi-document counting, and empty/whitespace → `0`.
27
+
8
28
  ## [3.6.4] - 2026-06-18
9
29
 
10
30
  ### Changed
package/README.md CHANGED
@@ -6,7 +6,7 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
6
6
 
7
7
  [![npm version](https://img.shields.io/npm/v/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
8
8
  [![npm downloads](https://img.shields.io/npm/dt/mcp-ssh-manager.svg?style=for-the-badge&logo=npm)](https://www.npmjs.com/package/mcp-ssh-manager)
9
- [![Version](https://img.shields.io/badge/Version-3.6.4-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.4)
9
+ [![Version](https://img.shields.io/badge/Version-3.6.5-brightgreen?style=for-the-badge)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v3.6.5)
10
10
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=for-the-badge&logo=anthropic)](https://claude.ai/code)
11
11
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=for-the-badge&logo=openai)](https://openai.com/codex)
12
12
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=for-the-badge)](https://modelcontextprotocol.io)
@@ -20,19 +20,23 @@ A Model Context Protocol (MCP) server that enables **Claude Code** and **OpenAI
20
20
 
21
21
  ---
22
22
 
23
- ## 🎉 What's New in v3.6.4
23
+ ## 🎉 What's New in v3.6.5
24
24
 
25
- **Internal cleanup + a dead-code quality gate** (Released: June 18, 2026)
25
+ **Security fix: `ssh_db_query` shell injection + a row-count fix** (Released: June 30, 2026)
26
26
 
27
- - **🧹 Dead-code removal (−343 lines), zero behavioral change** — removed 27 unused exports and 2 duplicate exports. The MCP server and CLI behave identically: command builders/parsers are byte-identical before/after, and all 37 tools were verified end-to-end against a live SSH server.
28
- - **🛡️ Dead-code CI gate** — a calibrated `knip.json` plus a **blocking** `knip` step in CI keep unused code and dependencies from creeping back. `eslint src/` is now clean (0 errors, 0 warnings).
27
+ - **🔒 `ssh_db_query` no longer lets the remote shell parse your query** ([#44](https://github.com/bvisible/mcp-ssh-manager/pull/44) — thanks [@technophile77](https://github.com/technophile77)) — the builders interpolated the query into a double-quoted shell string (`mysql -e "${query}"`, `psql -c "${query}"`, `mongo --eval "${query}"`), so the remote shell evaluated backticks and `$(…)` **before** the database saw it. That both **corrupted** backtick identifiers (hyphenated DB names, cross-DB joins → empty results, no error) **and** let the "SELECT-only" tool **run arbitrary shell commands** on the host. The query is now delivered on **stdin via a single-quoted heredoc**, so only the database engine ever interprets it.
28
+ - **🔢 `ssh_db_query` reports the real `row_count`** ([#45](https://github.com/bvisible/mcp-ssh-manager/pull/45) — thanks [@technophile77](https://github.com/technophile77)) — it used to count the cosmetic JSON-wrapper line (1 row → `2`, 0 rows → `2`); it now derives the count from each engine's actual output (MySQL JSON entries, psql's `(N rows)` footer, MongoDB documents).
29
29
 
30
- [Read full changelog →](CHANGELOG.md#364---2026-06-18)
30
+ [Read full changelog →](CHANGELOG.md#365---2026-06-30)
31
31
 
32
32
  ---
33
33
 
34
34
  ## Previous Releases
35
35
 
36
+ ### v3.6.4 - Internal cleanup + a dead-code quality gate (June 18, 2026)
37
+
38
+ - **🧹 Dead-code removal (−343 lines), zero behavioral change** — removed 27 unused exports and 2 duplicate exports; the MCP server and CLI behave identically (command builders/parsers byte-identical, all 37 tools verified end-to-end). A calibrated `knip.json` plus a **blocking** `knip` CI step keep unused code from creeping back. [Full changelog →](CHANGELOG.md#364---2026-06-18)
39
+
36
40
  ### v3.6.3 - `ssh_sync` reports the real transfer count (June 18, 2026)
37
41
 
38
42
  - **📊 No more false "No files needed to be transferred"** ([#42](https://github.com/bvisible/mcp-ssh-manager/pull/42) — thanks [@MakksSh](https://github.com/MakksSh)) — fixed rsync `--stats` parsing: `--stats` is always passed now, and rsync 2.x/3.x wording, openrsync's `B` suffix, and locale separators are all handled. [Full changelog →](CHANGELOG.md#363---2026-06-18)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-ssh-manager",
3
- "version": "3.6.4",
3
+ "version": "3.6.5",
4
4
  "description": "MCP SSH Manager: Model Context Protocol server for SSH remote server management. Control SSH connections from Claude Code and OpenAI Codex - execute commands, transfer files, database operations, backups, health monitoring, and DevOps automation. NEW: Tool activation system reduces context usage by 92%",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -13,7 +13,7 @@
13
13
  "setup": "npm install && pip install -r tools/requirements.txt",
14
14
  "configure": "python tools/server-manager.py",
15
15
  "test-connection": "python tools/test-connection.py",
16
- "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:lifecycle && npm run test:sync",
16
+ "test": "npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:ping && npm run test:config && npm run test:lifecycle && npm run test:sync && npm run test:dbquoting && npm run test:dbrowcount",
17
17
  "test:profiles": "node tests/test-profiles.js",
18
18
  "test:aliases": "node tests/test-command-aliases.js",
19
19
  "test:hooks": "node tests/test-hooks.js",
@@ -23,6 +23,8 @@
23
23
  "test:config": "node tests/test-server-config-manager.js",
24
24
  "test:lifecycle": "node tests/test-lifecycle.js",
25
25
  "test:sync": "node tests/test-sync-stats.js",
26
+ "test:dbquoting": "node tests/test-database-query-quoting.js",
27
+ "test:dbrowcount": "node tests/test-database-row-count.js",
26
28
  "test:all": "npm test && ./scripts/validate.sh",
27
29
  "validate": "./scripts/validate.sh",
28
30
  "lint": "eslint src/*.js",
@@ -339,6 +339,41 @@ export function buildMongoDBListCollectionsCommand(options) {
339
339
  return command;
340
340
  }
341
341
 
342
+ /**
343
+ * Build a single-quoted shell heredoc that carries `body` to a command's stdin.
344
+ *
345
+ * The delimiter is single-quoted (`<<'DELIM'`) so the remote shell takes the body
346
+ * literally — backticks, `$VAR`, and `$(...)` inside `body` are never expanded by the
347
+ * shell. This is how SQL/JS query text is delivered to mysql/psql/mongo without the
348
+ * shell parsing it first (the cause of issue #44: corruption of backtick-quoted
349
+ * identifiers and remote command injection).
350
+ *
351
+ * When the command pipes its stdout onward (e.g. `mysql ... | awk ...`), the pipe must
352
+ * stay on the heredoc's opening line — the terminator has to be alone on its own line —
353
+ * so the pipeline is passed via `options.pipeline` and emitted as `<<'DELIM' | awk ...`.
354
+ *
355
+ * @param body Text fed to the command's stdin (e.g. a SQL statement). Passed verbatim.
356
+ * @param options.delimiter Heredoc terminator. Must not appear as a standalone line in
357
+ * `body`, otherwise the heredoc would end early; this is rejected defensively.
358
+ * @param options.pipeline Shell pipeline appended after the heredoc marker on the
359
+ * opening line (e.g. `"| awk '...'"`). Omit for a plain stdin redirect.
360
+ * @returns The redirection fragment to append after a command, ending with the
361
+ * terminator on its own line.
362
+ * @throws {Error} If a line of `body` equals `delimiter`.
363
+ * @example
364
+ * `mysql app${buildHeredoc('SELECT 1')}`
365
+ * // mysql app <<'__MCP_SQL_EOF__'\nSELECT 1\n__MCP_SQL_EOF__
366
+ * @see buildMySQLQueryCommand
367
+ */
368
+ export function buildHeredoc(body, { delimiter = '__MCP_SQL_EOF__', pipeline = '' } = {}) {
369
+ const text = body == null ? '' : String(body);
370
+ if (text.split('\n').some(line => line === delimiter)) {
371
+ throw new Error(`Query contains the heredoc delimiter "${delimiter}" on its own line`);
372
+ }
373
+ const suffix = pipeline ? ` ${pipeline}` : '';
374
+ return ` <<'${delimiter}'${suffix}\n${text}\n${delimiter}`;
375
+ }
376
+
342
377
  /**
343
378
  * Build MySQL query command (SELECT only)
344
379
  */
@@ -357,11 +392,16 @@ export function buildMySQLQueryCommand(options) {
357
392
  if (port) command += ` -P ${port}`;
358
393
  command += ` ${database}`;
359
394
 
395
+ // Feed the SQL via stdin (quoted heredoc) so the remote shell never parses it —
396
+ // backtick-quoted identifiers and `$` survive intact, and query text cannot inject
397
+ // shell commands. See buildHeredoc and issue #44.
360
398
  if (format === 'json') {
361
- // Use JSON output if MySQL 5.7.8+
362
- command += ` -e "${query}" --batch --skip-column-names | awk 'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}'`;
399
+ // Use JSON output if MySQL 5.7.8+. The awk pipe stays on the heredoc opening line so
400
+ // the terminator remains alone on its own line.
401
+ const awk = 'awk \'BEGIN{print "["} {if(NR>1)print ","; printf "{\\"row\\":%d,\\"data\\":\\"%s\\"}", NR, $0} END{print "]"}\'';
402
+ command += ` --batch --skip-column-names${buildHeredoc(query, { pipeline: `| ${awk}` })}`;
363
403
  } else {
364
- command += ` -e "${query}"`;
404
+ command += buildHeredoc(query);
365
405
  }
366
406
 
367
407
  return command;
@@ -387,7 +427,9 @@ export function buildPostgreSQLQueryCommand(options) {
387
427
  if (host) command += ` -h ${host}`;
388
428
  if (port) command += ` -p ${port}`;
389
429
  command += ` -d ${database}`;
390
- command += ` -c "${query}"`;
430
+ // Feed SQL via stdin (quoted heredoc) instead of `-c "${query}"` so the remote shell
431
+ // never parses it. See buildHeredoc and issue #44.
432
+ command += buildHeredoc(query);
391
433
 
392
434
  return command;
393
435
  }
@@ -404,7 +446,11 @@ export function buildMongoDBQueryCommand(options) {
404
446
  if (user) command += ` --username ${user}`;
405
447
  if (password) command += ` --password '${password}'`;
406
448
  command += ` ${database}`;
407
- command += ` --quiet --eval "db.${collection}.find(${query || '{}'}).forEach(printjson)"`;
449
+ // Feed the JS script via stdin (quoted heredoc) instead of `--eval "..."` so the
450
+ // remote shell never expands backticks/`$` in the query. mongo still evaluates the
451
+ // script as JavaScript (expected). See buildHeredoc and issue #44.
452
+ const script = `db.${collection}.find(${query || '{}'}).forEach(printjson)`;
453
+ command += ` --quiet${buildHeredoc(script)}`;
408
454
 
409
455
  return command;
410
456
  }
@@ -435,6 +481,64 @@ export function isSafeQuery(query) {
435
481
  return true;
436
482
  }
437
483
 
484
+ /**
485
+ * Count the actual result rows in the raw output of an `ssh_db_query` command.
486
+ *
487
+ * The handler previously reported `output.split('\n').length`, which counts cosmetic
488
+ * lines (the leading `[` of the MySQL JSON wrapper, psql headers/separators) rather than
489
+ * data rows — so it was off by one for MySQL and over-counted for psql (issue #45). This
490
+ * derives the count from the structure each engine actually produces.
491
+ *
492
+ * @param output Raw, already-trimmed stdout of the query command.
493
+ * @param type One of {@link DB_TYPES} (`'mysql' | 'postgresql' | 'mongodb'`).
494
+ * @param format Output format used to build the command; only `'json'` MySQL is wrapped
495
+ * by the `awk` JSON formatter, which is what this counts. Defaults to `'json'`.
496
+ * @returns The number of result rows (documents for MongoDB). `0` for empty output.
497
+ * @example
498
+ * countQueryRows('[\n{"row":1,"data":"a"},\n{"row":2,"data":"b"}]', 'mysql') // => 2
499
+ * countQueryRows(' id \n----\n 1\n(1 row)', 'postgresql') // => 1
500
+ * @see buildMySQLQueryCommand
501
+ */
502
+ export function countQueryRows(output, type, format = 'json') {
503
+ if (!output || !output.trim()) {
504
+ return 0;
505
+ }
506
+ const lines = output.split('\n');
507
+
508
+ if (type === DB_TYPES.MYSQL) {
509
+ if (format === 'json') {
510
+ // The awk wrapper emits exactly one `{"row":N,...}` entry per result row, anchored
511
+ // at the start of its own line, bracketed by cosmetic `[` / `]` lines.
512
+ return lines.filter(line => /^\{"row":\d+,/.test(line)).length;
513
+ }
514
+ // Tabular `--batch` output: one row per non-empty line (column names are suppressed).
515
+ return lines.filter(line => line.trim() !== '').length;
516
+ }
517
+
518
+ if (type === DB_TYPES.POSTGRESQL) {
519
+ // psql prints an authoritative footer like `(13 rows)` — trust it when present.
520
+ const footer = output.match(/\((\d+)\s+rows?\)/);
521
+ if (footer) {
522
+ return Number(footer[1]);
523
+ }
524
+ // Otherwise fall back to the data lines, dropping the column-header line, the
525
+ // `---+---` separator, and any `(N rows)` footer line.
526
+ const dataLines = lines.filter(line => {
527
+ const trimmed = line.trim();
528
+ return trimmed !== '' && !/^[-+\s]+$/.test(trimmed) && !/^\(\d+\s+rows?\)$/.test(trimmed);
529
+ });
530
+ return Math.max(0, dataLines.length - 1); // first remaining line is the header
531
+ }
532
+
533
+ if (type === DB_TYPES.MONGODB) {
534
+ // `printjson` closes each document with a `}` at column 0 — one per document.
535
+ return lines.filter(line => line === '}').length;
536
+ }
537
+
538
+ // Unknown type: best-effort non-empty line count.
539
+ return lines.filter(line => line.trim() !== '').length;
540
+ }
541
+
438
542
  /**
439
543
  * Parse database list output
440
544
  */
package/src/index.js CHANGED
@@ -132,6 +132,7 @@ import {
132
132
  buildPostgreSQLQueryCommand,
133
133
  buildMongoDBQueryCommand,
134
134
  isSafeQuery,
135
+ countQueryRows,
135
136
  parseDatabaseList,
136
137
  parseTableList,
137
138
  parseSize,
@@ -4783,12 +4784,14 @@ registerToolConditional(
4783
4784
 
4784
4785
  // Parse output (basic parsing, output depends on database type)
4785
4786
  const output = result.stdout.trim();
4786
- const lines = output.split('\n');
4787
+ // Derive the real row count from each engine's output structure rather than the
4788
+ // raw line count, which counts cosmetic wrapper/header lines (issue #45).
4789
+ const rowCount = countQueryRows(output, type);
4787
4790
 
4788
4791
  logger.info('Query executed successfully', {
4789
4792
  server: serverName,
4790
4793
  database,
4791
- rows: lines.length
4794
+ rows: rowCount
4792
4795
  });
4793
4796
 
4794
4797
  return {
@@ -4802,7 +4805,7 @@ registerToolConditional(
4802
4805
  database,
4803
4806
  collection: collection || null,
4804
4807
  query,
4805
- row_count: lines.length,
4808
+ row_count: rowCount,
4806
4809
  output: output,
4807
4810
  timestamp: new Date().toISOString()
4808
4811
  }, null, 2)