@neon/tools 2.11.0 → 2.13.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.
Files changed (97) hide show
  1. package/README.md +150 -7
  2. package/dist/descriptions.gen.d.ts +10 -0
  3. package/dist/descriptions.gen.d.ts.map +1 -0
  4. package/dist/descriptions.gen.js +150 -0
  5. package/dist/generated/zod.gen.d.ts +33 -2
  6. package/dist/generated/zod.gen.d.ts.map +1 -1
  7. package/dist/generated/zod.gen.js +29 -11
  8. package/dist/index.d.ts +4 -3
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +14 -11
  11. package/dist/lib/custom/auth-config.d.ts +164 -0
  12. package/dist/lib/custom/auth-config.d.ts.map +1 -0
  13. package/dist/lib/custom/auth-config.js +177 -0
  14. package/dist/lib/custom/docs.d.ts +58 -0
  15. package/dist/lib/custom/docs.d.ts.map +1 -0
  16. package/dist/lib/custom/docs.js +143 -0
  17. package/dist/lib/custom/feedback.d.ts +15 -0
  18. package/dist/lib/custom/feedback.d.ts.map +1 -0
  19. package/dist/lib/custom/feedback.js +55 -0
  20. package/dist/lib/custom/fetch.d.ts +402 -0
  21. package/dist/lib/custom/fetch.d.ts.map +1 -0
  22. package/dist/lib/custom/fetch.js +198 -0
  23. package/dist/lib/custom/organizations.d.ts +23 -0
  24. package/dist/lib/custom/organizations.d.ts.map +1 -0
  25. package/dist/lib/custom/organizations.js +32 -0
  26. package/dist/lib/custom/resources.d.ts +22 -0
  27. package/dist/lib/custom/resources.d.ts.map +1 -0
  28. package/dist/lib/custom/resources.js +113 -0
  29. package/dist/lib/custom/sql/connection.d.ts +46 -0
  30. package/dist/lib/custom/sql/connection.d.ts.map +1 -0
  31. package/dist/lib/custom/sql/connection.js +78 -0
  32. package/dist/lib/custom/sql/describe-branch.d.ts +84 -0
  33. package/dist/lib/custom/sql/describe-branch.d.ts.map +1 -0
  34. package/dist/lib/custom/sql/describe-branch.js +155 -0
  35. package/dist/lib/custom/sql/inspect/inspect.d.ts +75 -0
  36. package/dist/lib/custom/sql/inspect/inspect.d.ts.map +1 -0
  37. package/dist/lib/custom/sql/inspect/inspect.js +135 -0
  38. package/dist/lib/custom/sql/inspect/queries.d.ts +63 -0
  39. package/dist/lib/custom/sql/inspect/queries.d.ts.map +1 -0
  40. package/dist/lib/custom/sql/inspect/queries.js +528 -0
  41. package/dist/lib/custom/sql/inspect/report.d.ts +31 -0
  42. package/dist/lib/custom/sql/inspect/report.d.ts.map +1 -0
  43. package/dist/lib/custom/sql/inspect/report.js +43 -0
  44. package/dist/lib/custom/sql/inspect/targets.d.ts +27 -0
  45. package/dist/lib/custom/sql/inspect/targets.d.ts.map +1 -0
  46. package/dist/lib/custom/sql/inspect/targets.js +33 -0
  47. package/dist/lib/custom/sql/migrations.d.ts +69 -0
  48. package/dist/lib/custom/sql/migrations.d.ts.map +1 -0
  49. package/dist/lib/custom/sql/migrations.js +144 -0
  50. package/dist/lib/custom/sql/plan.d.ts +27 -0
  51. package/dist/lib/custom/sql/plan.d.ts.map +1 -0
  52. package/dist/lib/custom/sql/plan.js +53 -0
  53. package/dist/lib/custom/sql/query-tuning.d.ts +107 -0
  54. package/dist/lib/custom/sql/query-tuning.d.ts.map +1 -0
  55. package/dist/lib/custom/sql/query-tuning.js +129 -0
  56. package/dist/lib/custom/sql/rows.d.ts +11 -0
  57. package/dist/lib/custom/sql/rows.d.ts.map +1 -0
  58. package/dist/lib/custom/sql/rows.js +19 -0
  59. package/dist/lib/custom/sql/run.d.ts +81 -0
  60. package/dist/lib/custom/sql/run.d.ts.map +1 -0
  61. package/dist/lib/custom/sql/run.js +90 -0
  62. package/dist/lib/custom/sql/schema.d.ts +84 -0
  63. package/dist/lib/custom/sql/schema.d.ts.map +1 -0
  64. package/dist/lib/custom/sql/schema.js +201 -0
  65. package/dist/lib/custom/sql/slow-queries.d.ts +43 -0
  66. package/dist/lib/custom/sql/slow-queries.d.ts.map +1 -0
  67. package/dist/lib/custom/sql/slow-queries.js +87 -0
  68. package/dist/lib/customize.d.ts +9 -2
  69. package/dist/lib/customize.d.ts.map +1 -1
  70. package/dist/lib/customize.js +21 -7
  71. package/dist/lib/ergonomic/bind.d.ts +11 -1
  72. package/dist/lib/ergonomic/bind.d.ts.map +1 -1
  73. package/dist/lib/ergonomic/bind.js +13 -3
  74. package/dist/lib/ergonomic/catalog.d.ts +870 -38
  75. package/dist/lib/ergonomic/catalog.d.ts.map +1 -1
  76. package/dist/lib/ergonomic/catalog.js +44 -8
  77. package/dist/lib/ergonomic/composed.d.ts +4 -4
  78. package/dist/lib/ergonomic/composed.d.ts.map +1 -1
  79. package/dist/lib/ergonomic/composed.js +47 -45
  80. package/dist/lib/ergonomic/ids.d.ts +3 -1
  81. package/dist/lib/ergonomic/ids.d.ts.map +1 -1
  82. package/dist/lib/ergonomic/ids.js +42 -2
  83. package/dist/lib/ergonomic/index.d.ts +1 -1
  84. package/dist/lib/ergonomic/index.d.ts.map +1 -1
  85. package/dist/lib/ergonomic/index.js +2 -2
  86. package/dist/lib/operation.d.ts +11 -0
  87. package/dist/lib/operation.d.ts.map +1 -1
  88. package/dist/lib/references.d.ts +10 -0
  89. package/dist/lib/references.d.ts.map +1 -0
  90. package/dist/lib/references.js +28 -0
  91. package/dist/operations.gen.d.ts +22 -2
  92. package/dist/operations.gen.d.ts.map +1 -1
  93. package/dist/operations.gen.js +335 -300
  94. package/dist/schemas.d.ts +1 -1
  95. package/dist/schemas.d.ts.map +1 -1
  96. package/dist/schemas.js +1 -1
  97. package/package.json +9 -6
