truss-db-mcp 1.0.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +69 -0
  3. package/dist/index.d.ts +3 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +79 -0
  6. package/dist/index.js.map +1 -0
  7. package/dist/lib/ai-query.d.ts +7 -0
  8. package/dist/lib/ai-query.d.ts.map +1 -0
  9. package/dist/lib/ai-query.js +224 -0
  10. package/dist/lib/ai-query.js.map +1 -0
  11. package/dist/lib/config.d.ts +4 -0
  12. package/dist/lib/config.d.ts.map +1 -0
  13. package/dist/lib/config.js +30 -0
  14. package/dist/lib/config.js.map +1 -0
  15. package/dist/lib/connection.d.ts +14 -0
  16. package/dist/lib/connection.d.ts.map +1 -0
  17. package/dist/lib/connection.js +175 -0
  18. package/dist/lib/connection.js.map +1 -0
  19. package/dist/lib/license.d.ts +4 -0
  20. package/dist/lib/license.d.ts.map +1 -0
  21. package/dist/lib/license.js +94 -0
  22. package/dist/lib/license.js.map +1 -0
  23. package/dist/lib/query-optimizer.d.ts +3 -0
  24. package/dist/lib/query-optimizer.d.ts.map +1 -0
  25. package/dist/lib/query-optimizer.js +155 -0
  26. package/dist/lib/query-optimizer.js.map +1 -0
  27. package/dist/tools/connect.d.ts +3 -0
  28. package/dist/tools/connect.d.ts.map +1 -0
  29. package/dist/tools/connect.js +37 -0
  30. package/dist/tools/connect.js.map +1 -0
  31. package/dist/tools/describe-table.d.ts +3 -0
  32. package/dist/tools/describe-table.d.ts.map +1 -0
  33. package/dist/tools/describe-table.js +60 -0
  34. package/dist/tools/describe-table.js.map +1 -0
  35. package/dist/tools/export-data.d.ts +3 -0
  36. package/dist/tools/export-data.d.ts.map +1 -0
  37. package/dist/tools/export-data.js +68 -0
  38. package/dist/tools/export-data.js.map +1 -0
  39. package/dist/tools/generate-migration.d.ts +3 -0
  40. package/dist/tools/generate-migration.d.ts.map +1 -0
  41. package/dist/tools/generate-migration.js +36 -0
  42. package/dist/tools/generate-migration.js.map +1 -0
  43. package/dist/tools/list-tables.d.ts +3 -0
  44. package/dist/tools/list-tables.d.ts.map +1 -0
  45. package/dist/tools/list-tables.js +45 -0
  46. package/dist/tools/list-tables.js.map +1 -0
  47. package/dist/tools/natural-language-query.d.ts +3 -0
  48. package/dist/tools/natural-language-query.d.ts.map +1 -0
  49. package/dist/tools/natural-language-query.js +53 -0
  50. package/dist/tools/natural-language-query.js.map +1 -0
  51. package/dist/tools/optimize-query.d.ts +3 -0
  52. package/dist/tools/optimize-query.d.ts.map +1 -0
  53. package/dist/tools/optimize-query.js +51 -0
  54. package/dist/tools/optimize-query.js.map +1 -0
  55. package/dist/tools/query.d.ts +3 -0
  56. package/dist/tools/query.d.ts.map +1 -0
  57. package/dist/tools/query.js +79 -0
  58. package/dist/tools/query.js.map +1 -0
  59. package/dist/types.d.ts +86 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/dist/types.js +3 -0
  62. package/dist/types.js.map +1 -0
  63. package/evals/eval-query.ts +356 -0
  64. package/evals/run-evals.ts +36 -0
  65. package/evals/test.db +0 -0
  66. package/glama.json +4 -0
  67. package/package.json +47 -0
  68. package/smithery.yaml +18 -0
  69. package/src/index.ts +99 -0
  70. package/src/lib/ai-query.ts +274 -0
  71. package/src/lib/config.ts +33 -0
  72. package/src/lib/connection.ts +263 -0
  73. package/src/lib/license.ts +118 -0
  74. package/src/lib/query-optimizer.ts +191 -0
  75. package/src/tools/connect.ts +43 -0
  76. package/src/tools/describe-table.ts +67 -0
  77. package/src/tools/export-data.ts +81 -0
  78. package/src/tools/generate-migration.ts +43 -0
  79. package/src/tools/list-tables.ts +52 -0
  80. package/src/tools/natural-language-query.ts +61 -0
  81. package/src/tools/optimize-query.ts +59 -0
  82. package/src/tools/query.ts +89 -0
  83. package/src/types.ts +115 -0
  84. package/tsconfig.json +19 -0
