@ecubelabs/mysql-mcp 1.0.0-next.6 → 1.0.0-next.7

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.
@@ -1,4 +1,4 @@
1
- import { ALLOW_DELETE_OPERATION, ALLOW_DDL_OPERATION, ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION, SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, } from '../config/index.js';
1
+ import { WRITE_KINDS } from '../config/schema.js';
2
2
  function schemaOverride(permissions, schema) {
3
3
  const lowered = schema.toLowerCase();
4
4
  let override;
@@ -15,43 +15,28 @@ function schemaOverride(permissions, schema) {
15
15
  }
16
16
  return override;
17
17
  }
18
- function isInsertAllowedForSchema(schema) {
18
+ export function isWriteAllowed(policy, kind, schema) {
19
+ const global = policy.allow[kind];
19
20
  if (!schema) {
20
- return ALLOW_INSERT_OPERATION;
21
+ return global;
21
22
  }
22
- return schemaOverride(SCHEMA_INSERT_PERMISSIONS, schema) ?? ALLOW_INSERT_OPERATION;
23
+ return schemaOverride(policy.schemas[kind], schema) ?? global;
23
24
  }
24
- function isUpdateAllowedForSchema(schema) {
25
- if (!schema) {
26
- return ALLOW_UPDATE_OPERATION;
27
- }
28
- return schemaOverride(SCHEMA_UPDATE_PERMISSIONS, schema) ?? ALLOW_UPDATE_OPERATION;
29
- }
30
- function isDeleteAllowedForSchema(schema) {
31
- if (!schema) {
32
- return ALLOW_DELETE_OPERATION;
33
- }
34
- return schemaOverride(SCHEMA_DELETE_PERMISSIONS, schema) ?? ALLOW_DELETE_OPERATION;
35
- }
36
- function isDDLAllowedForSchema(schema) {
37
- if (!schema) {
38
- return ALLOW_DDL_OPERATION;
39
- }
40
- return schemaOverride(SCHEMA_DDL_PERMISSIONS, schema) ?? ALLOW_DDL_OPERATION;
41
- }
42
- function writeCapabilities() {
43
- const kinds = [
44
- { label: 'INSERT', global: ALLOW_INSERT_OPERATION, perSchema: SCHEMA_INSERT_PERMISSIONS },
45
- { label: 'UPDATE', global: ALLOW_UPDATE_OPERATION, perSchema: SCHEMA_UPDATE_PERMISSIONS },
46
- { label: 'DELETE', global: ALLOW_DELETE_OPERATION, perSchema: SCHEMA_DELETE_PERMISSIONS },
47
- { label: 'DDL', global: ALLOW_DDL_OPERATION, perSchema: SCHEMA_DDL_PERMISSIONS },
48
- ];
25
+ export const WRITE_LABELS = {
26
+ insert: 'INSERT',
27
+ update: 'UPDATE',
28
+ delete: 'DELETE',
29
+ ddl: 'DDL',
30
+ };
31
+ export function writeCapabilities(policy) {
49
32
  const capabilities = [];
50
- for (const { label, global, perSchema } of kinds) {
51
- if (global) {
33
+ for (const kind of WRITE_KINDS) {
34
+ const label = WRITE_LABELS[kind];
35
+ if (policy.allow[kind]) {
52
36
  capabilities.push({ label, schemas: null });
53
37
  continue;
54
38
  }
39
+ const perSchema = policy.schemas[kind];
55
40
  const opened = Object.keys(perSchema).filter((schema) => schemaOverride(perSchema, schema) === true);
56
41
  if (opened.length > 0) {
57
42
  capabilities.push({ label, schemas: opened });
@@ -59,4 +44,3 @@ function writeCapabilities() {
59
44
  }
60
45
  return capabilities;
61
46
  }
62
- export { isInsertAllowedForSchema, isUpdateAllowedForSchema, isDeleteAllowedForSchema, isDDLAllowedForSchema, writeCapabilities, };
@@ -0,0 +1,178 @@
1
+ import { createHash } from 'crypto';
2
+ import * as mysql2 from 'mysql2/promise';
3
+ import { SecretResolver, withSecretRetry, isAccessDeniedError } from '../config/secrets.js';
4
+ import { readCACertificate, readSSLFile } from '../config/ssl.js';
5
+ import { expandHome } from '../ssh/config.js';
6
+ import { resolveBastion, SshSession } from '../ssh/tunnel.js';
7
+ import { log } from '../utils/index.js';
8
+ export function buildPoolOptions(spec, endpoint, password, defaults) {
9
+ const { instance } = spec;
10
+ const target = endpoint
11
+ ? { host: endpoint.host, port: endpoint.port }
12
+ : instance.socketPath
13
+ ? { socketPath: instance.socketPath }
14
+ : { host: instance.host, port: instance.port };
15
+ const ssl = instance.ssl;
16
+ return {
17
+ ...target,
18
+ user: spec.user,
19
+ password,
20
+ ...(spec.database ? { database: spec.database } : {}),
21
+ connectionLimit: defaults.poolSize,
22
+ waitForConnections: true,
23
+ queueLimit: defaults.queueLimit,
24
+ enableKeepAlive: true,
25
+ keepAliveInitialDelay: 0,
26
+ connectTimeout: defaults.connectTimeoutMs,
27
+ authPlugins: {
28
+ mysql_clear_password: () => () => Buffer.from(password),
29
+ },
30
+ ...(ssl
31
+ ? {
32
+ ssl: {
33
+ rejectUnauthorized: ssl.rejectUnauthorized ?? false,
34
+ ...(ssl.ca ? { ca: readCACertificate(expandHome(ssl.ca)) } : {}),
35
+ ...(ssl.cert ? { cert: readSSLFile(expandHome(ssl.cert), 'client certificate') } : {}),
36
+ ...(ssl.key ? { key: readSSLFile(expandHome(ssl.key), 'client private key') } : {}),
37
+ },
38
+ }
39
+ : {}),
40
+ ...(instance.timezone ? { timezone: instance.timezone } : {}),
41
+ ...(instance.dateStrings ? { dateStrings: true } : {}),
42
+ ...(instance.bigNumberStrings ? { supportBigNumbers: true, bigNumberStrings: true } : {}),
43
+ };
44
+ }
45
+ function poolKey(spec, endpoint, password) {
46
+ const { instance } = spec;
47
+ const where = endpoint
48
+ ? `tunnel ${endpoint.host}:${endpoint.port}`
49
+ : (instance.socketPath ?? `${instance.host}:${instance.port}`);
50
+ const options = JSON.stringify([
51
+ spec.user,
52
+ createHash('sha256').update(password).digest('hex'),
53
+ spec.database ?? null,
54
+ instance.ssl ?? null,
55
+ instance.timezone ?? null,
56
+ instance.dateStrings ?? false,
57
+ instance.bigNumberStrings ?? false,
58
+ ]);
59
+ return `${where}\0${options}`;
60
+ }
61
+ function sessionKey(config) {
62
+ return [config.sshHost, config.sshPort, config.sshUser, config.privateKeyPath].join('\0');
63
+ }
64
+ function cacheUnlessRejected(map, key, create) {
65
+ let pending = map.get(key);
66
+ if (!pending) {
67
+ pending = create();
68
+ map.set(key, pending);
69
+ pending.catch(() => {
70
+ if (map.get(key) === pending) {
71
+ map.delete(key);
72
+ }
73
+ });
74
+ }
75
+ return pending;
76
+ }
77
+ export class ConnectionHandle {
78
+ spec;
79
+ registry;
80
+ endpoint = null;
81
+ constructor(spec, registry) {
82
+ this.spec = spec;
83
+ this.registry = registry;
84
+ }
85
+ get name() {
86
+ return this.spec.name;
87
+ }
88
+ describeTransport() {
89
+ const bastion = this.spec.bastion;
90
+ if (!bastion) {
91
+ return null;
92
+ }
93
+ return `ssh tunnel: ${bastion.sshConfigHost ?? `${bastion.user}@${bastion.host}`}`;
94
+ }
95
+ getConnection() {
96
+ return this.registry.acquire(this);
97
+ }
98
+ }
99
+ export class ConnectionRegistry {
100
+ env;
101
+ handles = new Map();
102
+ sessions = new Map();
103
+ pools = new Map();
104
+ secrets;
105
+ resolveBastionConfig;
106
+ openSession;
107
+ createPool;
108
+ preparePool;
109
+ constructor(env, deps = {}) {
110
+ this.env = env;
111
+ this.secrets = deps.secrets ?? new SecretResolver();
112
+ this.resolveBastionConfig = deps.resolveBastion ?? ((bastion) => resolveBastion(bastion));
113
+ this.openSession = deps.openSession ?? ((config) => new SshSession(config));
114
+ this.createPool = deps.createPool ?? ((options) => mysql2.createPool(options));
115
+ this.preparePool = deps.preparePool;
116
+ for (const spec of env.connections) {
117
+ this.handles.set(spec.name, new ConnectionHandle(spec, this));
118
+ }
119
+ }
120
+ list() {
121
+ return [...this.handles.values()];
122
+ }
123
+ get(name) {
124
+ return this.handles.get(name);
125
+ }
126
+ async acquire(handle) {
127
+ const { spec } = handle;
128
+ const session = spec.bastion ? await this.sessionFor(spec.bastion) : null;
129
+ if (session?.fatalError) {
130
+ throw session.fatalError;
131
+ }
132
+ return withSecretRetry(this.secrets, spec.password, async (password) => {
133
+ const endpoint = session ? await session.openListener(spec.instance.host, spec.instance.port) : null;
134
+ const key = poolKey(spec, endpoint, password);
135
+ const pending = cacheUnlessRejected(this.pools, key, async () => {
136
+ const created = this.createPool(buildPoolOptions(spec, endpoint, password, this.env.defaults));
137
+ this.preparePool?.(created);
138
+ log('info', `MySQL pool created for connection "${spec.name}" (${spec.user}@${spec.instance.name})`);
139
+ return created;
140
+ });
141
+ const pool = await pending;
142
+ handle.endpoint = endpoint;
143
+ try {
144
+ return await pool.getConnection();
145
+ }
146
+ catch (error) {
147
+ if (isAccessDeniedError(error) && this.pools.get(key) === pending) {
148
+ this.pools.delete(key);
149
+ pool.end().catch((e) => log('error', 'Failed to close a rejected pool:', e));
150
+ }
151
+ throw error;
152
+ }
153
+ });
154
+ }
155
+ sessionFor(bastion) {
156
+ const config = this.resolveBastionConfig(bastion);
157
+ return cacheUnlessRejected(this.sessions, sessionKey(config), async () => {
158
+ const passphrase = bastion.passphrase ? await this.secrets.resolve(bastion.passphrase) : undefined;
159
+ return this.openSession(passphrase ? { ...config, passphrase } : config);
160
+ });
161
+ }
162
+ async close() {
163
+ const pools = [...this.pools.values()];
164
+ const sessions = [...this.sessions.values()];
165
+ this.pools.clear();
166
+ this.sessions.clear();
167
+ for (const result of await Promise.allSettled(pools)) {
168
+ if (result.status === 'fulfilled') {
169
+ await result.value.end().catch((error) => log('error', 'Failed to close a pool:', error));
170
+ }
171
+ }
172
+ for (const result of await Promise.allSettled(sessions)) {
173
+ if (result.status === 'fulfilled') {
174
+ await result.value.close();
175
+ }
176
+ }
177
+ }
178
+ }
@@ -1,5 +1,4 @@
1
1
  import SqlParser from 'node-sql-parser';
2
- import { MYSQL_DB } from './../config/index.js';
3
2
  import { log } from './../utils/index.js';
4
3
  const { Parser } = SqlParser;
5
4
  const parser = new Parser();
@@ -61,7 +60,7 @@ function databaseStatementName(node) {
61
60
  const schema = node.database?.schema?.[0]?.value;
62
61
  return typeof schema === 'string' ? schema : null;
63
62
  }
64
- function extractReferencedSchemas(sql) {
63
+ function extractReferencedSchemas(sql, defaultSchema = null) {
65
64
  let astOrArray;
66
65
  try {
67
66
  astOrArray = parser.astify(sql, { database: 'mysql' });
@@ -70,7 +69,6 @@ function extractReferencedSchemas(sql) {
70
69
  log('error', 'Failed to parse SQL for schema extraction:', err.message);
71
70
  return null;
72
71
  }
73
- const defaultSchema = MYSQL_DB ?? null;
74
72
  const schemas = new Set();
75
73
  const names = new Map();
76
74
  const deleteTargets = new Set();
@@ -0,0 +1,31 @@
1
+ import { ConnectionDatabase, sessionLimitPrimer } from '../db/index.js';
2
+ import { writeCapabilities } from '../db/permissions.js';
3
+ import { ConnectionRegistry } from '../db/registry.js';
4
+ export async function checkConnection(env, connection) {
5
+ const registry = new ConnectionRegistry(env, { preparePool: sessionLimitPrimer(env.defaults) });
6
+ try {
7
+ const handle = registry.get(connection);
8
+ if (!handle) {
9
+ throw new Error(`${env.name}에 ${connection} 연결이 없습니다.`);
10
+ }
11
+ const db = new ConnectionDatabase(handle, env);
12
+ const result = await db.executeReadOnlyQuery('SELECT 1 AS ok, CURRENT_USER() AS currentUser, VERSION() AS version');
13
+ if (result.isError) {
14
+ throw new Error(result.content.map((block) => block.text).join('\n'));
15
+ }
16
+ const [row] = JSON.parse(result.content[0].text);
17
+ const writes = writeCapabilities(handle.spec.write);
18
+ return [
19
+ `MySQL ${row.version}에 ${row.currentUser}(으)로 SELECT 1을 실행했습니다.`,
20
+ handle.spec.instance.disableReadOnlyTransactions
21
+ ? 'config에서 이 instance의 읽기 전용 트랜잭션을 껐습니다.'
22
+ : '읽기는 읽기 전용 트랜잭션 안에서 실행합니다.',
23
+ env.writeForbidden || writes.length === 0
24
+ ? '이 연결에서는 서버가 쓰기를 거부합니다.'
25
+ : `이 연결에서 서버가 허용하는 쓰기: ${writes.map((w) => w.label).join(', ')}`,
26
+ ];
27
+ }
28
+ finally {
29
+ await registry.close();
30
+ }
31
+ }
@@ -0,0 +1,26 @@
1
+ import { spawn } from 'child_process';
2
+ import * as path from 'path';
3
+ import { parseFlags } from '../config/args.js';
4
+ import { DEFAULT_CONFIG_PATH } from '../config/load.js';
5
+ import { expandHome } from '../ssh/config.js';
6
+ import { checkConnection } from './check.js';
7
+ import { terminalPrompter } from './prompt.js';
8
+ import { runInit } from './wizard.js';
9
+ function run(file, args, stdio) {
10
+ return new Promise((resolve) => {
11
+ const child = spawn(file, args, { stdio });
12
+ child.once('error', () => resolve(127));
13
+ child.once('close', (code) => resolve(code ?? 1));
14
+ });
15
+ }
16
+ export async function runInitCli(argv) {
17
+ const flags = parseFlags(argv, ['config']);
18
+ const configPath = path.resolve(expandHome(flags.config ?? DEFAULT_CONFIG_PATH));
19
+ return runInit(configPath, {
20
+ prompt: terminalPrompter(),
21
+ platform: process.platform,
22
+ runInteractive: (file, args) => run(file, args, 'inherit'),
23
+ runQuiet: (file, args) => run(file, args, 'ignore'),
24
+ checkConnection,
25
+ });
26
+ }
@@ -0,0 +1,95 @@
1
+ import * as fs from 'fs';
2
+ import * as path from 'path';
3
+ import { DEFAULT_CONFIG_PATH } from '../config/load.js';
4
+ import { CONFIG_VERSION, NAME_PATTERN, validateConfig } from '../config/schema.js';
5
+ export const KEYCHAIN_SERVICE = 'mysql-mcp';
6
+ export function keychainAccount(envName, connection) {
7
+ return `${envName}/${connection}`;
8
+ }
9
+ export function storeSecretCommand(platform, account) {
10
+ if (platform === 'darwin') {
11
+ return { file: 'security', args: ['add-generic-password', '-U', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'] };
12
+ }
13
+ if (platform === 'linux') {
14
+ return {
15
+ file: 'secret-tool',
16
+ args: ['store', `--label=${KEYCHAIN_SERVICE} ${account}`, 'service', KEYCHAIN_SERVICE, 'account', account],
17
+ };
18
+ }
19
+ return null;
20
+ }
21
+ export function secretExistsCommand(platform, account) {
22
+ if (platform === 'darwin') {
23
+ return { file: 'security', args: ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account] };
24
+ }
25
+ return null;
26
+ }
27
+ function bastionName(config, alias, envName) {
28
+ const bastions = config.bastions ?? {};
29
+ for (const [name, bastion] of Object.entries(bastions)) {
30
+ if (bastion.sshConfigHost === alias && !bastion.host) {
31
+ return name;
32
+ }
33
+ }
34
+ for (const candidate of [alias, envName]) {
35
+ if (NAME_PATTERN.test(candidate) && !bastions[candidate]) {
36
+ return candidate;
37
+ }
38
+ }
39
+ let index = 2;
40
+ while (bastions[`${envName}-${index}`]) {
41
+ index += 1;
42
+ }
43
+ return `${envName}-${index}`;
44
+ }
45
+ export function applyAccount(config, draft) {
46
+ const next = structuredClone(config ?? { version: CONFIG_VERSION, environments: {} });
47
+ let env = next.environments[draft.envName];
48
+ if (!env) {
49
+ env = { instances: {}, accounts: {} };
50
+ if (draft.bastionAlias) {
51
+ const name = bastionName(next, draft.bastionAlias, draft.envName);
52
+ next.bastions = { ...next.bastions, [name]: { sshConfigHost: draft.bastionAlias } };
53
+ env.bastion = name;
54
+ }
55
+ next.environments[draft.envName] = env;
56
+ }
57
+ if (!env.instances[draft.instance.name]) {
58
+ env.instances[draft.instance.name] = {
59
+ ...(draft.instance.host ? { host: draft.instance.host } : {}),
60
+ ...(draft.instance.port && draft.instance.port !== 3306 ? { port: draft.instance.port } : {}),
61
+ };
62
+ }
63
+ env.accounts[draft.connection] = {
64
+ instance: draft.instance.name,
65
+ user: draft.user,
66
+ password: draft.password,
67
+ ...(draft.database ? { database: draft.database } : {}),
68
+ };
69
+ return validateConfig(JSON.parse(JSON.stringify(next)));
70
+ }
71
+ export async function writeConfigAtomic(configPath, config) {
72
+ const dir = path.dirname(configPath);
73
+ await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 });
74
+ const tempPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
75
+ try {
76
+ await fs.promises.writeFile(tempPath, `${JSON.stringify(config, null, 2)}\n`, {
77
+ encoding: 'utf8',
78
+ mode: 0o600,
79
+ flag: 'wx',
80
+ });
81
+ await fs.promises.rename(tempPath, configPath);
82
+ }
83
+ catch (error) {
84
+ await fs.promises.rm(tempPath, { force: true });
85
+ throw error;
86
+ }
87
+ await fs.promises.chmod(configPath, 0o600);
88
+ }
89
+ export function mcpAddCommand(envName, configPath) {
90
+ const config = path.resolve(configPath) === DEFAULT_CONFIG_PATH ? '' : ` --config ${shellWord(configPath)}`;
91
+ return `claude mcp add mysql-${envName} -- npx -y @ecubelabs/mysql-mcp --env ${envName}${config}`;
92
+ }
93
+ function shellWord(value) {
94
+ return /^[A-Za-z0-9_./~-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
95
+ }
@@ -0,0 +1,82 @@
1
+ import * as readline from 'node:readline/promises';
2
+ export function terminalPrompter(input = process.stdin, output = process.stdout) {
3
+ let rl = null;
4
+ const lines = [];
5
+ let waiting = null;
6
+ let ended = false;
7
+ const open = () => {
8
+ if (rl) {
9
+ return;
10
+ }
11
+ ended = false;
12
+ rl = readline.createInterface({ input, terminal: false });
13
+ rl.on('line', (line) => {
14
+ const resolve = waiting;
15
+ waiting = null;
16
+ if (resolve) {
17
+ resolve(line);
18
+ }
19
+ else {
20
+ lines.push(line);
21
+ }
22
+ });
23
+ rl.on('close', () => {
24
+ ended = true;
25
+ const resolve = waiting;
26
+ waiting = null;
27
+ resolve?.(null);
28
+ });
29
+ };
30
+ const question = async (text) => {
31
+ open();
32
+ output.write(text);
33
+ const queued = lines.shift();
34
+ const line = queued ?? (ended ? null : await new Promise((resolve) => (waiting = resolve)));
35
+ if (line === null) {
36
+ output.write('\n');
37
+ throw new Error('init이 끝나기 전에 입력이 끝나 아무것도 저장하지 않았습니다.');
38
+ }
39
+ return line.trim();
40
+ };
41
+ const prompter = {
42
+ say(text) {
43
+ output.write(`${text}\n`);
44
+ },
45
+ async ask(text, fallback) {
46
+ const answer = await question(fallback ? `${text} [${fallback}]: ` : `${text}: `);
47
+ return answer || fallback || '';
48
+ },
49
+ async choose(text, options, fallback = 0) {
50
+ prompter.say(text);
51
+ options.forEach((option, index) => prompter.say(` ${index + 1}) ${option}`));
52
+ for (;;) {
53
+ const answer = await prompter.ask('번호를 고르세요', String(fallback + 1));
54
+ const index = Number(answer) - 1;
55
+ if (Number.isInteger(index) && index >= 0 && index < options.length) {
56
+ return index;
57
+ }
58
+ prompter.say(`1부터 ${options.length} 사이의 번호를 입력해 주세요.`);
59
+ }
60
+ },
61
+ async confirm(text, fallback = false) {
62
+ for (;;) {
63
+ const answer = (await question(`${text} ${fallback ? '[Y/n]' : '[y/N]'}: `)).toLowerCase();
64
+ if (!answer) {
65
+ return fallback;
66
+ }
67
+ if (['y', 'yes', '예', '네'].includes(answer)) {
68
+ return true;
69
+ }
70
+ if (['n', 'no', '아니오', '아니요'].includes(answer)) {
71
+ return false;
72
+ }
73
+ }
74
+ },
75
+ release() {
76
+ const current = rl;
77
+ rl = null;
78
+ current?.close();
79
+ },
80
+ };
81
+ return prompter;
82
+ }