@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.
@@ -0,0 +1,223 @@
1
+ import * as fs from 'fs';
2
+ import { isWriteForbiddenEnv, permissionProblems, readConfigFile, resolveEnvironment } from '../config/load.js';
3
+ import { ConfigValidationError, NAME_PATTERN } from '../config/schema.js';
4
+ import { listHostAliases, readSSHConfigHost } from '../ssh/config.js';
5
+ import { applyAccount, keychainAccount, KEYCHAIN_SERVICE, mcpAddCommand, secretExistsCommand, storeSecretCommand, writeConfigAtomic, } from './config-edit.js';
6
+ const ENV_VAR_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
7
+ async function askName(prompt, question, fallback) {
8
+ for (;;) {
9
+ const value = await prompt.ask(question, fallback);
10
+ if (NAME_PATTERN.test(value)) {
11
+ return value;
12
+ }
13
+ prompt.say('영문자, 숫자, ".", "_", "-"만 쓸 수 있고, 영문자나 숫자로 시작해야 합니다.');
14
+ }
15
+ }
16
+ async function askRequired(prompt, question, fallback) {
17
+ for (;;) {
18
+ const value = await prompt.ask(question, fallback);
19
+ if (value) {
20
+ return value;
21
+ }
22
+ prompt.say('값을 입력해 주세요.');
23
+ }
24
+ }
25
+ async function askPort(prompt, fallback = 3306) {
26
+ for (;;) {
27
+ const port = Number(await prompt.ask('포트', String(fallback)));
28
+ if (Number.isInteger(port) && port >= 1 && port <= 65535) {
29
+ return port;
30
+ }
31
+ prompt.say('1부터 65535 사이의 포트를 입력해 주세요.');
32
+ }
33
+ }
34
+ function instanceNameFromHost(host) {
35
+ if (/^[\d.]+$/.test(host) || host.includes(':')) {
36
+ return undefined;
37
+ }
38
+ const first = host.split('.')[0]?.replace(/[^A-Za-z0-9_.-]/g, '-');
39
+ return first && NAME_PATTERN.test(first) ? first : undefined;
40
+ }
41
+ async function askBastion(prompt, deps) {
42
+ const aliases = listHostAliases(deps.sshConfigPath);
43
+ if (aliases.length === 0) {
44
+ prompt.say('~/.ssh/config에 Host alias가 없습니다.');
45
+ if (await prompt.confirm('SSH bastion 없이 MySQL에 직접 접속할까요?', false)) {
46
+ return null;
47
+ }
48
+ throw new Error('~/.ssh/config에 bastion을 Host alias로 추가하고 `ssh <alias>`로 한 번 접속한 뒤 init을 다시 실행해 주세요.');
49
+ }
50
+ const direct = 'bastion 없음 (MySQL에 직접 접속)';
51
+ const index = await prompt.choose('이 환경의 bastion은 ~/.ssh/config의 어느 Host입니까?', [...aliases, direct]);
52
+ return index === aliases.length ? null : aliases[index];
53
+ }
54
+ async function askPassword(prompt, deps, envName, connection) {
55
+ const store = storeSecretCommand(deps.platform, keychainAccount(envName, connection));
56
+ const options = [
57
+ ...(store ? ['지금 OS 키체인에 저장 (권장)'] : []),
58
+ 'MCP 서버의 환경 변수에서 읽기',
59
+ '명령의 출력에서 읽기 (예: 비밀번호 관리자 CLI)',
60
+ ];
61
+ const choice = await prompt.choose('서버가 MySQL 비밀번호를 어디서 읽을까요?', options);
62
+ const kind = store ? ['keychain', 'env', 'command'][choice] : ['env', 'command'][choice];
63
+ if (kind === 'env') {
64
+ for (;;) {
65
+ const name = await prompt.ask('환경 변수 이름');
66
+ if (ENV_VAR_PATTERN.test(name)) {
67
+ prompt.say(`서버를 띄우는 MCP 클라이언트의 환경에 ${name}을(를) 설정해 주세요.`);
68
+ return { env: name };
69
+ }
70
+ prompt.say('영문자, 숫자, "_"만 쓸 수 있고, 숫자로 시작할 수 없습니다.');
71
+ }
72
+ }
73
+ if (kind === 'command') {
74
+ const line = await askRequired(prompt, '비밀번호를 출력하는 명령 (셸 없이 실행하며 공백으로 인자를 나눕니다)');
75
+ return { command: line.split(/\s+/) };
76
+ }
77
+ const account = keychainAccount(envName, connection);
78
+ const exists = secretExistsCommand(deps.platform, account);
79
+ if (exists && (await deps.runQuiet(exists.file, exists.args)) === 0) {
80
+ if (!(await prompt.confirm(`${account} 키체인 항목이 이미 있습니다. 비밀번호를 바꿀까요?`, false))) {
81
+ return { keychain: { service: KEYCHAIN_SERVICE, account } };
82
+ }
83
+ }
84
+ for (;;) {
85
+ prompt.say(`이제 ${store.file}이(가) 이 MySQL 계정의 비밀번호를 묻습니다. ` +
86
+ '거기에 입력해 주세요. 화면에 보이지 않고, 이 프로그램을 거치지 않습니다.');
87
+ prompt.release();
88
+ const code = await deps.runInteractive(store.file, store.args);
89
+ if (code === 0) {
90
+ return { keychain: { service: KEYCHAIN_SERVICE, account } };
91
+ }
92
+ prompt.say(`${store.file}이(가) 종료 코드 ${code}로 끝나 비밀번호가 저장되지 않았습니다.`);
93
+ if (!(await prompt.confirm('다시 시도할까요?', true))) {
94
+ throw new Error('비밀번호가 저장되지 않아 아무것도 저장하지 않았습니다.');
95
+ }
96
+ }
97
+ }
98
+ async function askAccount(prompt, deps, config, envName) {
99
+ const env = config?.environments[envName];
100
+ const draft = { envName };
101
+ if (!env) {
102
+ draft.bastionAlias = await askBastion(prompt, deps);
103
+ }
104
+ const instances = Object.keys(env?.instances ?? {});
105
+ const newInstance = '새 instance';
106
+ const picked = instances.length > 0 ? await prompt.choose('어느 MySQL instance입니까?', [...instances, newInstance]) : 0;
107
+ if (picked < instances.length) {
108
+ draft.instance = { name: instances[picked] };
109
+ }
110
+ else {
111
+ const alias = draft.bastionAlias ?? (env?.bastion ? config?.bastions[env.bastion]?.sshConfigHost : undefined);
112
+ const forward = alias ? readSSHConfigHost(alias, deps.sshConfigPath)?.forwardTarget : undefined;
113
+ const via = draft.bastionAlias ?? (env?.bastion ? 'bastion' : null);
114
+ const host = await askRequired(prompt, via ? `${via}에서 본 MySQL host` : '이 컴퓨터에서 본 MySQL host', forward?.host);
115
+ const port = await askPort(prompt, forward && forward.host === host ? forward.port : 3306);
116
+ const taken = new Set(instances);
117
+ let name;
118
+ for (;;) {
119
+ name = await askName(prompt, '이 instance의 이름', instanceNameFromHost(host));
120
+ if (!taken.has(name)) {
121
+ break;
122
+ }
123
+ prompt.say(`${envName}에 ${name} instance가 이미 있습니다.`);
124
+ }
125
+ draft.instance = { name, host, port };
126
+ }
127
+ for (;;) {
128
+ draft.connection = await askName(prompt, '연결 이름 (모델이 "connection" 인자로 고르는 이름)');
129
+ if (!env?.accounts[draft.connection]) {
130
+ break;
131
+ }
132
+ if (await prompt.confirm(`${envName}에 ${draft.connection} 연결이 이미 있습니다. 바꿀까요?`, false)) {
133
+ break;
134
+ }
135
+ }
136
+ draft.user = await askRequired(prompt, 'MySQL 사용자');
137
+ const database = await prompt.ask('기본 schema (없으면 Enter)');
138
+ if (database) {
139
+ draft.database = database;
140
+ }
141
+ draft.password = await askPassword(prompt, deps, envName, draft.connection);
142
+ return draft;
143
+ }
144
+ export async function runInit(configPath, deps) {
145
+ const { prompt } = deps;
146
+ let config = null;
147
+ if (fs.existsSync(configPath)) {
148
+ try {
149
+ config = readConfigFile(configPath, { platform: deps.platform });
150
+ }
151
+ catch (error) {
152
+ prompt.say(`init을 멈췄습니다: ${error.message}`);
153
+ return 1;
154
+ }
155
+ prompt.say(`${configPath}에 추가합니다.`);
156
+ }
157
+ else {
158
+ prompt.say(`${configPath}을(를) 새로 만듭니다.`);
159
+ }
160
+ try {
161
+ const known = Object.keys(config?.environments ?? {});
162
+ if (known.length > 0) {
163
+ prompt.say(`config에 있는 환경: ${known.join(', ')}`);
164
+ }
165
+ const envName = await askName(prompt, '환경 이름', known[0] ?? 'stage');
166
+ if (isWriteForbiddenEnv(envName)) {
167
+ prompt.say(`${envName}은(는) 언제나 읽기 전용입니다. config에 무엇을 적어도 서버가 쓰기를 거부합니다.`);
168
+ }
169
+ let changed = false;
170
+ for (;;) {
171
+ const draft = await askAccount(prompt, deps, config, envName);
172
+ let next;
173
+ try {
174
+ next = applyAccount(config, draft);
175
+ }
176
+ catch (error) {
177
+ if (!(error instanceof ConfigValidationError)) {
178
+ throw error;
179
+ }
180
+ prompt.say(`이 연결로는 올바른 config가 되지 않습니다:\n${error.message}`);
181
+ continue;
182
+ }
183
+ prompt.say(`${draft.connection} 연결을 시험합니다...`);
184
+ let saved = true;
185
+ try {
186
+ const env = resolveEnvironment(next, envName, { configPath });
187
+ for (const line of await deps.checkConnection(env, draft.connection)) {
188
+ prompt.say(` ${line}`);
189
+ }
190
+ }
191
+ catch (error) {
192
+ prompt.say(` 시험에 실패했습니다: ${error.message}`);
193
+ saved = await prompt.confirm(`그래도 ${draft.connection} 연결을 저장할까요?`, false);
194
+ }
195
+ if (saved) {
196
+ config = next;
197
+ changed = true;
198
+ }
199
+ if (!(await prompt.confirm(`${envName}에 연결을 더 추가할까요?`, false))) {
200
+ break;
201
+ }
202
+ }
203
+ if (!changed || !config) {
204
+ prompt.say('저장할 것이 없습니다.');
205
+ return 0;
206
+ }
207
+ await writeConfigAtomic(configPath, config);
208
+ prompt.say(`${configPath}을(를) 썼습니다.`);
209
+ for (const problem of permissionProblems(configPath, { platform: deps.platform })) {
210
+ prompt.say(` 이 문제를 고치기 전에는 서버가 뜨지 않습니다: ${problem}`);
211
+ }
212
+ prompt.say('Claude Code에 서버를 등록하는 명령:');
213
+ prompt.say(` ${mcpAddCommand(envName, configPath)}`);
214
+ return 0;
215
+ }
216
+ catch (error) {
217
+ prompt.say(`init을 멈췄습니다: ${error.message}`);
218
+ return 1;
219
+ }
220
+ finally {
221
+ prompt.release();
222
+ }
223
+ }
@@ -0,0 +1,91 @@
1
+ export async function runCatalogAction(catalog, args) {
2
+ if (!catalog.isEnabled()) {
3
+ throw new Error('The schema catalog is disabled.');
4
+ }
5
+ const action = args.action;
6
+ if (action === 'map') {
7
+ return catalog.map();
8
+ }
9
+ else if (action === 'search') {
10
+ if (typeof args.q !== 'string' || !args.q.trim()) {
11
+ throw new Error('mysql_catalog search requires a non-empty "q".');
12
+ }
13
+ return catalog.search(args.q, typeof args.limit === 'number' ? args.limit : undefined);
14
+ }
15
+ else if (action === 'describe') {
16
+ if (typeof args.table !== 'string' || !args.table.trim()) {
17
+ throw new Error('mysql_catalog describe requires "table" as schema.table.');
18
+ }
19
+ return catalog.describe(args.table);
20
+ }
21
+ else if (action === 'link') {
22
+ if (!Array.isArray(args.links) ||
23
+ !args.links.every((link) => link &&
24
+ typeof link === 'object' &&
25
+ typeof link.table === 'string' &&
26
+ typeof link.doc === 'string' &&
27
+ typeof link.repo === 'string')) {
28
+ throw new Error('mysql_catalog link requires "links" as [{table, doc, repo}, ...].');
29
+ }
30
+ return catalog.link(args.links);
31
+ }
32
+ else if (action === 'unlink') {
33
+ if (typeof args.table !== 'string' || !args.table.trim()) {
34
+ throw new Error('mysql_catalog unlink requires "table" as schema.table.');
35
+ }
36
+ return catalog.unlink(args.table);
37
+ }
38
+ else if (action === 'note') {
39
+ if (typeof args.target !== 'string' || !args.target.trim()) {
40
+ throw new Error('mysql_catalog note requires "target" as schema.table, or a schema name for a schema memo.');
41
+ }
42
+ const hasText = typeof args.text === 'string' && args.text.trim().length > 0;
43
+ const hasAlias = typeof args.alias === 'string' && args.alias.trim().length > 0;
44
+ if (hasText === hasAlias) {
45
+ throw new Error('mysql_catalog note requires exactly one non-empty "text" or "alias".');
46
+ }
47
+ return catalog.note(args.target, {
48
+ ...(hasText ? { text: args.text } : {}),
49
+ ...(hasAlias ? { alias: args.alias } : {}),
50
+ });
51
+ }
52
+ else if (action === 'forget') {
53
+ if (typeof args.target !== 'string' || !args.target.trim()) {
54
+ throw new Error('mysql_catalog forget requires "target" as schema.table, or a schema name for its notes.');
55
+ }
56
+ const scopes = new Set(['notes', 'aliases', 'usage', 'joins', 'metadata']);
57
+ if (typeof args.scope !== 'string' || !scopes.has(args.scope)) {
58
+ throw new Error('mysql_catalog forget requires "scope" as notes, aliases, usage, joins, or metadata.');
59
+ }
60
+ return catalog.forget(args.target, args.scope);
61
+ }
62
+ else if (action === 'branch') {
63
+ if (typeof args.repo !== 'string' ||
64
+ !args.repo.trim() ||
65
+ typeof args.branch !== 'string' ||
66
+ !args.branch.trim()) {
67
+ throw new Error('mysql_catalog branch requires "repo" and "branch", e.g. {repo: "owner/name", branch: "develop"}.');
68
+ }
69
+ return catalog.setCodeBranch(args.repo, args.branch);
70
+ }
71
+ else if (action === 'owner') {
72
+ if (typeof args.target !== 'string' ||
73
+ !args.target.trim() ||
74
+ typeof args.repo !== 'string' ||
75
+ !args.repo.trim() ||
76
+ typeof args.app !== 'string' ||
77
+ !args.app.trim()) {
78
+ throw new Error('mysql_catalog owner requires "target", "repo" and "app", e.g. {target: "haulla", repo: "owner/name", app: "core-api"}.');
79
+ }
80
+ return catalog.setSchemaOwner(args.target, args.repo, args.app);
81
+ }
82
+ else if (action === 'refresh') {
83
+ if (args.target !== undefined && typeof args.target !== 'string') {
84
+ throw new Error('mysql_catalog refresh takes "target" as a string.');
85
+ }
86
+ return catalog.refresh(args.target);
87
+ }
88
+ else {
89
+ throw new Error(`Unknown mysql_catalog action: ${String(action)}`);
90
+ }
91
+ }
@@ -0,0 +1,117 @@
1
+ import { codeRevisionDescription } from '../catalog/branch.js';
2
+ import { renderToolDescriptionSuffix } from '../catalog/render.js';
3
+ import { normalizeName } from '../catalog/types.js';
4
+ import { describeWriteMode } from '../db/index.js';
5
+ import { writeCapabilities } from '../db/permissions.js';
6
+ import { extractReferencedSchemas } from '../db/utils.js';
7
+ export const TOOL_DESCRIPTION_LIMIT = 2048;
8
+ export function allReadOnly(env, runtimes) {
9
+ return env.writeForbidden || runtimes.every((rt) => writeCapabilities(rt.spec.write).length === 0);
10
+ }
11
+ function connectionLine(env, rt, schemaLimit = Infinity) {
12
+ const schemas = rt.catalog.schemaNames();
13
+ let visible;
14
+ if (schemas.length === 0) {
15
+ visible = 'schemas not yet scanned';
16
+ }
17
+ else if (schemas.length <= schemaLimit) {
18
+ visible = `schemas ${schemas.join(', ')}`;
19
+ }
20
+ else if (schemaLimit === 0) {
21
+ visible = `${schemas.length} schemas (see mysql_catalog map)`;
22
+ }
23
+ else {
24
+ visible = `schemas ${schemas.slice(0, schemaLimit).join(', ')} and ${schemas.length - schemaLimit} more`;
25
+ }
26
+ const parts = [rt.spec.instance.name, `user ${rt.spec.user}`, visible];
27
+ const capabilities = writeCapabilities(rt.spec.write);
28
+ if (!env.writeForbidden && capabilities.length > 0) {
29
+ parts.push(describeWriteMode(false, capabilities));
30
+ }
31
+ return `${rt.name}: ${parts.join(', ')}`;
32
+ }
33
+ const CONNECTIONS_HEADING = '\n\nCONNECTIONS (pass one as "connection"; each is one database account, so a query cannot JOIN across connections):';
34
+ export function connectionsBlock(env, runtimes, budget) {
35
+ const render = (limit) => CONNECTIONS_HEADING + runtimes.map((rt) => `\n- ${connectionLine(env, rt, limit)}`).join('');
36
+ const widest = Math.max(0, ...runtimes.map((rt) => rt.catalog.schemaNames().length));
37
+ for (let limit = widest; limit > 0; limit--) {
38
+ const block = render(limit);
39
+ if (block.length <= budget) {
40
+ return block;
41
+ }
42
+ }
43
+ return render(0);
44
+ }
45
+ export function queryToolDescription(env, runtimes, version) {
46
+ const { defaults } = env;
47
+ let head = `[MySQL MCP Server [v${version}]] Run SQL queries against the ${env.label} MySQL environment`;
48
+ head += env.writeForbidden
49
+ ? ` — ENVIRONMENT: ${env.label}, STRICTLY READ-ONLY (writes are refused by policy)`
50
+ : ` — ENVIRONMENT: ${env.label}`;
51
+ head += allReadOnly(env, runtimes) ? ' (READ-ONLY)' : ' (writes depend on the connection; see CONNECTIONS)';
52
+ const limits = `\n\nLIMITS: every read is cancelled after ${defaults.defaultTimeoutSeconds}s ` +
53
+ `(raise per call with timeout_seconds, up to ${defaults.maxTimeoutSeconds}) and returns at most ` +
54
+ `${defaults.maxResponseRows.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
55
+ `USE and SET are rejected; write schema.table instead of USE. ` +
56
+ `Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
57
+ const qualify = '\n\nQualify every table with its schema (schema.table). ' +
58
+ 'A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `my-schema`.some_table.';
59
+ const branches = {};
60
+ for (const rt of runtimes) {
61
+ Object.assign(branches, rt.catalog.codeBranches());
62
+ }
63
+ const revision = codeRevisionDescription(branches);
64
+ const fixed = head.length + limits.length + qualify.length + revision.length;
65
+ const connections = connectionsBlock(env, runtimes, TOOL_DESCRIPTION_LIMIT - fixed);
66
+ const base = head + connections + limits + qualify + revision;
67
+ const snapshots = runtimes
68
+ .map((rt) => ({ connection: rt.name, catalog: rt.catalog.descriptionSnapshot() }))
69
+ .filter((entry) => entry.catalog !== null);
70
+ const suffix = snapshots.length > 0 ? renderToolDescriptionSuffix(snapshots, TOOL_DESCRIPTION_LIMIT - base.length) : '';
71
+ return { text: base + suffix, overflow: Math.max(0, base.length - TOOL_DESCRIPTION_LIMIT) };
72
+ }
73
+ function connectionChoices(runtimes) {
74
+ return runtimes
75
+ .map((rt) => {
76
+ const schemas = rt.catalog.schemaNames();
77
+ const visible = schemas.length > 0 ? `schemas: ${schemas.join(', ')}` : 'schemas not yet scanned';
78
+ return `${rt.name} (${rt.spec.instance.name}, user ${rt.spec.user}; ${visible})`;
79
+ })
80
+ .join('; ');
81
+ }
82
+ export function resolveConnection(env, runtimes, value) {
83
+ if (typeof value !== 'string' || value.trim() === '') {
84
+ throw new Error(`The "connection" argument is required. Connections in ${env.label}: ${connectionChoices(runtimes)}.`);
85
+ }
86
+ const found = runtimes.find((rt) => rt.name === value);
87
+ if (!found) {
88
+ throw new Error(`Unknown connection "${value}". Connections in ${env.label}: ${connectionChoices(runtimes)}.`);
89
+ }
90
+ return found;
91
+ }
92
+ export function schemaVisibilityHint(runtimes, chosen, sql) {
93
+ const visible = new Set(chosen.catalog.schemaNames().map(normalizeName));
94
+ if (visible.size === 0) {
95
+ return null;
96
+ }
97
+ const referenced = extractReferencedSchemas(sql, chosen.spec.database ?? null) ?? [];
98
+ const facts = [];
99
+ const seen = new Set();
100
+ for (const schema of referenced) {
101
+ if (!schema || visible.has(normalizeName(schema)) || seen.has(normalizeName(schema))) {
102
+ continue;
103
+ }
104
+ seen.add(normalizeName(schema));
105
+ const elsewhere = runtimes
106
+ .filter((rt) => rt !== chosen && rt.catalog.schemaNames().some((name) => sameName(name, schema)))
107
+ .map((rt) => rt.name);
108
+ facts.push(`Schema "${schema}" is not visible on connection "${chosen.name}" (user ${chosen.spec.user}). ` +
109
+ (elsewhere.length > 0
110
+ ? `Visible on: ${elsewhere.join(', ')}.`
111
+ : 'No other connection in this environment lists it either.'));
112
+ }
113
+ return facts.length > 0 ? facts.join(' ') : null;
114
+ }
115
+ function sameName(a, b) {
116
+ return normalizeName(a) === normalizeName(b);
117
+ }
@@ -38,37 +38,16 @@ function splitDirective(line) {
38
38
  }
