postgresai 0.12.0-beta.6 → 0.14.0-dev.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.
- package/README.md +91 -2
- package/bin/postgres-ai.ts +552 -37
- package/dist/bin/postgres-ai.js +503 -26
- package/dist/bin/postgres-ai.js.map +1 -1
- package/dist/lib/init.d.ts +61 -0
- package/dist/lib/init.d.ts.map +1 -0
- package/dist/lib/init.js +359 -0
- package/dist/lib/init.js.map +1 -0
- package/dist/lib/issues.d.ts +69 -1
- package/dist/lib/issues.d.ts.map +1 -1
- package/dist/lib/issues.js +232 -1
- package/dist/lib/issues.js.map +1 -1
- package/dist/lib/mcp-server.d.ts.map +1 -1
- package/dist/lib/mcp-server.js +69 -15
- package/dist/lib/mcp-server.js.map +1 -1
- package/dist/package.json +3 -2
- package/lib/init.ts +404 -0
- package/lib/issues.ts +325 -3
- package/lib/mcp-server.ts +75 -17
- package/package.json +3 -2
- package/test/init.integration.test.cjs +269 -0
- package/test/init.test.cjs +69 -0
package/lib/init.ts
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
import * as readline from "readline";
|
|
2
|
+
import { URL } from "url";
|
|
3
|
+
import type { Client as PgClient } from "pg";
|
|
4
|
+
|
|
5
|
+
export type PgClientConfig = {
|
|
6
|
+
connectionString?: string;
|
|
7
|
+
host?: string;
|
|
8
|
+
port?: number;
|
|
9
|
+
user?: string;
|
|
10
|
+
password?: string;
|
|
11
|
+
database?: string;
|
|
12
|
+
ssl?: any;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export type AdminConnection = {
|
|
16
|
+
clientConfig: PgClientConfig;
|
|
17
|
+
display: string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type InitStep = {
|
|
21
|
+
name: string;
|
|
22
|
+
sql: string;
|
|
23
|
+
params?: unknown[];
|
|
24
|
+
optional?: boolean;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type InitPlan = {
|
|
28
|
+
monitoringUser: string;
|
|
29
|
+
database: string;
|
|
30
|
+
steps: InitStep[];
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function quoteIdent(ident: string): string {
|
|
34
|
+
// Always quote. Escape embedded quotes by doubling.
|
|
35
|
+
return `"${ident.replace(/"/g, "\"\"")}"`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function maskConnectionString(dbUrl: string): string {
|
|
39
|
+
// Hide password if present (postgresql://user:pass@host/db).
|
|
40
|
+
try {
|
|
41
|
+
const u = new URL(dbUrl);
|
|
42
|
+
if (u.password) u.password = "*****";
|
|
43
|
+
return u.toString();
|
|
44
|
+
} catch {
|
|
45
|
+
return dbUrl.replace(/\/\/([^:/?#]+):([^@/?#]+)@/g, "//$1:*****@");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function isLikelyUri(value: string): boolean {
|
|
50
|
+
return /^postgres(ql)?:\/\//i.test(value.trim());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function tokenizeConninfo(input: string): string[] {
|
|
54
|
+
const s = input.trim();
|
|
55
|
+
const tokens: string[] = [];
|
|
56
|
+
let i = 0;
|
|
57
|
+
|
|
58
|
+
const isSpace = (ch: string) => ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
|
|
59
|
+
|
|
60
|
+
while (i < s.length) {
|
|
61
|
+
while (i < s.length && isSpace(s[i]!)) i++;
|
|
62
|
+
if (i >= s.length) break;
|
|
63
|
+
|
|
64
|
+
let tok = "";
|
|
65
|
+
let inSingle = false;
|
|
66
|
+
while (i < s.length) {
|
|
67
|
+
const ch = s[i]!;
|
|
68
|
+
if (!inSingle && isSpace(ch)) break;
|
|
69
|
+
|
|
70
|
+
if (ch === "'" && !inSingle) {
|
|
71
|
+
inSingle = true;
|
|
72
|
+
i++;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (ch === "'" && inSingle) {
|
|
76
|
+
inSingle = false;
|
|
77
|
+
i++;
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (ch === "\\" && i + 1 < s.length) {
|
|
82
|
+
tok += s[i + 1]!;
|
|
83
|
+
i += 2;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
tok += ch;
|
|
88
|
+
i++;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
tokens.push(tok);
|
|
92
|
+
while (i < s.length && isSpace(s[i]!)) i++;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return tokens;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function parseLibpqConninfo(input: string): PgClientConfig {
|
|
99
|
+
const tokens = tokenizeConninfo(input);
|
|
100
|
+
const cfg: PgClientConfig = {};
|
|
101
|
+
|
|
102
|
+
for (const t of tokens) {
|
|
103
|
+
const eq = t.indexOf("=");
|
|
104
|
+
if (eq <= 0) continue;
|
|
105
|
+
const key = t.slice(0, eq).trim();
|
|
106
|
+
const rawVal = t.slice(eq + 1);
|
|
107
|
+
const val = rawVal.trim();
|
|
108
|
+
if (!key) continue;
|
|
109
|
+
|
|
110
|
+
switch (key) {
|
|
111
|
+
case "host":
|
|
112
|
+
cfg.host = val;
|
|
113
|
+
break;
|
|
114
|
+
case "port": {
|
|
115
|
+
const p = Number(val);
|
|
116
|
+
if (Number.isFinite(p)) cfg.port = p;
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case "user":
|
|
120
|
+
cfg.user = val;
|
|
121
|
+
break;
|
|
122
|
+
case "password":
|
|
123
|
+
cfg.password = val;
|
|
124
|
+
break;
|
|
125
|
+
case "dbname":
|
|
126
|
+
case "database":
|
|
127
|
+
cfg.database = val;
|
|
128
|
+
break;
|
|
129
|
+
// ignore everything else (sslmode, options, application_name, etc.)
|
|
130
|
+
default:
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return cfg;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function describePgConfig(cfg: PgClientConfig): string {
|
|
139
|
+
if (cfg.connectionString) return maskConnectionString(cfg.connectionString);
|
|
140
|
+
const user = cfg.user ? cfg.user : "<user>";
|
|
141
|
+
const host = cfg.host ? cfg.host : "<host>";
|
|
142
|
+
const port = cfg.port ? String(cfg.port) : "<port>";
|
|
143
|
+
const db = cfg.database ? cfg.database : "<db>";
|
|
144
|
+
// Don't include password
|
|
145
|
+
return `postgresql://${user}:*****@${host}:${port}/${db}`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function resolveAdminConnection(opts: {
|
|
149
|
+
conn?: string;
|
|
150
|
+
dbUrlFlag?: string;
|
|
151
|
+
host?: string;
|
|
152
|
+
port?: string | number;
|
|
153
|
+
username?: string;
|
|
154
|
+
dbname?: string;
|
|
155
|
+
adminPassword?: string;
|
|
156
|
+
envPassword?: string;
|
|
157
|
+
}): AdminConnection {
|
|
158
|
+
const conn = (opts.conn || "").trim();
|
|
159
|
+
const dbUrlFlag = (opts.dbUrlFlag || "").trim();
|
|
160
|
+
|
|
161
|
+
const hasPsqlParts =
|
|
162
|
+
!!(opts.host || opts.port || opts.username || opts.dbname || opts.adminPassword || opts.envPassword);
|
|
163
|
+
|
|
164
|
+
if (conn && dbUrlFlag) {
|
|
165
|
+
throw new Error("Provide either positional connection string or --db-url, not both");
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (conn || dbUrlFlag) {
|
|
169
|
+
const v = conn || dbUrlFlag;
|
|
170
|
+
if (isLikelyUri(v)) {
|
|
171
|
+
return { clientConfig: { connectionString: v }, display: maskConnectionString(v) };
|
|
172
|
+
}
|
|
173
|
+
// libpq conninfo (dbname=... host=...)
|
|
174
|
+
const cfg = parseLibpqConninfo(v);
|
|
175
|
+
if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
|
|
176
|
+
return { clientConfig: cfg, display: describePgConfig(cfg) };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (!hasPsqlParts) {
|
|
180
|
+
throw new Error(
|
|
181
|
+
"Connection is required. Provide a connection string/conninfo as a positional arg, or use --db-url, or use -h/-p/-U/-d."
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const cfg: PgClientConfig = {};
|
|
186
|
+
if (opts.host) cfg.host = opts.host;
|
|
187
|
+
if (opts.port !== undefined && opts.port !== "") cfg.port = Number(opts.port);
|
|
188
|
+
if (opts.username) cfg.user = opts.username;
|
|
189
|
+
if (opts.dbname) cfg.database = opts.dbname;
|
|
190
|
+
if (opts.adminPassword) cfg.password = opts.adminPassword;
|
|
191
|
+
if (opts.envPassword && !cfg.password) cfg.password = opts.envPassword;
|
|
192
|
+
return { clientConfig: cfg, display: describePgConfig(cfg) };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export async function promptHidden(prompt: string): Promise<string> {
|
|
196
|
+
const rl = readline.createInterface({
|
|
197
|
+
input: process.stdin,
|
|
198
|
+
output: process.stdout,
|
|
199
|
+
terminal: true,
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
// Mask input by overriding internal write method.
|
|
203
|
+
const anyRl = rl as any;
|
|
204
|
+
const out = process.stdout as NodeJS.WriteStream;
|
|
205
|
+
anyRl._writeToOutput = (str: string) => {
|
|
206
|
+
// Keep newlines and carriage returns; mask everything else.
|
|
207
|
+
if (str === "\n" || str === "\r\n") {
|
|
208
|
+
out.write(str);
|
|
209
|
+
} else {
|
|
210
|
+
out.write("*");
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
try {
|
|
215
|
+
const answer = await new Promise<string>((resolve) => rl.question(prompt, resolve));
|
|
216
|
+
// Ensure we end the masked line cleanly.
|
|
217
|
+
process.stdout.write("\n");
|
|
218
|
+
return answer;
|
|
219
|
+
} finally {
|
|
220
|
+
rl.close();
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export async function resolveMonitoringPassword(opts: {
|
|
225
|
+
passwordFlag?: string;
|
|
226
|
+
passwordEnv?: string;
|
|
227
|
+
prompt?: (prompt: string) => Promise<string>;
|
|
228
|
+
monitoringUser: string;
|
|
229
|
+
}): Promise<string> {
|
|
230
|
+
const fromFlag = (opts.passwordFlag || "").trim();
|
|
231
|
+
if (fromFlag) return fromFlag;
|
|
232
|
+
|
|
233
|
+
const fromEnv = (opts.passwordEnv || "").trim();
|
|
234
|
+
if (fromEnv) return fromEnv;
|
|
235
|
+
|
|
236
|
+
if (!process.stdin.isTTY) {
|
|
237
|
+
throw new Error(
|
|
238
|
+
"Monitoring user password is required in non-interactive mode (use --password or PGAI_MON_PASSWORD)"
|
|
239
|
+
);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const prompter = opts.prompt || promptHidden;
|
|
243
|
+
while (true) {
|
|
244
|
+
const pw = (await prompter(`Enter password for monitoring user ${opts.monitoringUser}: `)).trim();
|
|
245
|
+
if (pw) return pw;
|
|
246
|
+
// eslint-disable-next-line no-console
|
|
247
|
+
console.error("Password cannot be empty");
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function buildInitPlan(params: {
|
|
252
|
+
database: string;
|
|
253
|
+
monitoringUser?: string;
|
|
254
|
+
monitoringPassword: string;
|
|
255
|
+
includeOptionalPermissions: boolean;
|
|
256
|
+
roleExists?: boolean;
|
|
257
|
+
}): Promise<InitPlan> {
|
|
258
|
+
const monitoringUser = params.monitoringUser || "postgres_ai_mon";
|
|
259
|
+
const database = params.database;
|
|
260
|
+
|
|
261
|
+
const qRole = quoteIdent(monitoringUser);
|
|
262
|
+
const qDb = quoteIdent(database);
|
|
263
|
+
|
|
264
|
+
const steps: InitStep[] = [];
|
|
265
|
+
|
|
266
|
+
// Role creation/update is done in two alternative steps. Caller decides by checking role existence.
|
|
267
|
+
if (params.roleExists === false) {
|
|
268
|
+
steps.push({
|
|
269
|
+
name: "create monitoring user",
|
|
270
|
+
sql: `create user ${qRole} with password $1;`,
|
|
271
|
+
params: [params.monitoringPassword],
|
|
272
|
+
});
|
|
273
|
+
} else if (params.roleExists === true) {
|
|
274
|
+
steps.push({
|
|
275
|
+
name: "update monitoring user password",
|
|
276
|
+
sql: `alter user ${qRole} with password $1;`,
|
|
277
|
+
params: [params.monitoringPassword],
|
|
278
|
+
});
|
|
279
|
+
} else {
|
|
280
|
+
// Unknown: caller will rebuild after probing role existence.
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
steps.push(
|
|
284
|
+
{
|
|
285
|
+
name: "grant connect on database",
|
|
286
|
+
sql: `grant connect on database ${qDb} to ${qRole};`,
|
|
287
|
+
},
|
|
288
|
+
{
|
|
289
|
+
name: "grant pg_monitor",
|
|
290
|
+
sql: `grant pg_monitor to ${qRole};`,
|
|
291
|
+
},
|
|
292
|
+
{
|
|
293
|
+
name: "grant select on pg_index",
|
|
294
|
+
sql: `grant select on pg_catalog.pg_index to ${qRole};`,
|
|
295
|
+
},
|
|
296
|
+
{
|
|
297
|
+
name: "create or replace public.pg_statistic view",
|
|
298
|
+
sql: `create or replace view public.pg_statistic as
|
|
299
|
+
select
|
|
300
|
+
n.nspname as schemaname,
|
|
301
|
+
c.relname as tablename,
|
|
302
|
+
a.attname,
|
|
303
|
+
s.stanullfrac as null_frac,
|
|
304
|
+
s.stawidth as avg_width,
|
|
305
|
+
false as inherited
|
|
306
|
+
from pg_catalog.pg_statistic s
|
|
307
|
+
join pg_catalog.pg_class c on c.oid = s.starelid
|
|
308
|
+
join pg_catalog.pg_namespace n on n.oid = c.relnamespace
|
|
309
|
+
join pg_catalog.pg_attribute a on a.attrelid = s.starelid and a.attnum = s.staattnum
|
|
310
|
+
where a.attnum > 0 and not a.attisdropped;`,
|
|
311
|
+
},
|
|
312
|
+
{
|
|
313
|
+
name: "grant select on public.pg_statistic",
|
|
314
|
+
sql: `grant select on public.pg_statistic to ${qRole};`,
|
|
315
|
+
},
|
|
316
|
+
{
|
|
317
|
+
name: "ensure access to public schema (for hardened clusters)",
|
|
318
|
+
sql: `grant usage on schema public to ${qRole};`,
|
|
319
|
+
},
|
|
320
|
+
{
|
|
321
|
+
name: "set monitoring user search_path",
|
|
322
|
+
sql: `alter user ${qRole} set search_path = "$user", public, pg_catalog;`,
|
|
323
|
+
}
|
|
324
|
+
);
|
|
325
|
+
|
|
326
|
+
if (params.includeOptionalPermissions) {
|
|
327
|
+
steps.push(
|
|
328
|
+
{
|
|
329
|
+
name: "create rds_tools extension (optional)",
|
|
330
|
+
sql: "create extension if not exists rds_tools;",
|
|
331
|
+
optional: true,
|
|
332
|
+
},
|
|
333
|
+
{
|
|
334
|
+
name: "grant rds_tools.pg_ls_multixactdir() (optional)",
|
|
335
|
+
sql: `grant execute on function rds_tools.pg_ls_multixactdir() to ${qRole};`,
|
|
336
|
+
optional: true,
|
|
337
|
+
},
|
|
338
|
+
{
|
|
339
|
+
name: "grant pg_stat_file(text) (optional)",
|
|
340
|
+
sql: `grant execute on function pg_catalog.pg_stat_file(text) to ${qRole};`,
|
|
341
|
+
optional: true,
|
|
342
|
+
},
|
|
343
|
+
{
|
|
344
|
+
name: "grant pg_stat_file(text, boolean) (optional)",
|
|
345
|
+
sql: `grant execute on function pg_catalog.pg_stat_file(text, boolean) to ${qRole};`,
|
|
346
|
+
optional: true,
|
|
347
|
+
},
|
|
348
|
+
{
|
|
349
|
+
name: "grant pg_ls_dir(text) (optional)",
|
|
350
|
+
sql: `grant execute on function pg_catalog.pg_ls_dir(text) to ${qRole};`,
|
|
351
|
+
optional: true,
|
|
352
|
+
},
|
|
353
|
+
{
|
|
354
|
+
name: "grant pg_ls_dir(text, boolean, boolean) (optional)",
|
|
355
|
+
sql: `grant execute on function pg_catalog.pg_ls_dir(text, boolean, boolean) to ${qRole};`,
|
|
356
|
+
optional: true,
|
|
357
|
+
}
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
return { monitoringUser, database, steps };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
export async function applyInitPlan(params: {
|
|
365
|
+
client: PgClient;
|
|
366
|
+
plan: InitPlan;
|
|
367
|
+
verbose?: boolean;
|
|
368
|
+
}): Promise<{ applied: string[]; skippedOptional: string[] }> {
|
|
369
|
+
const applied: string[] = [];
|
|
370
|
+
const skippedOptional: string[] = [];
|
|
371
|
+
|
|
372
|
+
// Apply non-optional steps in a single transaction.
|
|
373
|
+
await params.client.query("begin;");
|
|
374
|
+
try {
|
|
375
|
+
for (const step of params.plan.steps.filter((s) => !s.optional)) {
|
|
376
|
+
try {
|
|
377
|
+
await params.client.query(step.sql, step.params as any);
|
|
378
|
+
applied.push(step.name);
|
|
379
|
+
} catch (e) {
|
|
380
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
381
|
+
throw new Error(`Failed at step "${step.name}": ${msg}`);
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
await params.client.query("commit;");
|
|
385
|
+
} catch (e) {
|
|
386
|
+
await params.client.query("rollback;");
|
|
387
|
+
throw e;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Apply optional steps outside of the transaction so a failure doesn't abort everything.
|
|
391
|
+
for (const step of params.plan.steps.filter((s) => s.optional)) {
|
|
392
|
+
try {
|
|
393
|
+
await params.client.query(step.sql, step.params as any);
|
|
394
|
+
applied.push(step.name);
|
|
395
|
+
} catch {
|
|
396
|
+
skippedOptional.push(step.name);
|
|
397
|
+
// best-effort: ignore
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
return { applied, skippedOptional };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
|