@ecubelabs/mysql-mcp 0.0.1 → 1.0.0-next.2

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.
@@ -0,0 +1,105 @@
1
+ import { createHmac } from 'crypto';
2
+ import * as fs from 'fs';
3
+ import { expandHome } from './config.js';
4
+ export const DEFAULT_USER_KNOWN_HOSTS_FILES = ['~/.ssh/known_hosts', '~/.ssh/known_hosts2'];
5
+ const GLOBAL_KNOWN_HOSTS_FILES = ['/etc/ssh/ssh_known_hosts', '/etc/ssh/ssh_known_hosts2'];
6
+ export function knownHostsName(host, port) {
7
+ return port === 22 ? host : `[${host}]:${port}`;
8
+ }
9
+ function matchesWildcard(pattern, name) {
10
+ const source = pattern
11
+ .split('')
12
+ .map((ch) => (ch === '*' ? '.*' : ch === '?' ? '.' : ch.replace(/[\\^$.|+()[\]{}]/g, '\\$&')))
13
+ .join('');
14
+ return new RegExp(`^${source}$`, 'i').test(name);
15
+ }
16
+ function matchesHashed(entry, name) {
17
+ const [, , salt, hash] = entry.split('|');
18
+ if (!salt || !hash) {
19
+ return false;
20
+ }
21
+ const digest = createHmac('sha1', Buffer.from(salt, 'base64')).update(name).digest('base64');
22
+ return digest === hash;
23
+ }
24
+ function hostFieldMatches(field, name) {
25
+ if (field.startsWith('|1|')) {
26
+ return matchesHashed(field, name);
27
+ }
28
+ let matched = false;
29
+ for (const pattern of field.split(',')) {
30
+ if (pattern.startsWith('!')) {
31
+ if (matchesWildcard(pattern.slice(1), name)) {
32
+ return false;
33
+ }
34
+ }
35
+ else if (matchesWildcard(pattern, name)) {
36
+ matched = true;
37
+ }
38
+ }
39
+ return matched;
40
+ }
41
+ export function lookupKnownHosts(host, port, files) {
42
+ const name = knownHostsName(host, port);
43
+ const result = { name, files: [], keys: [], revoked: [] };
44
+ for (const file of [...files.map(expandHome), ...GLOBAL_KNOWN_HOSTS_FILES]) {
45
+ let raw;
46
+ try {
47
+ raw = fs.readFileSync(file, 'utf8');
48
+ }
49
+ catch {
50
+ continue;
51
+ }
52
+ result.files.push(file);
53
+ for (const line of raw.split(/\r?\n/)) {
54
+ const fields = line.trim().split(/\s+/);
55
+ if (!fields[0] || fields[0].startsWith('#')) {
56
+ continue;
57
+ }
58
+ const marker = fields[0].startsWith('@') ? fields.shift() : undefined;
59
+ if (marker === '@cert-authority') {
60
+ continue;
61
+ }
62
+ const [hosts, type, key] = fields;
63
+ if (!hosts || !type || !key || !hostFieldMatches(hosts, name)) {
64
+ continue;
65
+ }
66
+ const blob = Buffer.from(key, 'base64');
67
+ if (marker === '@revoked') {
68
+ result.revoked.push(blob);
69
+ }
70
+ else {
71
+ result.keys.push({ type, key: blob });
72
+ }
73
+ }
74
+ }
75
+ return result;
76
+ }
77
+ export function hostKeyAlgorithms(keys) {
78
+ const algorithms = [];
79
+ const add = (algorithm) => {
80
+ if (!algorithms.includes(algorithm)) {
81
+ algorithms.push(algorithm);
82
+ }
83
+ };
84
+ for (const { type } of keys) {
85
+ if (type === 'ssh-rsa') {
86
+ add('rsa-sha2-512');
87
+ add('rsa-sha2-256');
88
+ add('ssh-rsa');
89
+ }
90
+ else if (type === 'ssh-ed25519' ||
91
+ type === 'ecdsa-sha2-nistp256' ||
92
+ type === 'ecdsa-sha2-nistp384' ||
93
+ type === 'ecdsa-sha2-nistp521' ||
94
+ type === 'ssh-dss') {
95
+ add(type);
96
+ }
97
+ }
98
+ return algorithms;
99
+ }
100
+ export function isKnownHostKey(lookup, presented) {
101
+ if (lookup.revoked.some((key) => key.equals(presented))) {
102
+ return false;
103
+ }
104
+ return lookup.keys.some(({ key }) => key.equals(presented));
105
+ }
@@ -4,6 +4,7 @@ import { Client as SSHClient } from 'ssh2';
4
4
  import { MYSQL_HOST, MYSQL_PORT, SSH_CONFIG_HOST, SSH_ENABLED, SSH_HOST, SSH_LOCAL_PORT, SSH_PASSPHRASE, SSH_PORT, SSH_PRIVATE_KEY_PATH, SSH_REUSE_EXISTING, SSH_USER, } from '../config/index.js';
5
5
  import { log } from '../utils/index.js';
6
6
  import { expandHome, readSSHConfigHost } from './config.js';