@@ -0,0 +1,69 @@
1
+ import { type Branch, type NeonClient } from "@neon/sdk";
2
+ import * as z from "zod";
3
+ import { type ToolClientOptions } from "../../ergonomic/bind.js";
4
+ /** Splits on every `;`, including one inside a string literal or function body. */
5
+ export declare const splitSqlStatements: (sql: string) => string[];
6
+ /**
7
+ * Creates a branch with a 0.25 CU read-write compute and runs `use` on it once
8
+ * it is ready. If waiting for readiness or `use` fails, the branch is deleted and
9
+ * the original error is rethrown, so the id is recorded before any wait starts.
10
+ */
11
+ export declare const withTemporaryBranch: <T>(neonClient: NeonClient<true>, projectId: string, name: string | undefined, signal: AbortSignal | undefined, use: (branch: Branch) => Promise<T>) => Promise<T>;
12
+ export declare const prepareMigrationInputSchema: z.ZodObject<{
13
+ migration_sql: z.ZodString;
14
+ project_id: z.ZodString;
15
+ database_name: z.ZodOptional<z.ZodString>;
16
+ }, z.core.$strict>;
17
+ export declare const completeMigrationInputSchema: z.ZodObject<{
18
+ migration_id: z.ZodString;
19
+ migration_sql: z.ZodString;
20
+ database_name: z.ZodString;
21
+ project_id: z.ZodString;
22
+ temporary_branch_id: z.ZodString;
23
+ parent_branch_id: z.ZodString;
24
+ apply_changes: z.ZodDefault<z.ZodBoolean>;
25
+ }, z.core.$strict>;
26
+ export declare const prepareMigrationTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
27
+ migration_sql: z.ZodString;
28
+ project_id: z.ZodString;
29
+ database_name: z.ZodOptional<z.ZodString>;
30
+ }, z.core.$strict>, "prepare_migrations", {
31
+ complete: {
32
+ migration_id: `${string}-${string}-${string}-${string}-${string}`;
33
+ migration_sql: string;
34
+ database_name: string;
35
+ project_id: string;
36
+ temporary_branch_id: string;
37
+ parent_branch_id: string;
38
+ };
39
+ temporary_branch: {
40
+ id: string;
41
+ name: string;
42
+ parent_id: string;
43
+ };
44
+ migration_result: {
45
+ [x: string]: unknown;
46
+ }[][];
47
+ }>;
48
+ export declare const completeMigrationTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
49
+ migration_id: z.ZodString;
50
+ migration_sql: z.ZodString;
51
+ database_name: z.ZodString;
52
+ project_id: z.ZodString;
53
+ temporary_branch_id: z.ZodString;
54
+ parent_branch_id: z.ZodString;
55
+ apply_changes: z.ZodDefault<z.ZodBoolean>;
56
+ }, z.core.$strict>, "complete_migrations", {
57
+ migrationResult?: {
58
+ [x: string]: unknown;
59
+ }[][] | null | undefined;
60
+ deletedBranchId: string;
61
+ applied: boolean;
62
+ } | {
63
+ migrationResult?: {
64
+ [x: string]: unknown;
65
+ }[][] | null | undefined;
66
+ cleanupError: string;
67
+ applied: boolean;
68
+ }>;
69
+ //# sourceMappingURL=migrations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../../../../src/lib/custom/sql/migrations.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,MAAM,EAAE,KAAK,UAAU,EAAmB,MAAM,WAAW,CAAC;AAE1E,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAGN,KAAK,iBAAiB,EACtB,MAAM,yBAAyB,CAAC;AAUjC,mFAAmF;AACnF,eAAO,MAAM,kBAAkB,GAAI,KAAK,MAAM,KAAG,MAAM,EACxB,CAAC;AA8BhC;;;;GAIG;AACH,eAAO,MAAM,mBAAmB,GAAU,CAAC,EAC1C,YAAY,UAAU,CAAC,IAAI,CAAC,EAC5B,WAAW,MAAM,EACjB,MAAM,MAAM,GAAG,SAAS,EACxB,QAAQ,WAAW,GAAG,SAAS,EAC/B,KAAK,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,KACjC,OAAO,CAAC,CAAC,CAgCX,CAAC;AAMF,eAAO,MAAM,2BAA2B;;;;kBAQtC,CAAC;AAEH,eAAO,MAAM,4BAA4B;;;;;;;;kBAuBvC,CAAC;AAEH,eAAO,MAAM,oBAAoB,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;;;;;;;EAyE7D,CAAC;AAEH,eAAO,MAAM,qBAAqB,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;;;;;;EAoD9D,CAAC"}
@@ -0,0 +1,144 @@
1
+ import { bindTool, publishedId } from "../../ergonomic/bind.js";
2
+ import { DATABASE_NAME_DESCRIPTION, SQL_METADATA, defaultDatabase, projectIdField, refuseInReadOnly } from "./connection.js";
3
+ import { runTransaction, sqlWriteAnnotations } from "./run.js";
4
+ import { NeonClientError } from "@neon/sdk";
5
+ import * as z from "zod";
6
+ import { createProjectBranch } from "@neon/sdk/raw";
7
+ import { randomUUID } from "node:crypto";
8
+ // src/lib/custom/sql/migrations.ts
9
+ /** Splits on every `;`, including one inside a string literal or function body. */
10
+ const splitSqlStatements = (sql) => sql.split(";").filter(Boolean);
11
+ const CLEANUP_WAIT_MS = 6e4;
12
+ const discardTemporaryBranch = async (neonClient, projectId, branchId, operations) => {
13
+ try {
14
+ await neonClient.operations.waitFor({ operations }, { timeoutMs: CLEANUP_WAIT_MS });
15
+ } catch {}
16
+ try {
17
+ await neonClient.branches.delete({
18
+ projectId,
19
+ branchId
20
+ }, { waitForReadiness: false });
21
+ } catch {}
22
+ };
23
+ /**
24
+ * Creates a branch with a 0.25 CU read-write compute and runs `use` on it once
25
+ * it is ready. If waiting for readiness or `use` fails, the branch is deleted and
26
+ * the original error is rethrown, so the id is recorded before any wait starts.
27
+ */
28
+ const withTemporaryBranch = async (neonClient, projectId, name, signal, use) => {
29
+ const created = await createProjectBranch({
30
+ client: neonClient.client,
31
+ path: { project_id: projectId },
32
+ body: {
33
+ ...name === void 0 ? {} : { branch: { name } },
34
+ endpoints: [{
35
+ type: "read_write",
36
+ autoscaling_limit_min_cu: .25,
37
+ autoscaling_limit_max_cu: .25
38
+ }]
39
+ },
40
+ throwOnError: true,
41
+ signal
42
+ });
43
+ try {
44
+ await neonClient.operations.waitFor({ operations: created.operations }, { signal });
45
+ return await use(created.branch);
46
+ } catch (error) {
47
+ await discardTemporaryBranch(neonClient, projectId, created.branch.id, created.operations);
48
+ throw error;
49
+ }
50
+ };
51
+ const migrationBranchName = () => `mcp-migration-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, 19)}`;
52
+ const prepareMigrationInputSchema = z.strictObject({
53
+ migration_sql: z.string().describe("The migration SQL. It is split on every semicolon, including one inside a string or function body."),
54
+ project_id: projectIdField,
55
+ database_name: z.string().optional().describe(DATABASE_NAME_DESCRIPTION)
56
+ });
57
+ const completeMigrationInputSchema = z.strictObject({
58
+ migration_id: z.string().describe("The migration_id from {{migrations.prepare}}."),
59
+ migration_sql: z.string().describe("The exact migration_sql from {{migrations.prepare}}."),
60
+ database_name: z.string().describe("The exact database_name from {{migrations.prepare}}."),
61
+ project_id: z.string().describe("The exact project_id from {{migrations.prepare}}."),
62
+ temporary_branch_id: z.string().describe("The temporary branch to delete."),
63
+ parent_branch_id: z.string().describe("The branch the migration is applied to."),
64
+ apply_changes: z.boolean().default(true).describe("Apply the migration to the parent branch. false only deletes the temporary branch.")
65
+ });
66
+ const prepareMigrationTool = (options) => bindTool(options, {
67
+ operationId: "migrations.prepare",
68
+ id: publishedId("migrations.prepare"),
69
+ title: "Prepare Database Migration",
70
+ description: "Applies a schema change on a new temporary branch and returns a migration_id. Test it there with {{sql.run}}, ask the user, then always call {{migrations.complete}} with the response's complete object so the branch is deleted.",
71
+ inputSchema: prepareMigrationInputSchema,
72
+ annotations: {
73
+ readOnlyHint: false,
74
+ destructiveHint: false,
75
+ idempotentHint: false,
76
+ openWorldHint: false
77
+ },
78
+ requiresApproval: true,
79
+ metadata: SQL_METADATA
80
+ }, async (neonClient, input, signal, context) => {
81
+ refuseInReadOnly(context);
82
+ const projectId = input.project_id;
83
+ return withTemporaryBranch(neonClient, projectId, migrationBranchName(), signal, async (branch) => {
84
+ const parentBranchId = branch.parent_id;
85
+ if (parentBranchId === void 0) throw new NeonClientError(`Temporary branch ${branch.id} has no parent branch`);
86
+ const databaseName = input.database_name ?? (await defaultDatabase(neonClient, {
87
+ projectId,
88
+ branchId: branch.id
89
+ }, signal)).name;
90
+ const migrationResult = await runTransaction(neonClient, {
91
+ project_id: projectId,
92
+ branch_id: branch.id,
93
+ database_name: databaseName
94
+ }, splitSqlStatements(input.migration_sql), context, signal);
95
+ return {
96
+ complete: {
97
+ migration_id: randomUUID(),
98
+ migration_sql: input.migration_sql,
99
+ database_name: databaseName,
100
+ project_id: projectId,
101
+ temporary_branch_id: branch.id,
102
+ parent_branch_id: parentBranchId
103
+ },
104
+ temporary_branch: {
105
+ id: branch.id,
106
+ name: branch.name,
107
+ parent_id: parentBranchId
108
+ },
109
+ migration_result: migrationResult
110
+ };
111
+ });
112
+ });
113
+ const completeMigrationTool = (options) => bindTool(options, {
114
+ operationId: "migrations.complete",
115
+ id: publishedId("migrations.complete"),
116
+ title: "Complete Database Migration",
117
+ description: "Applies or discards a prepared migration and deletes the temporary branch. NEVER run autonomously; always ask the user first. Pass the complete object from {{migrations.prepare}}; apply_changes false discards.",
118
+ inputSchema: completeMigrationInputSchema,
119
+ annotations: sqlWriteAnnotations,
120
+ requiresApproval: true,
121
+ metadata: SQL_METADATA
122
+ }, async (neonClient, input, signal, context) => {
123
+ refuseInReadOnly(context);
124
+ const migrationResult = input.apply_changes ? await runTransaction(neonClient, {
125
+ project_id: input.project_id,
126
+ branch_id: input.parent_branch_id,
127
+ database_name: input.database_name
128
+ }, splitSqlStatements(input.migration_sql), context, signal) : void 0;
129
+ let cleanupError;
130
+ try {
131
+ await neonClient.branches.delete({
132
+ projectId: input.project_id,
133
+ branchId: input.temporary_branch_id
134
+ }, { signal });
135
+ } catch (error) {
136
+ cleanupError = error instanceof Error ? error.message : String(error);
137
+ }
138
+ return {
139
+ applied: input.apply_changes,
140
+ ...cleanupError === void 0 ? { deletedBranchId: input.temporary_branch_id } : { cleanupError },
141
+ ...migrationResult === void 0 ? {} : { migrationResult }
142
+ };
143
+ });
144
+ export { completeMigrationInputSchema, completeMigrationTool, prepareMigrationInputSchema, prepareMigrationTool, splitSqlStatements, withTemporaryBranch };
@@ -0,0 +1,27 @@
1
+ interface BufferMetrics {
2
+ hit: number;
3
+ read: number;
4
+ written: number;
5
+ dirtied: number;
6
+ }
7
+ export interface QueryMetrics {
8
+ executionTime: number;
9
+ planningTime: number;
10
+ totalCost: number;
11
+ actualRows: number;
12
+ bufferUsage: {
13
+ shared: BufferMetrics;
14
+ local: BufferMetrics;
15
+ };
16
+ }
17
+ /** Every `schema.relation` an `EXPLAIN (FORMAT JSON)` result scans. */
18
+ export declare const extractTableNamesFromPlan: (plan: unknown) => string[];
19
+ /**
20
+ * Query-level totals from the rows `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`
21
+ * returns: one row whose `QUERY PLAN` column holds the plan document. They come
22
+ * from the root plan node, because a parent node's cost, rows, and buffer
23
+ * counters already include its children.
24
+ */
25
+ export declare const extractExecutionMetrics: (rows: unknown) => QueryMetrics;
26
+ export {};
27
+ //# sourceMappingURL=plan.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../../src/lib/custom/sql/plan.ts"],"names":[],"mappings":"AAAA,UAAU,aAAa;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC5B,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE;QACZ,MAAM,EAAE,aAAa,CAAC;QACtB,KAAK,EAAE,aAAa,CAAC;KACrB,CAAC;CACF;AAUD,uEAAuE;AACvE,eAAO,MAAM,yBAAyB,GAAI,MAAM,OAAO,KAAG,MAAM,EAiB/D,CAAC;AAYF;;;;;GAKG;AACH,eAAO,MAAM,uBAAuB,GAAI,MAAM,OAAO,KAAG,YAkBvD,CAAC"}
@@ -0,0 +1,53 @@
1
+ // src/lib/custom/sql/plan.ts
2
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const numberAt = (node, key) => {
4
+ const value = node[key];
5
+ return typeof value === "number" ? value : 0;
6
+ };
7
+ /** Every `schema.relation` an `EXPLAIN (FORMAT JSON)` result scans. */
8
+ const extractTableNamesFromPlan = (plan) => {
9
+ const tableNames = /* @__PURE__ */ new Set();
10
+ const visit = (node) => {
11
+ if (Array.isArray(node)) {
12
+ for (const item of node) visit(item);
13
+ return;
14
+ }
15
+ if (!isRecord(node)) return;
16
+ const relation = node["Relation Name"];
17
+ const schema = node.Schema;
18
+ if (typeof relation === "string" && typeof schema === "string") tableNames.add(`${schema}.${relation}`);
19
+ for (const value of Object.values(node)) visit(value);
20
+ };
21
+ visit(plan);
22
+ return [...tableNames];
23
+ };
24
+ const buffers = (node, prefix) => ({
25
+ hit: numberAt(node, `${prefix} Hit Blocks`),
26
+ read: numberAt(node, `${prefix} Read Blocks`),
27
+ written: numberAt(node, `${prefix} Written Blocks`),
28
+ dirtied: numberAt(node, `${prefix} Dirtied Blocks`)
29
+ });
30
+ /**
31
+ * Query-level totals from the rows `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`
32
+ * returns: one row whose `QUERY PLAN` column holds the plan document. They come
33
+ * from the root plan node, because a parent node's cost, rows, and buffer
34
+ * counters already include its children.
35
+ */
36
+ const extractExecutionMetrics = (rows) => {
37
+ const firstRow = Array.isArray(rows) ? rows[0] : void 0;
38
+ const documents = isRecord(firstRow) ? firstRow["QUERY PLAN"] : void 0;
39
+ const document = Array.isArray(documents) ? documents[0] : void 0;
40
+ const root = isRecord(document) ? document.Plan : void 0;
41
+ if (!isRecord(document) || !isRecord(root)) throw new Error("EXPLAIN returned no JSON plan document");
42
+ return {
43
+ executionTime: numberAt(document, "Execution Time"),
44
+ planningTime: numberAt(document, "Planning Time"),
45
+ totalCost: numberAt(root, "Total Cost"),
46
+ actualRows: numberAt(root, "Actual Rows"),
47
+ bufferUsage: {
48
+ shared: buffers(root, "Shared"),
49
+ local: buffers(root, "Local")
50
+ }
51
+ };
52
+ };
53
+ export { extractExecutionMetrics, extractTableNamesFromPlan };
@@ -0,0 +1,107 @@
1
+ import * as z from "zod";
2
+ import { type ToolClientOptions } from "../../ergonomic/bind.js";
3
+ export declare const prepareQueryTuningInputSchema: z.ZodObject<{
4
+ sql: z.ZodString;
5
+ database_name: z.ZodString;
6
+ project_id: z.ZodString;
7
+ role_name: z.ZodOptional<z.ZodString>;
8
+ }, z.core.$strict>;
9
+ export declare const completeQueryTuningInputSchema: z.ZodObject<{
10
+ suggested_sql_statements: z.ZodArray<z.ZodString>;
11
+ apply_changes: z.ZodDefault<z.ZodBoolean>;
12
+ tuning_id: z.ZodString;
13
+ database_name: z.ZodString;
14
+ project_id: z.ZodString;
15
+ role_name: z.ZodOptional<z.ZodString>;
16
+ should_delete_temporary_branch: z.ZodDefault<z.ZodBoolean>;
17
+ temporary_branch_id: z.ZodString;
18
+ branch_id: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strict>;
20
+ export declare const prepareQueryTuningTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
21
+ sql: z.ZodString;
22
+ database_name: z.ZodString;
23
+ project_id: z.ZodString;
24
+ role_name: z.ZodOptional<z.ZodString>;
25
+ }, z.core.$strict>, "prepare_query_tuning", {
26
+ complete: {
27
+ tuning_id: `${string}-${string}-${string}-${string}-${string}`;
28
+ database_name: string;
29
+ project_id: string;
30
+ temporary_branch_id: string;
31
+ } | {
32
+ role_name: string;
33
+ tuning_id: `${string}-${string}-${string}-${string}-${string}`;
34
+ database_name: string;
35
+ project_id: string;
36
+ temporary_branch_id: string;
37
+ };
38
+ execution_plan: {
39
+ [x: string]: unknown;
40
+ }[];
41
+ table_schemas: {
42
+ tableName: string;
43
+ schema: {
44
+ columns: {
45
+ name: string;
46
+ type: string;
47
+ nullable: boolean;
48
+ default: string | null;
49
+ description: string | null;
50
+ }[];
51
+ indexes: {
52
+ name: string;
53
+ definition: string;
54
+ size: string;
55
+ }[];
56
+ constraints: {
57
+ name: string;
58
+ type: string;
59
+ definition: string;
60
+ }[];
61
+ tableSize: string;
62
+ indexSize: string;
63
+ totalSize: string;
64
+ };
65
+ formatted: string;
66
+ }[];
67
+ sql: string;
68
+ baseline_metrics: {
69
+ executionTime: number;
70
+ planningTime: number;
71
+ totalCost: number;
72
+ actualRows: number;
73
+ bufferUsage: {
74
+ shared: {
75
+ hit: number;
76
+ read: number;
77
+ written: number;
78
+ dirtied: number;
79
+ };
80
+ local: {
81
+ hit: number;
82
+ read: number;
83
+ written: number;
84
+ dirtied: number;
85
+ };
86
+ };
87
+ };
88
+ }>;
89
+ export declare const completeQueryTuningTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
90
+ suggested_sql_statements: z.ZodArray<z.ZodString>;
91
+ apply_changes: z.ZodDefault<z.ZodBoolean>;
92
+ tuning_id: z.ZodString;
93
+ database_name: z.ZodString;
94
+ project_id: z.ZodString;
95
+ role_name: z.ZodOptional<z.ZodString>;
96
+ should_delete_temporary_branch: z.ZodDefault<z.ZodBoolean>;
97
+ temporary_branch_id: z.ZodString;
98
+ branch_id: z.ZodOptional<z.ZodString>;
99
+ }, z.core.$strict>, "complete_query_tuning", {
100
+ message: string;
101
+ deletedBranches?: string[] | null | undefined;
102
+ results?: {
103
+ [x: string]: unknown;
104
+ }[][] | null | undefined;
105
+ appliedChanges?: string[] | null | undefined;
106
+ }>;
107
+ //# sourceMappingURL=query-tuning.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query-tuning.d.ts","sourceRoot":"","sources":["../../../../src/lib/custom/sql/query-tuning.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AAEzB,OAAO,EAGN,KAAK,iBAAiB,EACtB,MAAM,yBAAyB,CAAC;AAgBjC,eAAO,MAAM,6BAA6B;;;;;kBAQxC,CAAC;AAEH,eAAO,MAAM,8BAA8B;;;;;;;;;;kBAsCzC,CAAC;AAEH,eAAO,MAAM,sBAAsB,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA8F/D,CAAC;AAEH,eAAO,MAAM,uBAAuB,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;;;EAmEhE,CAAC"}
@@ -0,0 +1,129 @@
1
+ import { pathInputDescriptions } from "../../../descriptions.gen.js";
2
+ import { bindTool, publishedId } from "../../ergonomic/bind.js";
3
+ import { SQL_METADATA, projectIdField, refuseInReadOnly, resolveConnection } from "./connection.js";
4
+ import { describeTableAt } from "./schema.js";
5
+ import { explainStatement, runTransaction, sqlWriteAnnotations } from "./run.js";
6
+ import { withTemporaryBranch } from "./migrations.js";
7
+ import { extractExecutionMetrics, extractTableNamesFromPlan } from "./plan.js";
8
+ import { NeonClientError } from "@neon/sdk";
9
+ import * as z from "zod";
10
+ import { randomUUID } from "node:crypto";
11
+ // src/lib/custom/sql/query-tuning.ts
12
+ const prepareQueryTuningInputSchema = z.strictObject({
13
+ sql: z.string().describe("The slow SQL statement to analyze."),
14
+ database_name: z.string().describe("The database the statement runs in."),
15
+ project_id: projectIdField,
16
+ role_name: z.string().optional().describe("Postgres role to connect as. Omit for the database owner.")
17
+ });
18
+ const completeQueryTuningInputSchema = z.strictObject({
19
+ suggested_sql_statements: z.array(z.string()).describe("The DDL statements that improved the plan on the temporary branch, for example CREATE INDEX."),
20
+ apply_changes: z.boolean().default(false).describe("Apply suggested_sql_statements to branch_id."),
21
+ tuning_id: z.string().describe("The tuning_id from {{queryTuning.prepare}}, not a branch id."),
22
+ database_name: z.string().describe("The database_name from {{queryTuning.prepare}}."),
23
+ project_id: projectIdField,
24
+ role_name: z.string().optional().describe("The role_name passed to {{queryTuning.prepare}}, if any. Omit for the database owner."),
25
+ should_delete_temporary_branch: z.boolean().default(true).describe("Delete the temporary branch."),
26
+ temporary_branch_id: z.string().describe("The temporary_branch_id from {{queryTuning.prepare}}."),
27
+ branch_id: z.string().optional().describe(`${pathInputDescriptions.branch_id} The branch that receives the changes; omit it for the default branch.`)
28
+ });
29
+ const prepareQueryTuningTool = (options) => bindTool(options, {
30
+ operationId: "queryTuning.prepare",
31
+ id: publishedId("queryTuning.prepare"),
32
+ title: "Prepare Query Tuning",
33
+ description: "Runs EXPLAIN ANALYZE for a slow query on a new temporary branch; returns the plan, table schemas, and a tuning_id. Try changes there with {{sql.run}} and {{sql.explain}}, then always call {{queryTuning.complete}} with the complete object so the branch is deleted. Not {{migrations.prepare}}.",
34
+ inputSchema: prepareQueryTuningInputSchema,
35
+ annotations: {
36
+ readOnlyHint: false,
37
+ destructiveHint: false,
38
+ idempotentHint: false,
39
+ openWorldHint: false
40
+ },
41
+ requiresApproval: true,
42
+ metadata: SQL_METADATA
43
+ }, async (neonClient, input, signal, context) => {
44
+ refuseInReadOnly(context);
45
+ const projectId = input.project_id;
46
+ return withTemporaryBranch(neonClient, projectId, void 0, signal, async (branch) => {
47
+ const target = {
48
+ project_id: projectId,
49
+ branch_id: branch.id,
50
+ database_name: input.database_name,
51
+ role_name: input.role_name
52
+ };
53
+ const executionPlan = await explainStatement(neonClient, {
54
+ ...target,
55
+ sql: input.sql,
56
+ analyze: true
57
+ }, context, signal);
58
+ const tableNames = extractTableNamesFromPlan(executionPlan);
59
+ if (tableNames.length === 0) throw new NeonClientError("No tables found in execution plan. Cannot proceed with optimization.");
60
+ const connection = await resolveConnection(neonClient, target, context, signal);
61
+ const tableSchemas = await Promise.all(tableNames.map(async (tableName) => {
62
+ try {
63
+ const schema = await describeTableAt(connection.uri, tableName, signal);
64
+ return {
65
+ tableName,
66
+ schema: schema.raw,
67
+ formatted: schema.formatted
68
+ };
69
+ } catch (error) {
70
+ throw new Error(`Failed to get schema for table ${tableName}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
71
+ }
72
+ }));
73
+ const ids = {
74
+ tuning_id: randomUUID(),
75
+ database_name: input.database_name,
76
+ project_id: projectId,
77
+ temporary_branch_id: branch.id
78
+ };
79
+ return {
80
+ complete: input.role_name === void 0 ? ids : {
81
+ ...ids,
82
+ role_name: input.role_name
83
+ },
84
+ execution_plan: executionPlan,
85
+ table_schemas: tableSchemas,
86
+ sql: input.sql,
87
+ baseline_metrics: extractExecutionMetrics(executionPlan)
88
+ };
89
+ });
90
+ });
91
+ const completeQueryTuningTool = (options) => bindTool(options, {
92
+ operationId: "queryTuning.complete",
93
+ id: publishedId("queryTuning.complete"),
94
+ title: "Complete Query Tuning",
95
+ description: "Applies or discards query-tuning changes and deletes the temporary branch. NEVER run autonomously. Pass the complete object from {{queryTuning.prepare}} and suggested_sql_statements; apply_changes true applies, omitted discards. Call it even when the user rejects.",
96
+ inputSchema: completeQueryTuningInputSchema,
97
+ annotations: sqlWriteAnnotations,
98
+ requiresApproval: true,
99
+ metadata: SQL_METADATA
100
+ }, async (neonClient, input, signal, context) => {
101
+ refuseInReadOnly(context);
102
+ const operationLog = [];
103
+ let results;
104
+ if (input.apply_changes && input.suggested_sql_statements.length > 0) {
105
+ operationLog.push("Applying optimizations to main branch...");
106
+ results = await runTransaction(neonClient, {
107
+ project_id: input.project_id,
108
+ branch_id: input.branch_id,
109
+ database_name: input.database_name,
110
+ role_name: input.role_name
111
+ }, input.suggested_sql_statements, context, signal);
112
+ operationLog.push("Successfully applied optimizations to main branch.");
113
+ } else operationLog.push("No changes were applied (either none suggested or changes were discarded).");
114
+ if (input.should_delete_temporary_branch) {
115
+ operationLog.push("Cleaning up temporary branch...");
116
+ await neonClient.branches.delete({
117
+ projectId: input.project_id,
118
+ branchId: input.temporary_branch_id
119
+ }, { signal });
120
+ operationLog.push("Successfully cleaned up temporary branch.");
121
+ }
122
+ return {
123
+ ...input.apply_changes && { appliedChanges: input.suggested_sql_statements },
124
+ ...results === void 0 ? {} : { results },
125
+ ...input.should_delete_temporary_branch && { deletedBranches: [input.temporary_branch_id] },
126
+ message: operationLog.join("\n")
127
+ };
128
+ });
129
+ export { completeQueryTuningInputSchema, completeQueryTuningTool, prepareQueryTuningInputSchema, prepareQueryTuningTool };
@@ -0,0 +1,11 @@
1
+ export declare const SQL_DEFAULT_MAX_ROWS = 100;
2
+ export declare const SQL_MAX_ROWS_LIMIT = 10000;
3
+ export type Row = Record<string, unknown>;
4
+ export interface StatementRows {
5
+ rows: Row[];
6
+ totalRowCount: number;
7
+ truncated: boolean;
8
+ note?: string;
9
+ }
10
+ export declare const capRows: (rows: Row[], maxRows: number) => StatementRows;
11
+ //# sourceMappingURL=rows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rows.d.ts","sourceRoot":"","sources":["../../../../src/lib/custom/sql/rows.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB,MAAM,CAAC;AACxC,eAAO,MAAM,kBAAkB,QAAS,CAAC;AAEzC,MAAM,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE1C,MAAM,WAAW,aAAa;IAC7B,IAAI,EAAE,GAAG,EAAE,CAAC;IACZ,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,OAAO,CAAC;IACnB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAcD,eAAO,MAAM,OAAO,GAAI,MAAM,GAAG,EAAE,EAAE,SAAS,MAAM,KAAG,aAQtD,CAAC"}
@@ -0,0 +1,19 @@
1
+ // src/lib/custom/sql/rows.ts
2
+ const SQL_DEFAULT_MAX_ROWS = 100;
3
+ const SQL_MAX_ROWS_LIMIT = 1e4;
4
+ const truncationNote = (maxRows, totalRowCount) => {
5
+ const shown = `Showing the first ${maxRows} of ${totalRowCount} rows.`;
6
+ const rerun = "The SQL already ran, so if it changed data, running it again repeats the change.";
7
+ if (maxRows < 1e4) return `${shown} To see more, raise \`max_rows\` or narrow the query with WHERE or LIMIT. ${rerun}`;
8
+ return `${shown} That is the maximum this tool returns. To see the rest, narrow the query with WHERE or LIMIT. ${rerun}`;
9
+ };
10
+ const capRows = (rows, maxRows) => {
11
+ const truncated = rows.length > maxRows;
12
+ return {
13
+ rows: truncated ? rows.slice(0, maxRows) : rows,
14
+ totalRowCount: rows.length,
15
+ truncated,
16
+ ...truncated && { note: truncationNote(maxRows, rows.length) }
17
+ };
18
+ };
19
+ export { SQL_DEFAULT_MAX_ROWS, SQL_MAX_ROWS_LIMIT, capRows };
@@ -0,0 +1,81 @@
1
+ import type { NeonClient } from "@neon/sdk";
2
+ import * as z from "zod";
3
+ import { type ToolClientOptions } from "../../ergonomic/bind.js";
4
+ import type { NeonToolAnnotations, NeonToolExecutionContext } from "../../operation.js";
5
+ import { type ConnectionTarget } from "./connection.js";
6
+ import { type Row } from "./rows.js";
7
+ export declare const sqlWriteAnnotations: NeonToolAnnotations;
8
+ export declare const runSqlInputSchema: z.ZodObject<{
9
+ sql: z.ZodString;
10
+ project_id: z.ZodString;
11
+ branch_id: z.ZodOptional<z.ZodString>;
12
+ database_name: z.ZodOptional<z.ZodString>;
13
+ role_name: z.ZodOptional<z.ZodString>;
14
+ compute_id: z.ZodOptional<z.ZodString>;
15
+ max_rows: z.ZodDefault<z.ZodNumber>;
16
+ }, z.core.$strict>;
17
+ export declare const runSqlTransactionInputSchema: z.ZodObject<{
18
+ sql_statements: z.ZodArray<z.ZodString>;
19
+ project_id: z.ZodString;
20
+ branch_id: z.ZodOptional<z.ZodString>;
21
+ database_name: z.ZodOptional<z.ZodString>;
22
+ role_name: z.ZodOptional<z.ZodString>;
23
+ compute_id: z.ZodOptional<z.ZodString>;
24
+ max_rows: z.ZodDefault<z.ZodNumber>;
25
+ }, z.core.$strict>;
26
+ export declare const explainSqlInputSchema: z.ZodObject<{
27
+ sql: z.ZodString;
28
+ project_id: z.ZodString;
29
+ branch_id: z.ZodOptional<z.ZodString>;
30
+ database_name: z.ZodOptional<z.ZodString>;
31
+ analyze: z.ZodDefault<z.ZodBoolean>;
32
+ }, z.core.$strict>;
33
+ /** One caller statement, in its own `READ ONLY` transaction when `readOnly` is set. */
34
+ export declare const runStatement: (neonClient: NeonClient<true>, target: ConnectionTarget, sql: string, context: NeonToolExecutionContext, signal?: AbortSignal) => Promise<Row[]>;
35
+ export declare const runTransaction: (neonClient: NeonClient<true>, target: ConnectionTarget, statements: readonly string[], context: NeonToolExecutionContext, signal?: AbortSignal) => Promise<Row[][]>;
36
+ export declare const explainStatement: (neonClient: NeonClient<true>, input: {
37
+ sql: string;
38
+ analyze: boolean;
39
+ } & ConnectionTarget, context: NeonToolExecutionContext, signal?: AbortSignal) => Promise<Row[]>;
40
+ export declare const runSqlTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
41
+ sql: z.ZodString;
42
+ project_id: z.ZodString;
43
+ branch_id: z.ZodOptional<z.ZodString>;
44
+ database_name: z.ZodOptional<z.ZodString>;
45
+ role_name: z.ZodOptional<z.ZodString>;
46
+ compute_id: z.ZodOptional<z.ZodString>;
47
+ max_rows: z.ZodDefault<z.ZodNumber>;
48
+ }, z.core.$strict>, "run_sql", {
49
+ rows: {
50
+ [x: string]: unknown;
51
+ }[];
52
+ totalRowCount: number;
53
+ truncated: boolean;
54
+ note?: string | null | undefined;
55
+ }>;
56
+ export declare const runSqlTransactionTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
57
+ sql_statements: z.ZodArray<z.ZodString>;
58
+ project_id: z.ZodString;
59
+ branch_id: z.ZodOptional<z.ZodString>;
60
+ database_name: z.ZodOptional<z.ZodString>;
61
+ role_name: z.ZodOptional<z.ZodString>;
62
+ compute_id: z.ZodOptional<z.ZodString>;
63
+ max_rows: z.ZodDefault<z.ZodNumber>;
64
+ }, z.core.$strict>, "run_transaction_sql", {
65
+ rows: {
66
+ [x: string]: unknown;
67
+ }[];
68
+ totalRowCount: number;
69
+ truncated: boolean;
70
+ note?: string | null | undefined;
71
+ }[]>;
72
+ export declare const explainSqlTool: (options: ToolClientOptions) => import("../../operation.js").NeonTool<z.ZodObject<{
73
+ sql: z.ZodString;
74
+ project_id: z.ZodString;
75
+ branch_id: z.ZodOptional<z.ZodString>;
76
+ database_name: z.ZodOptional<z.ZodString>;
77
+ analyze: z.ZodDefault<z.ZodBoolean>;
78
+ }, z.core.$strict>, "explain_sql", {
79
+ [x: string]: unknown;
80
+ }[]>;
81
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"run.d.ts","sourceRoot":"","sources":["../../../../src/lib/custom/sql/run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC;AACzB,OAAO,EAGN,KAAK,iBAAiB,EACtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EACX,mBAAmB,EACnB,wBAAwB,EACxB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAEN,KAAK,gBAAgB,EASrB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEN,KAAK,GAAG,EAGR,MAAM,WAAW,CAAC;AAEnB,eAAO,MAAM,mBAAmB,EAAE,mBAKjC,CAAC;AAYF,eAAO,MAAM,iBAAiB;;;;;;;;kBAQ5B,CAAC;AAEH,eAAO,MAAM,4BAA4B;;;;;;;;kBAUvC,CAAC;AAEH,eAAO,MAAM,qBAAqB;;;;;;kBAWhC,CAAC;AAEH,uFAAuF;AACvF,eAAO,MAAM,YAAY,GACxB,YAAY,UAAU,CAAC,IAAI,CAAC,EAC5B,QAAQ,gBAAgB,EACxB,KAAK,MAAM,EACX,SAAS,wBAAwB,EACjC,SAAS,WAAW,KAClB,OAAO,CAAC,GAAG,EAAE,CAef,CAAC;AAEF,eAAO,MAAM,cAAc,GAC1B,YAAY,UAAU,CAAC,IAAI,CAAC,EAC5B,QAAQ,gBAAgB,EACxB,YAAY,SAAS,MAAM,EAAE,EAC7B,SAAS,wBAAwB,EACjC,SAAS,WAAW,KAClB,OAAO,CAAC,GAAG,EAAE,EAAE,CAWjB,CAAC;AAEF,eAAO,MAAM,gBAAgB,GAC5B,YAAY,UAAU,CAAC,IAAI,CAAC,EAC5B,OAAO;IACN,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;CACjB,GAAG,gBAAgB,EACpB,SAAS,wBAAwB,EACjC,SAAS,WAAW,KAClB,OAAO,CAAC,GAAG,EAAE,CAWf,CAAC;AAEF,eAAO,MAAM,UAAU,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;EAyBnD,CAAC;AAEH,eAAO,MAAM,qBAAqB,GAAI,SAAS,iBAAiB;;;;;;;;;;;;;;;IAyB9D,CAAC;AAEH,eAAO,MAAM,cAAc,GAAI,SAAS,iBAAiB;;;;;;;;IAgBvD,CAAC"}