39
39
  return [keyword, value];
40
40
  }
41
- function parseLocalForward(value) {
41
+ function parseForwardTarget(value) {
42
42
  const parts = value.split(/\s+/).filter(Boolean);
43
- if (parts.length < 2) {
43
+ const remote = parts[1];
44
+ if (!remote) {
44
45
  return null;
45
46
  }
46
- const localRaw = parts[0];
47
- const localPortStr = localRaw.includes(':') ? localRaw.slice(localRaw.lastIndexOf(':') + 1) : localRaw;
48
- const localPort = Number(localPortStr);
49
- if (!Number.isInteger(localPort) || localPort < 0 || localPort > 65535) {
50
- return null;
51
- }
52
- let remoteHost;
53
- let remotePortStr;
54
- const remoteRaw = parts[1];
55
- const lastColon = remoteRaw.lastIndexOf(':');
56
- if (lastColon > 0) {
57
- remoteHost = remoteRaw.slice(0, lastColon);
58
- remotePortStr = remoteRaw.slice(lastColon + 1);
59
- }
60
- else if (parts.length >= 3) {
61
- remoteHost = remoteRaw;
62
- remotePortStr = parts[2];
63
- }
64
- else {
65
- return null;
66
- }
67
- const remotePort = Number(remotePortStr);
68
- if (!remoteHost || !Number.isInteger(remotePort) || remotePort <= 0) {
69
- return null;
70
- }
71
- return { localPort, remoteHost, remotePort };
47
+ const colon = remote.lastIndexOf(':');
48
+ const host = colon > 0 ? remote.slice(0, colon) : remote;
49
+ const port = Number(colon > 0 ? remote.slice(colon + 1) : parts[2]);
50
+ return host && Number.isInteger(port) && port > 0 && port <= 65535 ? { host, port } : null;
72
51
  }
73
52
  export function readSSHConfigHost(alias, configPath = path.join(os.homedir(), '.ssh', 'config')) {
74
53
  if (!fs.existsSync(configPath)) {
@@ -131,16 +110,30 @@ export function readSSHConfigHost(alias, configPath = path.join(os.homedir(), '.
131
110
  case 'hostkeyalias':
132
111
  entry.hostKeyAlias ??= value;
133
112
  break;
134
- case 'localforward': {
135
- const forward = parseLocalForward(value);
136
- if (forward && !entry.localForward) {
137
- entry.localForward = forward;
138
- }
113
+ case 'localforward':
114
+ entry.forwardTarget ??= parseForwardTarget(value) ?? undefined;
139
115
  break;
140
- }
141
116
  default:
142
117
  break;
143
118
  }
144
119
  }
145
120
  return found ? entry : null;
146
121
  }
122
+ export function listHostAliases(configPath = path.join(os.homedir(), '.ssh', 'config')) {
123
+ if (!fs.existsSync(configPath)) {
124
+ return [];
125
+ }
126
+ const aliases = new Set();
127
+ for (const line of fs.readFileSync(configPath, 'utf8').split(/\r?\n/)) {
128
+ const directive = splitDirective(line);
129
+ if (!directive || directive[0] !== 'host') {
130
+ continue;
131
+ }
132
+ for (const token of directive[1].split(/\s+/)) {
133
+ if (token && !/[*?!]/.test(token)) {
134
+ aliases.add(token);
135
+ }
136
+ }
137
+ }
138
+ return [...aliases];
139
+ }