7
+ import { DEFAULT_USER_KNOWN_HOSTS_FILES, hostKeyAlgorithms, isKnownHostKey, lookupKnownHosts } from './known-hosts.js';
7
8
  class LocalPortTakenError extends Error {
8
9
  }
9
10
  const RECONNECT_MAX_ATTEMPTS = 3;
@@ -61,6 +62,9 @@ export function resolveTunnelConfig() {
61
62
  sshUser: sshUser,
62
63
  privateKeyPath,
63
64
  passphrase: SSH_PASSPHRASE,
65
+ knownHostsFiles: fromConfig?.userKnownHostsFiles ?? DEFAULT_USER_KNOWN_HOSTS_FILES,
66
+ hostKeyName: fromConfig?.hostKeyAlias ?? sshHost,
67
+ sshTarget: configHost ?? `${sshPort === 22 ? '' : `-p ${sshPort} `}${sshUser}@${sshHost}`,
64
68
  localPort,
65
69
  remoteHost: remoteHost,
66
70
  remotePort,
@@ -95,8 +99,17 @@ let shuttingDown = false;
95
99
  let fatalError = null;
96
100
  function connectSSH(cfg) {
97
101
  return new Promise((resolve, reject) => {
102
+ const known = lookupKnownHosts(cfg.hostKeyName, cfg.sshPort, cfg.knownHostsFiles);
103
+ const algorithms = hostKeyAlgorithms(known.keys);
104
+ if (algorithms.length === 0) {
105
+ const searched = known.files.length > 0 ? known.files.join(', ') : cfg.knownHostsFiles.join(', ');
106
+ reject(new Error(`No host key for ${known.name} in known_hosts (${searched}). ` +
107
+ `Run \`ssh ${cfg.sshTarget}\` once to verify the bastion's fingerprint and record it, then retry.`));
108
+ return;
109
+ }
98
110
  const client = new SSHClient();
99
111
  let settled = false;
112
+ let hostKeyRejection = null;
100
113
  const timer = setTimeout(() => {
101
114
  if (settled) {
102
115
  return;
@@ -120,7 +133,7 @@ function connectSSH(cfg) {
120
133
  settled = true;
121
134
  clearTimeout(timer);
122
135
  client.destroy();
123
- reject(new Error(`SSH connection to ${cfg.sshUser}@${cfg.sshHost}:${cfg.sshPort} failed: ${err.message}`));
136
+ reject(new Error(`SSH connection to ${cfg.sshUser}@${cfg.sshHost}:${cfg.sshPort} failed: ${hostKeyRejection ?? err.message}`));
124
137
  });
125
138
  let privateKey;
126
139
  try {
@@ -141,6 +154,16 @@ function connectSSH(cfg) {
141
154
  keepaliveInterval: 15000,
142
155
  keepaliveCountMax: 3,
143
156
  ...(cfg.passphrase ? { passphrase: cfg.passphrase } : {}),
157
+ algorithms: { serverHostKey: algorithms },
158
+ hostVerifier: (key) => {
159
+ if (isKnownHostKey(known, key)) {
160
+ return true;
161
+ }
162
+ hostKeyRejection =
163
+ `the host key for ${known.name} does not match known_hosts. The bastion's key changed or ` +
164
+ `the connection is being intercepted. Check with \`ssh ${cfg.sshTarget}\` before retrying.`;
165
+ return false;
166
+ },
144
167
  };
145
168
  client.connect(connectConfig);
146
169
  });
@@ -161,7 +184,7 @@ async function reconnect(cfg) {
161
184
  sshClient = client;
162
185
  fatalError = null;
163
186
  attachDropHandler(client, cfg);
164
- log('error', `[ssh] tunnel reconnected on attempt ${attempt}`);
187
+ log('info', `[ssh] tunnel reconnected on attempt ${attempt}`);
165
188
  return;
166
189
  }
167
190
  catch (err) {
@@ -252,7 +275,7 @@ export function ensureTunnel() {
252
275
  activeEndpoint = { host: '127.0.0.1', port: cfg.localPort, reused: true };
253
276
  return activeEndpoint;
254
277
  }
255
- log('error', `[ssh] opening tunnel ${cfg.sshUser}@${cfg.sshHost}:${cfg.sshPort} -> ${cfg.remoteHost}:${cfg.remotePort} ` +
278
+ log('info', `[ssh] opening tunnel ${cfg.sshUser}@${cfg.sshHost}:${cfg.sshPort} -> ${cfg.remoteHost}:${cfg.remotePort} ` +
256
279
  `(local port ${cfg.localPort === 0 ? 'auto' : cfg.localPort})`);
257
280
  const client = await connectSSH(cfg);
258
281
  sshClient = client;
@@ -277,7 +300,7 @@ export function ensureTunnel() {
277
300
  }
278
301
  }
279
302
  attachDropHandler(client, cfg);
280
- log('error', `[ssh] tunnel listening on 127.0.0.1:${port}`);
303
+ log('info', `[ssh] tunnel listening on 127.0.0.1:${port}`);
281
304
  activeEndpoint = { host: '127.0.0.1', port, reused: false };
282
305
  return activeEndpoint;
283
306
  })();
@@ -2,6 +2,10 @@ import { ENABLE_LOGGING } from '../config/index.js';
2
2
  export function tableResourceUri(schema, table) {
3
3
  return `mysql://tables/${encodeURIComponent(schema)}/${encodeURIComponent(table)}`;
4
4
  }
5
+ export function sharedOnce(fn) {
6
+ let running;
7
+ return (...args) => (running ??= fn(...args));
8
+ }
5
9
  export function log(type = 'info', ...args) {
6
10
  if (!ENABLE_LOGGING) {
7
11
  return;
package/package.json CHANGED
@@ -1,53 +1,53 @@
1
1
  {
2
- "name": "@ecubelabs/mysql-mcp",
3
- "version": "0.0.1",
4
- "description": "Read-only MySQL MCP server that reaches its database through an SSH bastion, with per-environment profiles",
5
- "license": "MIT",
6
- "repository": {
7
- "url": "https://github.com/Ecube-Labs/skynet.git",
8
- "directory": "packages/mysql-mcp"
9
- },
10
- "publishConfig": {
11
- "access": "public"
12
- },
13
- "type": "module",
14
- "engines": {
15
- "node": ">=18"
16
- },
17
- "main": "dist/index.js",
18
- "bin": "dist/index.js",
19
- "files": [
20
- "dist"
21
- ],
22
- "scripts": {
23
- "lint": "oxfmt --check . && oxlint && eslint index.ts \"src/**/*.ts\"",
24
- "lint:ci": "oxfmt --check . && oxlint --quiet && eslint --quiet index.ts \"src/**/*.ts\"",
25
- "lint:fix": "oxfmt . && oxlint --fix --quiet && eslint --fix index.ts \"src/**/*.ts\"",
26
- "build": "tsc && shx chmod +x dist/index.js",
27
- "prepack": "yarn build",
28
- "watch": "tsc --watch",
29
- "test": "tsc -p tsconfig.test.json && vitest run",
30
- "test:watch": "vitest",
31
- "start:stage": "./bin/mcp-mysql-stage.sh",
32
- "start:prod": "./bin/mcp-mysql-prod.sh"
33
- },
34
- "dependencies": {
35
- "@modelcontextprotocol/sdk": "^1.31.0",
36
- "mysql2": "^3.14.1",
37
- "node-sql-parser": "^5.3.9",
38
- "ssh2": "^1.17.0"
39
- },
40
- "devDependencies": {
41
- "@semantic-release/npm": "^13.1.5",
42
- "@types/node": "^22.20.2",
43
- "@types/ssh2": "^1.15.5",
44
- "eslint": "^9.27.0",
45
- "eslint-config-skynet": "^0.0.0",
46
- "semantic-release": "^25.0.9",
47
- "semantic-release-monorepo": "^8.0.2",
48
- "shx": "^0.3.4",
49
- "typescript": "^5.8.3",
50
- "vite": "^8.3.0",
51
- "vitest": "^5.0.0"
52
- }
53
- }
2
+ "name": "@ecubelabs/mysql-mcp",
3
+ "version": "1.0.0-next.2",
4
+ "description": "Read-only MySQL MCP server that reaches its database through an SSH bastion, with per-environment profiles",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "url": "https://github.com/Ecube-Labs/skynet.git",
8
+ "directory": "packages/mysql-mcp"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "type": "module",
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "main": "dist/index.js",
18
+ "bin": "dist/index.js",
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "scripts": {
23
+ "lint": "oxfmt --check . && oxlint && eslint index.ts \"src/**/*.ts\"",
24
+ "lint:ci": "oxfmt --check . && oxlint --quiet && eslint --quiet index.ts \"src/**/*.ts\"",
25
+ "lint:fix": "oxfmt . && oxlint --fix --quiet && eslint --fix index.ts \"src/**/*.ts\"",
26
+ "build": "tsc && shx chmod +x dist/index.js",
27
+ "prepack": "yarn build",
28
+ "watch": "tsc --watch",
29
+ "test": "tsc -p tsconfig.test.json && vitest run",
30
+ "test:watch": "vitest",
31
+ "start:stage": "./bin/mcp-mysql-stage.sh",
32
+ "start:prod": "./bin/mcp-mysql-prod.sh"
33
+ },
34
+ "dependencies": {
35
+ "@modelcontextprotocol/sdk": "^1.31.0",
36
+ "mysql2": "^3.14.1",
37
+ "node-sql-parser": "^5.3.9",
38
+ "ssh2": "^1.17.0"
39
+ },
40
+ "devDependencies": {
41
+ "@semantic-release/npm": "^13.1.5",
42
+ "@types/node": "^22.20.2",
43
+ "@types/ssh2": "^1.15.5",
44
+ "eslint": "^9.27.0",
45
+ "eslint-config-skynet": "workspace:^",
46
+ "semantic-release": "^25.0.9",
47
+ "semantic-release-monorepo": "^8.0.2",
48
+ "shx": "^0.3.4",
49
+ "typescript": "^5.8.3",
50
+ "vite": "^8.3.0",
51
+ "vitest": "^5.0.0"
52
+ }
53
+ }