@@ -0,0 +1,191 @@
1
+ import { explainQuery, getDb, listTables } from './connection.js';
2
+ import type { QueryOptimizationResult, OptimizationSuggestion } from '../types.js';
3
+
4
+ export function optimizeQuery(sql: string): QueryOptimizationResult {
5
+ const explainPlan = explainQuery(sql);
6
+ const suggestions = analyzeExplainPlan(explainPlan, sql);
7
+ const estimatedImprovement = estimateImprovement(suggestions);
8
+
9
+ return {
10
+ explainPlan,
11
+ suggestions,
12
+ estimatedImprovement,
13
+ };
14
+ }
15
+
16
+ function analyzeExplainPlan(plan: string, sql: string): OptimizationSuggestion[] {
17
+ const suggestions: OptimizationSuggestion[] = [];
18
+ const lines = plan.split('\n');
19
+
20
+ // Detect full table scans
21
+ const scanPattern = /SCAN (?:TABLE )?(\w+)/gi;
22
+ const scannedTables = new Set<string>();
23
+
24
+ for (const line of lines) {
25
+ let match;
26
+ while ((match = scanPattern.exec(line)) !== null) {
27
+ scannedTables.add(match[1]);
28
+ }
29
+ }
30
+
31
+ // For each full scan, check if WHERE clause references columns that could be indexed
32
+ if (scannedTables.size > 0) {
33
+ const whereColumns = extractWhereColumns(sql);
34
+
35
+ for (const table of scannedTables) {
36
+ const tableCols = whereColumns.filter(wc => {
37
+ // Column might be qualified (table.col) or unqualified
38
+ return wc.table === table || wc.table === null;
39
+ });
40
+
41
+ if (tableCols.length > 0) {
42
+ const existingIndexes = getExistingIndexes(table);
43
+ const indexedColumns = new Set(existingIndexes.flatMap(idx => idx.columns));
44
+
45
+ for (const col of tableCols) {
46
+ if (!indexedColumns.has(col.column)) {
47
+ suggestions.push({
48
+ type: 'index',
49
+ description: `Table "${table}" is doing a full scan. Consider adding an index on column "${col.column}" used in WHERE clause.`,
50
+ sql: `CREATE INDEX idx_${table}_${col.column} ON "${table}"("${col.column}");`,
51
+ });
52
+ }
53
+ }
54
+
55
+ if (tableCols.length === 0) {
56
+ suggestions.push({
57
+ type: 'warning',
58
+ description: `Full table scan on "${table}". This may be intentional if you need all rows, but can be slow on large tables.`,
59
+ });
60
+ }
61
+ } else {
62
+ suggestions.push({
63
+ type: 'warning',
64
+ description: `Full table scan on "${table}". No WHERE clause filtering detected for this table.`,
65
+ });
66
+ }
67
+ }
68
+ }
69
+
70
+ // Detect subquery patterns that could be JOINs
71
+ if (/\bIN\s*\(\s*SELECT\b/i.test(sql)) {
72
+ suggestions.push({
73
+ type: 'rewrite',
74
+ description: 'Consider rewriting IN (SELECT ...) as a JOIN, which is often faster for large datasets.',
75
+ });
76
+ }
77
+
78
+ // Detect SELECT * usage
79
+ if (/SELECT\s+\*/i.test(sql)) {
80
+ suggestions.push({
81
+ type: 'rewrite',
82
+ description: 'Consider selecting only the columns you need instead of SELECT *. This reduces I/O and memory usage.',
83
+ });
84
+ }
85
+
86
+ // Detect missing LIMIT
87
+ if (!/\bLIMIT\b/i.test(sql) && /^\s*SELECT\b/i.test(sql)) {
88
+ suggestions.push({
89
+ type: 'warning',
90
+ description: 'Query has no LIMIT clause. For large tables, consider adding LIMIT to avoid returning excessive rows.',
91
+ });
92
+ }
93
+
94
+ // Detect LIKE with leading wildcard
95
+ if (/LIKE\s+['"]%/i.test(sql)) {
96
+ suggestions.push({
97
+ type: 'warning',
98
+ description: 'LIKE pattern with leading wildcard (%) prevents index usage. Consider full-text search for better performance.',
99
+ });
100
+ }
101
+
102
+ // Detect ORDER BY without index
103
+ const orderByMatch = sql.match(/ORDER\s+BY\s+(\w+(?:\.\w+)?)/i);
104
+ if (orderByMatch) {
105
+ const orderCol = orderByMatch[1].includes('.') ? orderByMatch[1].split('.')[1] : orderByMatch[1];
106
+ suggestions.push({
107
+ type: 'index',
108
+ description: `If sorting is slow, consider indexing the ORDER BY column "${orderCol}".`,
109
+ });
110
+ }
111
+
112
+ // If no scan detected, query uses indexes well
113
+ if (scannedTables.size === 0 && suggestions.length === 0) {
114
+ suggestions.push({
115
+ type: 'rewrite',
116
+ description: 'Query already uses indexes effectively. No major optimizations needed.',
117
+ });
118
+ }
119
+
120
+ return suggestions;
121
+ }
122
+
123
+ interface WhereColumn {
124
+ table: string | null;
125
+ column: string;
126
+ }
127
+
128
+ function extractWhereColumns(sql: string): WhereColumn[] {
129
+ const columns: WhereColumn[] = [];
130
+
131
+ // Match WHERE and AND/OR conditions
132
+ const whereMatch = sql.match(/WHERE\s+([\s\S]*?)(?:ORDER\s+BY|GROUP\s+BY|HAVING|LIMIT|$)/i);
133
+ if (!whereMatch) return columns;
134
+
135
+ const whereClause = whereMatch[1];
136
+
137
+ // Extract column references from conditions
138
+ const colPattern = /(\w+)\.(\w+)\s*(?:=|!=|<>|>=|<=|>|<|LIKE|IN|IS|BETWEEN)/gi;
139
+ let match;
140
+
141
+ while ((match = colPattern.exec(whereClause)) !== null) {
142
+ columns.push({ table: match[1], column: match[2] });
143
+ }
144
+
145
+ // Also match unqualified columns
146
+ const unqualPattern = /(?:^|\bAND\b|\bOR\b|\bWHERE\b)\s+(\w+)\s*(?:=|!=|<>|>=|<=|>|<|LIKE|IN|IS|BETWEEN)/gi;
147
+ while ((match = unqualPattern.exec(whereClause)) !== null) {
148
+ if (!['AND', 'OR', 'NOT', 'WHERE', 'BETWEEN', 'IN', 'LIKE', 'IS'].includes(match[1].toUpperCase())) {
149
+ columns.push({ table: null, column: match[1] });
150
+ }
151
+ }
152
+
153
+ return columns;
154
+ }
155
+
156
+ function getExistingIndexes(tableName: string): Array<{ name: string; columns: string[] }> {
157
+ try {
158
+ const db = getDb();
159
+ const indexes = db.pragma(`index_list("${tableName}")`) as Array<{
160
+ name: string;
161
+ unique: number;
162
+ }>;
163
+
164
+ return indexes.map(idx => {
165
+ const cols = db.pragma(`index_info("${idx.name}")`) as Array<{ name: string }>;
166
+ return { name: idx.name, columns: cols.map(c => c.name) };
167
+ });
168
+ } catch {
169
+ return [];
170
+ }
171
+ }
172
+
173
+ function estimateImprovement(suggestions: OptimizationSuggestion[]): string {
174
+ const indexSuggestions = suggestions.filter(s => s.type === 'index').length;
175
+ const rewriteSuggestions = suggestions.filter(s => s.type === 'rewrite').length;
176
+ const warnings = suggestions.filter(s => s.type === 'warning').length;
177
+
178
+ if (indexSuggestions === 0 && rewriteSuggestions === 0) {
179
+ return 'Query is already well-optimized.';
180
+ }
181
+
182
+ if (indexSuggestions > 0) {
183
+ return `Adding ${indexSuggestions} index(es) could improve performance significantly, especially on large tables (10x-100x for indexed lookups vs full scans).`;
184
+ }
185
+
186
+ if (rewriteSuggestions > 0) {
187
+ return 'Query rewrite may improve performance by 2x-10x depending on data size.';
188
+ }
189
+
190
+ return 'Minor optimizations possible. See suggestions for details.';
191
+ }
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { connectSqlite } from '../lib/connection.js';
4
+
5
+ export function registerConnect(server: McpServer): void {
6
+ server.tool(
7
+ 'connect',
8
+ 'Connect to a SQLite database file. Provide the path to the .db or .sqlite file.',
9
+ {
10
+ path: z.string().describe('Path to the SQLite database file'),
11
+ },
12
+ async ({ path }) => {
13
+ try {
14
+ const info = connectSqlite(path);
15
+
16
+ return {
17
+ content: [{
18
+ type: 'text' as const,
19
+ text: JSON.stringify({
20
+ connected: info.connected,
21
+ dialect: info.dialect,
22
+ tables: info.tables,
23
+ tableCount: info.tables.length,
24
+ version: info.version,
25
+ path: info.path,
26
+ }, null, 2),
27
+ }],
28
+ };
29
+ } catch (err) {
30
+ return {
31
+ content: [{
32
+ type: 'text' as const,
33
+ text: JSON.stringify({
34
+ connected: false,
35
+ error: err instanceof Error ? err.message : String(err),
36
+ }),
37
+ }],
38
+ isError: true,
39
+ };
40
+ }
41
+ }
42
+ );
43
+ }
@@ -0,0 +1,67 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { describeTable, isConnected } from '../lib/connection.js';
4
+
5
+ export function registerDescribeTable(server: McpServer): void {
6
+ server.tool(
7
+ 'describe_table',
8
+ 'Get detailed schema for a table: columns, types, indexes, foreign keys, and CREATE statement.',
9
+ {
10
+ table: z.string().describe('Name of the table to describe'),
11
+ },
12
+ async ({ table }) => {
13
+ try {
14
+ if (!isConnected()) {
15
+ return {
16
+ content: [{
17
+ type: 'text' as const,
18
+ text: JSON.stringify({
19
+ error: 'No database connected. Use the connect tool first.',
20
+ }),
21
+ }],
22
+ isError: true,
23
+ };
24
+ }
25
+
26
+ const schema = describeTable(table);
27
+
28
+ return {
29
+ content: [{
30
+ type: 'text' as const,
31
+ text: JSON.stringify({
32
+ name: schema.name,
33
+ row_count: schema.rowCount,
34
+ columns: schema.columns.map(c => ({
35
+ name: c.name,
36
+ type: c.type,
37
+ nullable: c.nullable,
38
+ default_value: c.defaultValue,
39
+ primary_key: c.primaryKey,
40
+ })),
41
+ indexes: schema.indexes.map(i => ({
42
+ name: i.name,
43
+ columns: i.columns,
44
+ unique: i.unique,
45
+ })),
46
+ foreign_keys: schema.foreignKeys.map(fk => ({
47
+ column: fk.column,
48
+ references: `${fk.referencedTable}(${fk.referencedColumn})`,
49
+ })),
50
+ create_sql: schema.createSql,
51
+ }, null, 2),
52
+ }],
53
+ };
54
+ } catch (err) {
55
+ return {
56
+ content: [{
57
+ type: 'text' as const,
58
+ text: JSON.stringify({
59
+ error: err instanceof Error ? err.message : String(err),
60
+ }),
61
+ }],
62
+ isError: true,
63
+ };
64
+ }
65
+ }
66
+ );
67
+ }
@@ -0,0 +1,81 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { executeReadOnlyQuery, isConnected } from '../lib/connection.js';
4
+ import { requirePro } from '../lib/license.js';
5
+
6
+ function toCsv(rows: Record<string, unknown>[], columns: string[]): string {
7
+ if (rows.length === 0) return '';
8
+
9
+ const header = columns.map(escapeCsvField).join(',');
10
+ const dataRows = rows.map(row =>
11
+ columns.map(col => escapeCsvField(String(row[col] ?? ''))).join(',')
12
+ );
13
+
14
+ return [header, ...dataRows].join('\n');
15
+ }
16
+
17
+ function escapeCsvField(field: string): string {
18
+ if (field.includes(',') || field.includes('"') || field.includes('\n')) {
19
+ return `"${field.replace(/"/g, '""')}"`;
20
+ }
21
+ return field;
22
+ }
23
+
24
+ export function registerExportData(server: McpServer): void {
25
+ server.tool(
26
+ 'export_data',
27
+ 'Export query results as CSV or JSON. Requires Pro license.',
28
+ {
29
+ sql: z.string().describe('SELECT query to export'),
30
+ format: z.enum(['csv', 'json']).describe('Export format: csv or json'),
31
+ },
32
+ async ({ sql, format }) => {
33
+ try {
34
+ await requirePro();
35
+
36
+ if (!isConnected()) {
37
+ return {
38
+ content: [{
39
+ type: 'text' as const,
40
+ text: JSON.stringify({
41
+ error: 'No database connected. Use the connect tool first.',
42
+ }),
43
+ }],
44
+ isError: true,
45
+ };
46
+ }
47
+
48
+ // Always read-only for exports
49
+ const result = executeReadOnlyQuery(sql);
50
+
51
+ let data: string;
52
+ if (format === 'csv') {
53
+ data = toCsv(result.rows, result.columns);
54
+ } else {
55
+ data = JSON.stringify(result.rows, null, 2);
56
+ }
57
+
58
+ return {
59
+ content: [{
60
+ type: 'text' as const,
61
+ text: JSON.stringify({
62
+ data,
63
+ row_count: result.rowCount,
64
+ format,
65
+ }, null, 2),
66
+ }],
67
+ };
68
+ } catch (err) {
69
+ return {
70
+ content: [{
71
+ type: 'text' as const,
72
+ text: JSON.stringify({
73
+ error: err instanceof Error ? err.message : String(err),
74
+ }),
75
+ }],
76
+ isError: true,
77
+ };
78
+ }
79
+ }
80
+ );
81
+ }
@@ -0,0 +1,43 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { requirePro } from '../lib/license.js';
4
+ import { generateMigrationSql } from '../lib/ai-query.js';
5
+
6
+ export function registerGenerateMigration(server: McpServer): void {
7
+ server.tool(
8
+ 'generate_migration',
9
+ 'Generate SQL migration (up + down) from a natural language description. Requires Pro license and AI API key.',
10
+ {
11
+ description: z.string().describe('Description of the database change (e.g. "add email column to users table")'),
12
+ dialect: z.enum(['sqlite', 'postgresql', 'mysql']).optional().describe('SQL dialect (default: sqlite)'),
13
+ },
14
+ async ({ description, dialect }) => {
15
+ try {
16
+ await requirePro();
17
+
18
+ const result = await generateMigrationSql(description, dialect ?? 'sqlite');
19
+
20
+ return {
21
+ content: [{
22
+ type: 'text' as const,
23
+ text: JSON.stringify({
24
+ up_sql: result.upSql,
25
+ down_sql: result.downSql,
26
+ dialect: dialect ?? 'sqlite',
27
+ }, null, 2),
28
+ }],
29
+ };
30
+ } catch (err) {
31
+ return {
32
+ content: [{
33
+ type: 'text' as const,
34
+ text: JSON.stringify({
35
+ error: err instanceof Error ? err.message : String(err),
36
+ }),
37
+ }],
38
+ isError: true,
39
+ };
40
+ }
41
+ }
42
+ );
43
+ }
@@ -0,0 +1,52 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { listTables, isConnected } from '../lib/connection.js';
3
+
4
+ export function registerListTables(server: McpServer): void {
5
+ server.tool(
6
+ 'list_tables',
7
+ 'List all tables in the connected database with row counts and column info.',
8
+ {},
9
+ async () => {
10
+ try {
11
+ if (!isConnected()) {
12
+ return {
13
+ content: [{
14
+ type: 'text' as const,
15
+ text: JSON.stringify({
16
+ error: 'No database connected. Use the connect tool first.',
17
+ }),
18
+ }],
19
+ isError: true,
20
+ };
21
+ }
22
+
23
+ const tables = listTables();
24
+
25
+ return {
26
+ content: [{
27
+ type: 'text' as const,
28
+ text: JSON.stringify(tables.map(t => ({
29
+ name: t.name,
30
+ columns: t.columns.map(c => ({
31
+ name: c.name,
32
+ type: c.type,
33
+ nullable: c.nullable,
34
+ })),
35
+ row_count: t.rowCount,
36
+ })), null, 2),
37
+ }],
38
+ };
39
+ } catch (err) {
40
+ return {
41
+ content: [{
42
+ type: 'text' as const,
43
+ text: JSON.stringify({
44
+ error: err instanceof Error ? err.message : String(err),
45
+ }),
46
+ }],
47
+ isError: true,
48
+ };
49
+ }
50
+ }
51
+ );
52
+ }
@@ -0,0 +1,61 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { isConnected } from '../lib/connection.js';
4
+ import { requirePro } from '../lib/license.js';
5
+ import { naturalLanguageToSql } from '../lib/ai-query.js';
6
+
7
+ export function registerNaturalLanguageQuery(server: McpServer): void {
8
+ server.tool(
9
+ 'natural_language_query',
10
+ 'Convert a natural language question to SQL and execute it. Requires Pro license and ANTHROPIC_API_KEY or OPENAI_API_KEY.',
11
+ {
12
+ question: z.string().describe('Natural language question about your data'),
13
+ tables: z.array(z.string()).optional().describe('Limit query generation to these tables'),
14
+ },
15
+ async ({ question, tables }) => {
16
+ try {
17
+ await requirePro();
18
+
19
+ if (!isConnected()) {
20
+ return {
21
+ content: [{
22
+ type: 'text' as const,
23
+ text: JSON.stringify({
24
+ error: 'No database connected. Use the connect tool first.',
25
+ }),
26
+ }],
27
+ isError: true,
28
+ };
29
+ }
30
+
31
+ const result = await naturalLanguageToSql(question, tables);
32
+
33
+ return {
34
+ content: [{
35
+ type: 'text' as const,
36
+ text: JSON.stringify({
37
+ sql: result.sql,
38
+ explanation: result.explanation,
39
+ results: {
40
+ rows: result.results.rows,
41
+ columns: result.results.columns,
42
+ row_count: result.results.rowCount,
43
+ execution_time_ms: result.results.executionTimeMs,
44
+ },
45
+ }, null, 2),
46
+ }],
47
+ };
48
+ } catch (err) {
49
+ return {
50
+ content: [{
51
+ type: 'text' as const,
52
+ text: JSON.stringify({
53
+ error: err instanceof Error ? err.message : String(err),
54
+ }),
55
+ }],
56
+ isError: true,
57
+ };
58
+ }
59
+ }
60
+ );
61
+ }
@@ -0,0 +1,59 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { isConnected } from '../lib/connection.js';
4
+ import { requirePro } from '../lib/license.js';
5
+ import { optimizeQuery } from '../lib/query-optimizer.js';
6
+
7
+ export function registerOptimizeQuery(server: McpServer): void {
8
+ server.tool(
9
+ 'optimize_query',
10
+ 'Analyze a SQL query for performance issues. Shows EXPLAIN plan, suggests indexes, and estimates improvement. Requires Pro license.',
11
+ {
12
+ sql: z.string().describe('SQL query to analyze'),
13
+ },
14
+ async ({ sql }) => {
15
+ try {
16
+ await requirePro();
17
+
18
+ if (!isConnected()) {
19
+ return {
20
+ content: [{
21
+ type: 'text' as const,
22
+ text: JSON.stringify({
23
+ error: 'No database connected. Use the connect tool first.',
24
+ }),
25
+ }],
26
+ isError: true,
27
+ };
28
+ }
29
+
30
+ const result = optimizeQuery(sql);
31
+
32
+ return {
33
+ content: [{
34
+ type: 'text' as const,
35
+ text: JSON.stringify({
36
+ explain_plan: result.explainPlan,
37
+ suggestions: result.suggestions.map(s => ({
38
+ type: s.type,
39
+ description: s.description,
40
+ ...(s.sql ? { suggested_sql: s.sql } : {}),
41
+ })),
42
+ estimated_improvement: result.estimatedImprovement,
43
+ }, null, 2),
44
+ }],
45
+ };
46
+ } catch (err) {
47
+ return {
48
+ content: [{
49
+ type: 'text' as const,
50
+ text: JSON.stringify({
51
+ error: err instanceof Error ? err.message : String(err),
52
+ }),
53
+ }],
54
+ isError: true,
55
+ };
56
+ }
57
+ }
58
+ );
59
+ }
@@ -0,0 +1,89 @@
1
+ import { z } from 'zod';
2
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ import { executeReadOnlyQuery, executeQuery, isConnected, isWriteQuery } from '../lib/connection.js';
4
+ import { getLicenseStatus } from '../lib/license.js';
5
+
6
+ export function registerQuery(server: McpServer): void {
7
+ server.tool(
8
+ 'query',
9
+ 'Execute a SQL query. Free tier: SELECT only. Pro tier: full read/write with confirmation flag.',
10
+ {
11
+ sql: z.string().describe('SQL query to execute'),
12
+ params: z.array(z.unknown()).optional().describe('Query parameters for prepared statement'),
13
+ confirm_write: z.boolean().optional().describe('Set to true to confirm write operations (Pro tier only)'),
14
+ },
15
+ async ({ sql, params, confirm_write }) => {
16
+ try {
17
+ if (!isConnected()) {
18
+ return {
19
+ content: [{
20
+ type: 'text' as const,
21
+ text: JSON.stringify({
22
+ error: 'No database connected. Use the connect tool first.',
23
+ }),
24
+ }],
25
+ isError: true,
26
+ };
27
+ }
28
+
29
+ const license = await getLicenseStatus();
30
+ const isWrite = isWriteQuery(sql);
31
+
32
+ // Free tier: read-only only
33
+ if (license.tier === 'free') {
34
+ const result = executeReadOnlyQuery(sql, params ?? []);
35
+ return {
36
+ content: [{
37
+ type: 'text' as const,
38
+ text: JSON.stringify({
39
+ rows: result.rows,
40
+ columns: result.columns,
41
+ row_count: result.rowCount,
42
+ execution_time_ms: result.executionTimeMs,
43
+ }, null, 2),
44
+ }],
45
+ };
46
+ }
47
+
48
+ // Pro tier: write operations require confirmation
49
+ if (isWrite && !confirm_write) {
50
+ return {
51
+ content: [{
52
+ type: 'text' as const,
53
+ text: JSON.stringify({
54
+ warning: 'This is a write operation. Set confirm_write: true to execute.',
55
+ sql: sql,
56
+ operation_type: sql.trim().split(/\s+/)[0].toUpperCase(),
57
+ }, null, 2),
58
+ }],
59
+ };
60
+ }
61
+
62
+ const result = executeQuery(sql, params ?? []);
63
+
64
+ return {
65
+ content: [{
66
+ type: 'text' as const,
67
+ text: JSON.stringify({
68
+ rows: result.rows,
69
+ columns: result.columns,
70
+ row_count: result.rowCount,
71
+ execution_time_ms: result.executionTimeMs,
72
+ ...(isWrite ? { write_operation: true } : {}),
73
+ }, null, 2),
74
+ }],
75
+ };
76
+ } catch (err) {
77
+ return {
78
+ content: [{
79
+ type: 'text' as const,
80
+ text: JSON.stringify({
81
+ error: err instanceof Error ? err.message : String(err),
82
+ }),
83
+ }],
84
+ isError: true,
85
+ };
86
+ }
87
+ }
88
+ );
89
+ }