@deepsql/mcp 0.13.4 → 0.14.0

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,426 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * `deepsql index-recommendations` — surface DeepSQL's DBA-grade index
5
+ * advisor from the terminal. Mirrors the MCP tools (`get_index_recommendations`
6
+ * + `apply_index_recommendation`) so an on-call DBA gets the same workflow
7
+ * an AI coding agent does, without needing the IDE plumbing.
8
+ *
9
+ * Subcommands:
10
+ * deepsql index-recommendations top --connection <name> [--limit N] [--json]
11
+ * deepsql index-recommendations list --connection <name> [--json]
12
+ * deepsql index-recommendations show <id> [--json]
13
+ * deepsql index-recommendations refresh --connection <name> [--json]
14
+ * deepsql index-recommendations apply <id> [--mode dry-run|apply|apply-and-measure]
15
+ * [--confirm] [--concurrent|--no-concurrent]
16
+ * [--json]
17
+ * deepsql index-recommendations dismiss <id> [--json]
18
+ *
19
+ * Default output is a compact terminal-friendly table. `--json` passes the
20
+ * raw backend payload through, which is what callers from scripts / CI
21
+ * pipelines want.
22
+ *
23
+ * Apply is the one mutation. The contract matches the MCP tool: default
24
+ * mode is `dry-run` (HypoPG-based, no writes); the two write modes
25
+ * (`apply`, `apply-and-measure`) require `--confirm`. `--no-concurrent`
26
+ * opts out of CREATE INDEX CONCURRENTLY when the brief ACCESS EXCLUSIVE
27
+ * lock is acceptable (small dev tables, or after the DBA has drained the
28
+ * connection pool).
29
+ */
30
+
31
+ const { ApiError, request } = require("../api/client");
32
+ const { resolveSession } = require("./_session");
33
+ const { resolveConnectionId } = require("./_connections");
34
+
35
+ const SUBCOMMANDS = {
36
+ top: cmdTop,
37
+ list: cmdList,
38
+ show: cmdShow,
39
+ refresh: cmdRefresh,
40
+ apply: cmdApply,
41
+ dismiss: cmdDismiss,
42
+ };
43
+
44
+ async function run(opts, io = {}) {
45
+ const sub = opts.positional[0];
46
+ if (!sub) {
47
+ throw new Error(
48
+ "Usage: deepsql index-recommendations <top|list|show|refresh|apply|dismiss> …"
49
+ );
50
+ }
51
+ const handler = SUBCOMMANDS[sub];
52
+ if (!handler) {
53
+ throw new Error(`Unknown index-recommendations subcommand: ${sub}.`);
54
+ }
55
+ return wrap(handler)(
56
+ { ...opts, positional: opts.positional.slice(1) },
57
+ io
58
+ );
59
+ }
60
+
61
+ function wrap(handler) {
62
+ return async (opts, io) => {
63
+ try {
64
+ return await handler(opts, io);
65
+ } catch (err) {
66
+ if (err instanceof ApiError && err.status === 403) {
67
+ throw new Error(
68
+ "Access denied — index-recommendation operations require permissions on this connection."
69
+ );
70
+ }
71
+ if (err instanceof ApiError && err.status === 404) {
72
+ throw new Error(err.message || "Recommendation not found.");
73
+ }
74
+ throw err;
75
+ }
76
+ };
77
+ }
78
+
79
+ // ─── top ───────────────────────────────────────────────────────────────────
80
+
81
+ async function cmdTop(opts, { stdout = process.stdout } = {}) {
82
+ const session = resolveSession(opts);
83
+ const connectionId = await resolveConnectionId(session, opts.connection);
84
+ const limit = clampLimit(opts.limit, 5);
85
+ const result = await request(
86
+ session.baseUrl,
87
+ `/index-recommendations/${encodeURIComponent(connectionId)}/top`,
88
+ { token: session.token, query: { limit } }
89
+ );
90
+
91
+ if (opts.json) {
92
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
93
+ return;
94
+ }
95
+
96
+ const list = Array.isArray(result) ? result : [];
97
+ if (list.length === 0) {
98
+ stdout.write(
99
+ "No pending index recommendations. The 6-hour refresh scheduler may not have run yet, " +
100
+ "or the workload has none worth flagging. Try `deepsql index-recommendations refresh` " +
101
+ "to force a fresh accumulation cycle.\n"
102
+ );
103
+ return;
104
+ }
105
+
106
+ stdout.write(`Top ${list.length} pending index recommendation(s):\n\n`);
107
+ list.forEach((r, idx) => {
108
+ const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
109
+ const target =
110
+ r.kind === "DROP_INDEX"
111
+ ? `${r.tableName}.${r.indexName} (unused)`
112
+ : `${r.tableName}(${r.columnNames})`;
113
+
114
+ const meta = [
115
+ r.priority,
116
+ r.occurrenceCount != null ? `seen ${r.occurrenceCount}×` : null,
117
+ formatNet(r),
118
+ r.evidenceCount > 0 ? `${r.evidenceCount} ev` : null,
119
+ ]
120
+ .filter(Boolean)
121
+ .join(", ");
122
+
123
+ stdout.write(`${idx + 1}. [${action}] ${target} — ${meta}\n`);
124
+ stdout.write(` id: ${r.id}\n`);
125
+ if (r.hypopgReductionPct != null) {
126
+ stdout.write(
127
+ ` HypoPG cost: ${formatCost(r.hypopgBeforeCost)} → ${formatCost(r.hypopgAfterCost)} ` +
128
+ `(${signedPct(r.hypopgReductionPct)})\n`
129
+ );
130
+ }
131
+ if (r.reason) {
132
+ stdout.write(` ${truncate(r.reason, 200)}\n`);
133
+ }
134
+ if (Array.isArray(r.topEvidence) && r.topEvidence.length) {
135
+ const ev = r.topEvidence[0];
136
+ stdout.write(
137
+ ` top evidence: ${ev.calls} calls × ${formatMs(ev.meanExecTimeMs)}` +
138
+ ` mean = ${formatMs(ev.totalExecTimeMs)} total (${ev.role})\n`
139
+ );
140
+ }
141
+ stdout.write("\n");
142
+ });
143
+ }
144
+
145
+ // ─── list / show ───────────────────────────────────────────────────────────
146
+
147
+ async function cmdList(opts, { stdout = process.stdout } = {}) {
148
+ const session = resolveSession(opts);
149
+ const connectionId = await resolveConnectionId(session, opts.connection);
150
+ const result = await request(
151
+ session.baseUrl,
152
+ `/index-recommendations/pending/${encodeURIComponent(connectionId)}`,
153
+ { token: session.token }
154
+ );
155
+ if (opts.json) {
156
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
157
+ return;
158
+ }
159
+ const list = Array.isArray(result) ? result : [];
160
+ if (list.length === 0) {
161
+ stdout.write("No pending index recommendations.\n");
162
+ return;
163
+ }
164
+ stdout.write(`${list.length} pending recommendation(s):\n\n`);
165
+ list.forEach((r, idx) => {
166
+ const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
167
+ stdout.write(
168
+ `${idx + 1}. [${action}] ${r.tableName}(${r.columnNames || r.indexName}) — ${r.priority}, occ=${r.occurrenceCount}, id=${r.id}\n`
169
+ );
170
+ });
171
+ }
172
+
173
+ async function cmdShow(opts, { stdout = process.stdout } = {}) {
174
+ const id = opts.positional[0];
175
+ if (!id) throw new Error("Usage: deepsql index-recommendations show <id>");
176
+ const session = resolveSession(opts);
177
+ // No direct GET by id endpoint — use the connection's top with a wide
178
+ // limit and filter client-side. Cheap enough for inspection use.
179
+ const connectionId = opts.connection
180
+ ? await resolveConnectionId(session, opts.connection)
181
+ : null;
182
+ if (!connectionId) {
183
+ throw new Error(
184
+ "`show` needs --connection <name> to look up the recommendation (or pin one with `deepsql connections use`)."
185
+ );
186
+ }
187
+ const list = await request(
188
+ session.baseUrl,
189
+ `/index-recommendations/${encodeURIComponent(connectionId)}/top`,
190
+ { token: session.token, query: { limit: 50 } }
191
+ );
192
+ const found = (list || []).find((r) => r.id === id);
193
+ if (!found) {
194
+ throw new Error(`Recommendation ${id} not in the top-50 for this connection.`);
195
+ }
196
+ if (opts.json) {
197
+ stdout.write(`${JSON.stringify(found, null, 2)}\n`);
198
+ return;
199
+ }
200
+ renderRecommendationDetail(stdout, found);
201
+ }
202
+
203
+ // ─── refresh ───────────────────────────────────────────────────────────────
204
+
205
+ async function cmdRefresh(opts, { stdout = process.stdout, stderr = process.stderr } = {}) {
206
+ const session = resolveSession(opts);
207
+ const connectionId = await resolveConnectionId(session, opts.connection);
208
+ stderr.write(`Refreshing index recommendations on ${opts.connection || connectionId}…\n`);
209
+ const result = await request(
210
+ session.baseUrl,
211
+ `/index-recommendations/generate/${encodeURIComponent(connectionId)}`,
212
+ { method: "POST", token: session.token, timeoutMs: 600000 }
213
+ );
214
+ if (opts.json) {
215
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
216
+ return;
217
+ }
218
+ if (result && result.success) {
219
+ stdout.write(
220
+ `Refresh complete: ${result.count} candidate(s) merged. ` +
221
+ `Use \`deepsql index-recommendations top\` to see the top-N.\n`
222
+ );
223
+ } else {
224
+ stdout.write(`Refresh response: ${JSON.stringify(result)}\n`);
225
+ }
226
+ }
227
+
228
+ // ─── apply ─────────────────────────────────────────────────────────────────
229
+
230
+ async function cmdApply(opts, { stdout = process.stdout, stderr = process.stderr } = {}) {
231
+ const id = opts.positional[0];
232
+ if (!id) {
233
+ throw new Error(
234
+ "Usage: deepsql index-recommendations apply <id> [--mode dry-run|apply|apply-and-measure] [--confirm] [--no-concurrent]"
235
+ );
236
+ }
237
+
238
+ const mode = normalizeMode(opts.mode);
239
+ const isWriteMode = mode === "APPLY" || mode === "APPLY_AND_MEASURE";
240
+ if (isWriteMode && !opts.confirm) {
241
+ throw new Error(
242
+ `Mode ${mode} mutates the target database. Re-run with --confirm to proceed.`
243
+ );
244
+ }
245
+ // --concurrent defaults to true; --no-concurrent flips it off (parser
246
+ // surfaces noConcurrent boolean).
247
+ const concurrent = !opts.noConcurrent;
248
+
249
+ const session = resolveSession(opts);
250
+ if (isWriteMode) {
251
+ stderr.write(`Running ${mode} on recommendation ${id}…\n`);
252
+ }
253
+
254
+ const result = await request(
255
+ session.baseUrl,
256
+ `/index-recommendations/${encodeURIComponent(id)}/apply`,
257
+ {
258
+ method: "POST",
259
+ token: session.token,
260
+ timeoutMs: 600000,
261
+ query: { mode, confirm: opts.confirm === true, concurrent },
262
+ }
263
+ );
264
+
265
+ if (opts.json) {
266
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
267
+ return;
268
+ }
269
+ renderApplyResult(stdout, result);
270
+ }
271
+
272
+ // ─── dismiss ───────────────────────────────────────────────────────────────
273
+
274
+ async function cmdDismiss(opts, { stdout = process.stdout } = {}) {
275
+ const id = opts.positional[0];
276
+ if (!id) throw new Error("Usage: deepsql index-recommendations dismiss <id>");
277
+ const session = resolveSession(opts);
278
+ const result = await request(
279
+ session.baseUrl,
280
+ `/index-recommendations/${encodeURIComponent(id)}/dismiss`,
281
+ { method: "PUT", token: session.token }
282
+ );
283
+ if (opts.json) {
284
+ stdout.write(`${JSON.stringify(result, null, 2)}\n`);
285
+ return;
286
+ }
287
+ stdout.write(`Dismissed recommendation ${id}.\n`);
288
+ }
289
+
290
+ // ─── formatting helpers ────────────────────────────────────────────────────
291
+
292
+ function renderRecommendationDetail(stdout, r) {
293
+ const action = r.kind === "DROP_INDEX" ? "DROP" : "CREATE";
294
+ stdout.write(`[${action}] ${r.tableName}(${r.columnNames || r.indexName})\n`);
295
+ stdout.write(` id : ${r.id}\n`);
296
+ stdout.write(` priority : ${r.priority}\n`);
297
+ stdout.write(` status : ${r.status || "PENDING"}\n`);
298
+ stdout.write(` occurrenceCnt : ${r.occurrenceCount}\n`);
299
+ stdout.write(` workloadScore : ${formatMs(r.workloadScoreMs)}\n`);
300
+ stdout.write(` writeCost : ${formatMs(r.writeCostScore)}\n`);
301
+ stdout.write(` netBenefit : ${formatMs(r.netBenefitMs)}\n`);
302
+ if (r.hypopgReductionPct != null) {
303
+ stdout.write(
304
+ ` HypoPG : ${formatCost(r.hypopgBeforeCost)} → ${formatCost(r.hypopgAfterCost)} ` +
305
+ `(${signedPct(r.hypopgReductionPct)})\n`
306
+ );
307
+ }
308
+ stdout.write(` DDL : ${r.createStatement}\n`);
309
+ if (r.reason) stdout.write(` reason : ${r.reason}\n`);
310
+ if (Array.isArray(r.topEvidence) && r.topEvidence.length) {
311
+ stdout.write(` contributing queries (${r.topEvidence.length}):\n`);
312
+ for (const ev of r.topEvidence) {
313
+ stdout.write(
314
+ ` - fp=${(ev.fingerprint || "?").slice(0, 12)} calls=${ev.calls} mean=${formatMs(ev.meanExecTimeMs)} total=${formatMs(ev.totalExecTimeMs)} role=${ev.role}\n`
315
+ );
316
+ if (ev.exampleSql) {
317
+ stdout.write(` ${truncate(ev.exampleSql, 200)}\n`);
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ function renderApplyResult(stdout, r) {
324
+ if (!r || typeof r !== "object") {
325
+ stdout.write("Apply returned no body.\n");
326
+ return;
327
+ }
328
+ const status = r.status || "?";
329
+ if (status === "BLOCKED_NEEDS_CONFIRMATION") {
330
+ stdout.write(`[${r.mode}] blocked — pass --confirm to mutate the database.\n`);
331
+ return;
332
+ }
333
+ if (status === "NOT_FOUND") {
334
+ stdout.write(`[${r.mode}] recommendation not found: ${r.recommendationId}\n`);
335
+ return;
336
+ }
337
+ if (status === "NO_USABLE_SAMPLES") {
338
+ stdout.write(
339
+ `[${r.mode}] no literal-bearing contributing queries available; cannot measure.\n`
340
+ );
341
+ return;
342
+ }
343
+ if (status === "FAILED") {
344
+ stdout.write(`[${r.mode}] failed: ${r.message || "(no message)"}\n`);
345
+ return;
346
+ }
347
+
348
+ stdout.write(`[${r.mode}] ${status}\n`);
349
+ stdout.write(` DDL: ${r.executedDdl}\n`);
350
+ if (r.beforeCost != null && r.afterCost != null) {
351
+ stdout.write(
352
+ ` planner cost: ${formatCost(r.beforeCost)} → ${formatCost(r.afterCost)} ` +
353
+ `(${signedPct(r.costReductionPct)})\n`
354
+ );
355
+ }
356
+ if (r.beforeWallTimeMs != null && r.afterWallTimeMs != null) {
357
+ stdout.write(
358
+ ` wall time: ${formatMs(r.beforeWallTimeMs)} → ${formatMs(r.afterWallTimeMs)} ` +
359
+ `(${signedPct(r.wallTimeImprovementPct)})\n`
360
+ );
361
+ }
362
+ if (Array.isArray(r.samples) && r.samples.length) {
363
+ stdout.write(` ${r.samples.length} contributing query sample(s):\n`);
364
+ for (const s of r.samples.slice(0, 5)) {
365
+ stdout.write(
366
+ ` fp=${(s.fingerprint || "?").slice(0, 12)} cost ${formatCost(s.beforeCost)} → ${formatCost(s.afterCost)}` +
367
+ (s.error ? ` (error: ${s.error})` : "") +
368
+ "\n"
369
+ );
370
+ }
371
+ }
372
+ if (r.message) stdout.write(` ${r.message}\n`);
373
+ }
374
+
375
+ function clampLimit(raw, fallback) {
376
+ const n = Number.parseInt(raw, 10);
377
+ if (!Number.isFinite(n)) return fallback;
378
+ return Math.min(50, Math.max(1, n));
379
+ }
380
+
381
+ function normalizeMode(raw) {
382
+ if (!raw) return "DRY_RUN";
383
+ // Accept dash-form (CLI convention) and underscore-form (API enum).
384
+ const m = String(raw).toUpperCase().replace(/-/g, "_");
385
+ if (!["DRY_RUN", "APPLY", "APPLY_AND_MEASURE"].includes(m)) {
386
+ throw new Error(`Unknown mode: ${raw}. Expected dry-run, apply, or apply-and-measure.`);
387
+ }
388
+ return m;
389
+ }
390
+
391
+ function formatMs(ms) {
392
+ if (ms == null || !Number.isFinite(Number(ms))) return "—";
393
+ const n = Number(ms);
394
+ if (n <= 0) return "0ms";
395
+ if (n >= 86_400_000) return `${(n / 86_400_000).toFixed(1)}d`;
396
+ if (n >= 3_600_000) return `${(n / 3_600_000).toFixed(1)}h`;
397
+ if (n >= 60_000) return `${(n / 60_000).toFixed(1)}m`;
398
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}s`;
399
+ return `${n.toFixed(n >= 10 ? 0 : 1)}ms`;
400
+ }
401
+
402
+ function formatCost(c) {
403
+ if (c == null || !Number.isFinite(Number(c))) return "—";
404
+ return Number(c).toFixed(0);
405
+ }
406
+
407
+ function signedPct(pct) {
408
+ if (pct == null || !Number.isFinite(Number(pct))) return "—";
409
+ const sign = pct >= 0 ? "−" : "+";
410
+ return `${sign}${Math.abs(pct).toFixed(1)}%`;
411
+ }
412
+
413
+ function formatNet(r) {
414
+ if (r.netBenefitMs != null && r.netBenefitMs > 0) {
415
+ return `net=${formatMs(r.netBenefitMs)} saved`;
416
+ }
417
+ if (r.estimatedImpact != null) return `impact ${r.estimatedImpact}`;
418
+ return null;
419
+ }
420
+
421
+ function truncate(s, max) {
422
+ if (!s) return s;
423
+ return s.length <= max ? s : `${s.slice(0, max)}…`;
424
+ }
425
+
426
+ module.exports = { run };