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.
- package/LICENSE +21 -0
- package/README.md +69 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +79 -0
- package/dist/index.js.map +1 -0
- package/dist/lib/ai-query.d.ts +7 -0
- package/dist/lib/ai-query.d.ts.map +1 -0
- package/dist/lib/ai-query.js +224 -0
- package/dist/lib/ai-query.js.map +1 -0
- package/dist/lib/config.d.ts +4 -0
- package/dist/lib/config.d.ts.map +1 -0
- package/dist/lib/config.js +30 -0
- package/dist/lib/config.js.map +1 -0
- package/dist/lib/connection.d.ts +14 -0
- package/dist/lib/connection.d.ts.map +1 -0
- package/dist/lib/connection.js +175 -0
- package/dist/lib/connection.js.map +1 -0
- package/dist/lib/license.d.ts +4 -0
- package/dist/lib/license.d.ts.map +1 -0
- package/dist/lib/license.js +94 -0
- package/dist/lib/license.js.map +1 -0
- package/dist/lib/query-optimizer.d.ts +3 -0
- package/dist/lib/query-optimizer.d.ts.map +1 -0
- package/dist/lib/query-optimizer.js +155 -0
- package/dist/lib/query-optimizer.js.map +1 -0
- package/dist/tools/connect.d.ts +3 -0
- package/dist/tools/connect.d.ts.map +1 -0
- package/dist/tools/connect.js +37 -0
- package/dist/tools/connect.js.map +1 -0
- package/dist/tools/describe-table.d.ts +3 -0
- package/dist/tools/describe-table.d.ts.map +1 -0
- package/dist/tools/describe-table.js +60 -0
- package/dist/tools/describe-table.js.map +1 -0
- package/dist/tools/export-data.d.ts +3 -0
- package/dist/tools/export-data.d.ts.map +1 -0
- package/dist/tools/export-data.js +68 -0
- package/dist/tools/export-data.js.map +1 -0
- package/dist/tools/generate-migration.d.ts +3 -0
- package/dist/tools/generate-migration.d.ts.map +1 -0
- package/dist/tools/generate-migration.js +36 -0
- package/dist/tools/generate-migration.js.map +1 -0
- package/dist/tools/list-tables.d.ts +3 -0
- package/dist/tools/list-tables.d.ts.map +1 -0
- package/dist/tools/list-tables.js +45 -0
- package/dist/tools/list-tables.js.map +1 -0
- package/dist/tools/natural-language-query.d.ts +3 -0
- package/dist/tools/natural-language-query.d.ts.map +1 -0
- package/dist/tools/natural-language-query.js +53 -0
- package/dist/tools/natural-language-query.js.map +1 -0
- package/dist/tools/optimize-query.d.ts +3 -0
- package/dist/tools/optimize-query.d.ts.map +1 -0
- package/dist/tools/optimize-query.js +51 -0
- package/dist/tools/optimize-query.js.map +1 -0
- package/dist/tools/query.d.ts +3 -0
- package/dist/tools/query.d.ts.map +1 -0
- package/dist/tools/query.js +79 -0
- package/dist/tools/query.js.map +1 -0
- package/dist/types.d.ts +86 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/evals/eval-query.ts +356 -0
- package/evals/run-evals.ts +36 -0
- package/evals/test.db +0 -0
- package/glama.json +4 -0
- package/package.json +47 -0
- package/smithery.yaml +18 -0
- package/src/index.ts +99 -0
- package/src/lib/ai-query.ts +274 -0
- package/src/lib/config.ts +33 -0
- package/src/lib/connection.ts +263 -0
- package/src/lib/license.ts +118 -0
- package/src/lib/query-optimizer.ts +191 -0
- package/src/tools/connect.ts +43 -0
- package/src/tools/describe-table.ts +67 -0
- package/src/tools/export-data.ts +81 -0
- package/src/tools/generate-migration.ts +43 -0
- package/src/tools/list-tables.ts +52 -0
- package/src/tools/natural-language-query.ts +61 -0
- package/src/tools/optimize-query.ts +59 -0
- package/src/tools/query.ts +89 -0
- package/src/types.ts +115 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { getConfig } from './config.js';
|
|
2
|
+
import { listTables, executeQuery } from './connection.js';
|
|
3
|
+
import type { NaturalLanguageQueryResult, TableInfo } from '../types.js';
|
|
4
|
+
|
|
5
|
+
// ── Schema Summary ──────────────────────────────────────────────────
|
|
6
|
+
|
|
7
|
+
function buildSchemaContext(filterTables?: string[]): string {
|
|
8
|
+
const tables = listTables();
|
|
9
|
+
const relevant = filterTables
|
|
10
|
+
? tables.filter(t => filterTables.includes(t.name))
|
|
11
|
+
: tables;
|
|
12
|
+
|
|
13
|
+
return relevant.map(t => formatTableSchema(t)).join('\n\n');
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function formatTableSchema(t: TableInfo): string {
|
|
17
|
+
const cols = t.columns.map(c => {
|
|
18
|
+
const parts = [` ${c.name} ${c.type}`];
|
|
19
|
+
if (c.primaryKey) parts.push('PRIMARY KEY');
|
|
20
|
+
if (!c.nullable) parts.push('NOT NULL');
|
|
21
|
+
if (c.defaultValue !== null) parts.push(`DEFAULT ${c.defaultValue}`);
|
|
22
|
+
return parts.join(' ');
|
|
23
|
+
}).join(',\n');
|
|
24
|
+
|
|
25
|
+
return `TABLE ${t.name} (${t.rowCount} rows):\n${cols}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// ── AI Providers ────────────────────────────────────────────────────
|
|
29
|
+
|
|
30
|
+
interface AiResponse {
|
|
31
|
+
sql: string;
|
|
32
|
+
explanation: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function callAnthropic(prompt: string, apiKey: string): Promise<AiResponse> {
|
|
36
|
+
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: {
|
|
39
|
+
'Content-Type': 'application/json',
|
|
40
|
+
'x-api-key': apiKey,
|
|
41
|
+
'anthropic-version': '2023-06-01',
|
|
42
|
+
},
|
|
43
|
+
body: JSON.stringify({
|
|
44
|
+
model: 'claude-sonnet-4-20250514',
|
|
45
|
+
max_tokens: 1024,
|
|
46
|
+
messages: [{
|
|
47
|
+
role: 'user',
|
|
48
|
+
content: prompt,
|
|
49
|
+
}],
|
|
50
|
+
}),
|
|
51
|
+
signal: AbortSignal.timeout(30000),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
if (!response.ok) {
|
|
55
|
+
const body = await response.text();
|
|
56
|
+
throw new Error(`Anthropic API error (${response.status}): ${body}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const data = await response.json() as {
|
|
60
|
+
content: Array<{ type: string; text: string }>;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const text = data.content.find(c => c.type === 'text')?.text ?? '';
|
|
64
|
+
return parseAiResponse(text);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async function callOpenAI(prompt: string, apiKey: string): Promise<AiResponse> {
|
|
68
|
+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
69
|
+
method: 'POST',
|
|
70
|
+
headers: {
|
|
71
|
+
'Content-Type': 'application/json',
|
|
72
|
+
'Authorization': `Bearer ${apiKey}`,
|
|
73
|
+
},
|
|
74
|
+
body: JSON.stringify({
|
|
75
|
+
model: 'gpt-4o-mini',
|
|
76
|
+
messages: [{
|
|
77
|
+
role: 'user',
|
|
78
|
+
content: prompt,
|
|
79
|
+
}],
|
|
80
|
+
max_tokens: 1024,
|
|
81
|
+
}),
|
|
82
|
+
signal: AbortSignal.timeout(30000),
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
if (!response.ok) {
|
|
86
|
+
const body = await response.text();
|
|
87
|
+
throw new Error(`OpenAI API error (${response.status}): ${body}`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const data = await response.json() as {
|
|
91
|
+
choices: Array<{ message: { content: string } }>;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const text = data.choices[0]?.message?.content ?? '';
|
|
95
|
+
return parseAiResponse(text);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function parseAiResponse(text: string): AiResponse {
|
|
99
|
+
// Extract SQL from code blocks or raw text
|
|
100
|
+
const sqlMatch = text.match(/```sql\n([\s\S]*?)```/);
|
|
101
|
+
const sql = sqlMatch ? sqlMatch[1].trim() : extractSqlFromText(text);
|
|
102
|
+
|
|
103
|
+
// Extract explanation (everything that is not the SQL block)
|
|
104
|
+
const explanation = text
|
|
105
|
+
.replace(/```sql[\s\S]*?```/, '')
|
|
106
|
+
.replace(/^SQL:\s*/mi, '')
|
|
107
|
+
.trim()
|
|
108
|
+
|| 'Query generated from natural language.';
|
|
109
|
+
|
|
110
|
+
if (!sql) {
|
|
111
|
+
throw new Error('AI did not produce a valid SQL query. Try rephrasing your question.');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return { sql, explanation };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function extractSqlFromText(text: string): string {
|
|
118
|
+
// Try to find a SELECT/WITH statement in the text
|
|
119
|
+
const match = text.match(/((?:WITH|SELECT)\b[\s\S]*?;)/i);
|
|
120
|
+
return match ? match[1].trim() : '';
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── Public API ──────────────────────────────────────────────────────
|
|
124
|
+
|
|
125
|
+
export async function naturalLanguageToSql(
|
|
126
|
+
question: string,
|
|
127
|
+
filterTables?: string[]
|
|
128
|
+
): Promise<NaturalLanguageQueryResult> {
|
|
129
|
+
const config = getConfig();
|
|
130
|
+
|
|
131
|
+
if (!config.anthropicApiKey && !config.openaiApiKey) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
'Natural language queries require an AI API key. ' +
|
|
134
|
+
'Set ANTHROPIC_API_KEY or OPENAI_API_KEY in your environment.'
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const schema = buildSchemaContext(filterTables);
|
|
139
|
+
|
|
140
|
+
const prompt = `You are a SQL query generator. Given the database schema below and a natural language question, generate the correct SQL query.
|
|
141
|
+
|
|
142
|
+
DATABASE SCHEMA:
|
|
143
|
+
${schema}
|
|
144
|
+
|
|
145
|
+
QUESTION: ${question}
|
|
146
|
+
|
|
147
|
+
Respond with:
|
|
148
|
+
1. The SQL query in a \`\`\`sql code block
|
|
149
|
+
2. A brief explanation of what the query does
|
|
150
|
+
|
|
151
|
+
Important:
|
|
152
|
+
- Use only tables and columns that exist in the schema above
|
|
153
|
+
- Write SQLite-compatible SQL
|
|
154
|
+
- Use appropriate JOINs when data spans multiple tables
|
|
155
|
+
- Always include a LIMIT if the result could be large (default LIMIT 100)`;
|
|
156
|
+
|
|
157
|
+
let aiResult: AiResponse;
|
|
158
|
+
|
|
159
|
+
if (config.anthropicApiKey) {
|
|
160
|
+
aiResult = await callAnthropic(prompt, config.anthropicApiKey);
|
|
161
|
+
} else {
|
|
162
|
+
aiResult = await callOpenAI(prompt, config.openaiApiKey!);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Execute the generated SQL
|
|
166
|
+
const results = executeQuery(aiResult.sql);
|
|
167
|
+
|
|
168
|
+
return {
|
|
169
|
+
sql: aiResult.sql,
|
|
170
|
+
explanation: aiResult.explanation,
|
|
171
|
+
results,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export async function generateMigrationSql(
|
|
176
|
+
description: string,
|
|
177
|
+
dialect: string = 'sqlite'
|
|
178
|
+
): Promise<{ upSql: string; downSql: string }> {
|
|
179
|
+
const config = getConfig();
|
|
180
|
+
|
|
181
|
+
if (!config.anthropicApiKey && !config.openaiApiKey) {
|
|
182
|
+
throw new Error(
|
|
183
|
+
'Migration generation requires an AI API key. ' +
|
|
184
|
+
'Set ANTHROPIC_API_KEY or OPENAI_API_KEY in your environment.'
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
let schemaContext = '';
|
|
189
|
+
try {
|
|
190
|
+
schemaContext = buildSchemaContext();
|
|
191
|
+
} catch {
|
|
192
|
+
// No connection -- generate migration without existing schema context
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const prompt = `You are a database migration generator. Generate SQL migration statements for the following change.
|
|
196
|
+
|
|
197
|
+
${schemaContext ? `EXISTING SCHEMA:\n${schemaContext}\n\n` : ''}DIALECT: ${dialect}
|
|
198
|
+
CHANGE DESCRIPTION: ${description}
|
|
199
|
+
|
|
200
|
+
Respond with two SQL code blocks:
|
|
201
|
+
|
|
202
|
+
1. UP migration (apply the change):
|
|
203
|
+
\`\`\`sql
|
|
204
|
+
-- up migration here
|
|
205
|
+
\`\`\`
|
|
206
|
+
|
|
207
|
+
2. DOWN migration (revert the change):
|
|
208
|
+
\`\`\`sql
|
|
209
|
+
-- down migration here
|
|
210
|
+
\`\`\`
|
|
211
|
+
|
|
212
|
+
Important:
|
|
213
|
+
- Use IF EXISTS / IF NOT EXISTS where appropriate
|
|
214
|
+
- Make migrations idempotent when possible
|
|
215
|
+
- Use correct syntax for the ${dialect} dialect`;
|
|
216
|
+
|
|
217
|
+
let text: string;
|
|
218
|
+
|
|
219
|
+
if (config.anthropicApiKey) {
|
|
220
|
+
const response = await fetch('https://api.anthropic.com/v1/messages', {
|
|
221
|
+
method: 'POST',
|
|
222
|
+
headers: {
|
|
223
|
+
'Content-Type': 'application/json',
|
|
224
|
+
'x-api-key': config.anthropicApiKey,
|
|
225
|
+
'anthropic-version': '2023-06-01',
|
|
226
|
+
},
|
|
227
|
+
body: JSON.stringify({
|
|
228
|
+
model: 'claude-sonnet-4-20250514',
|
|
229
|
+
max_tokens: 2048,
|
|
230
|
+
messages: [{ role: 'user', content: prompt }],
|
|
231
|
+
}),
|
|
232
|
+
signal: AbortSignal.timeout(30000),
|
|
233
|
+
});
|
|
234
|
+
if (!response.ok) throw new Error(`Anthropic API error: ${response.status}`);
|
|
235
|
+
const data = await response.json() as { content: Array<{ type: string; text: string }> };
|
|
236
|
+
text = data.content.find(c => c.type === 'text')?.text ?? '';
|
|
237
|
+
} else {
|
|
238
|
+
const response = await fetch('https://api.openai.com/v1/chat/completions', {
|
|
239
|
+
method: 'POST',
|
|
240
|
+
headers: {
|
|
241
|
+
'Content-Type': 'application/json',
|
|
242
|
+
'Authorization': `Bearer ${config.openaiApiKey}`,
|
|
243
|
+
},
|
|
244
|
+
body: JSON.stringify({
|
|
245
|
+
model: 'gpt-4o-mini',
|
|
246
|
+
messages: [{ role: 'user', content: prompt }],
|
|
247
|
+
max_tokens: 2048,
|
|
248
|
+
}),
|
|
249
|
+
signal: AbortSignal.timeout(30000),
|
|
250
|
+
});
|
|
251
|
+
if (!response.ok) throw new Error(`OpenAI API error: ${response.status}`);
|
|
252
|
+
const data = await response.json() as { choices: Array<{ message: { content: string } }> };
|
|
253
|
+
text = data.choices[0]?.message?.content ?? '';
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// Parse two SQL blocks from response
|
|
257
|
+
const sqlBlocks = [...text.matchAll(/```sql\n([\s\S]*?)```/g)].map(m => m[1].trim());
|
|
258
|
+
|
|
259
|
+
if (sqlBlocks.length < 2) {
|
|
260
|
+
// Try to split on common markers
|
|
261
|
+
const upMatch = text.match(/(?:UP|up|Up)[:\s]*\n*```sql\n([\s\S]*?)```/);
|
|
262
|
+
const downMatch = text.match(/(?:DOWN|down|Down)[:\s]*\n*```sql\n([\s\S]*?)```/);
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
upSql: upMatch?.[1]?.trim() || sqlBlocks[0] || '-- Could not generate up migration',
|
|
266
|
+
downSql: downMatch?.[1]?.trim() || sqlBlocks[1] || '-- Could not generate down migration',
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
upSql: sqlBlocks[0],
|
|
272
|
+
downSql: sqlBlocks[1],
|
|
273
|
+
};
|
|
274
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { homedir } from 'node:os';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { mkdirSync } from 'node:fs';
|
|
4
|
+
import type { TrussConfig } from '../types.js';
|
|
5
|
+
|
|
6
|
+
const DATA_DIR = join(homedir(), '.truss');
|
|
7
|
+
|
|
8
|
+
// Ensure data directory exists on import
|
|
9
|
+
try {
|
|
10
|
+
mkdirSync(DATA_DIR, { recursive: true });
|
|
11
|
+
} catch {
|
|
12
|
+
// ignore -- directory already exists
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function getConfig(): TrussConfig {
|
|
16
|
+
return {
|
|
17
|
+
licenseKey: process.env.TRUSS_LICENSE_KEY,
|
|
18
|
+
databaseUrl: process.env.DATABASE_URL,
|
|
19
|
+
dbHost: process.env.DB_HOST,
|
|
20
|
+
dbPort: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : undefined,
|
|
21
|
+
dbName: process.env.DB_NAME,
|
|
22
|
+
dbUser: process.env.DB_USER,
|
|
23
|
+
dbPassword: process.env.DB_PASSWORD,
|
|
24
|
+
anthropicApiKey: process.env.ANTHROPIC_API_KEY,
|
|
25
|
+
openaiApiKey: process.env.OPENAI_API_KEY,
|
|
26
|
+
trussApiBaseUrl: process.env.TRUSS_API_BASE_URL || 'https://api.truss.dev',
|
|
27
|
+
dataDir: DATA_DIR,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function getDataDir(): string {
|
|
32
|
+
return DATA_DIR;
|
|
33
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import Database from 'better-sqlite3';
|
|
4
|
+
import type {
|
|
5
|
+
DatabaseDialect,
|
|
6
|
+
ConnectionInfo,
|
|
7
|
+
TableInfo,
|
|
8
|
+
TableSchema,
|
|
9
|
+
ColumnInfo,
|
|
10
|
+
IndexInfo,
|
|
11
|
+
ForeignKeyInfo,
|
|
12
|
+
QueryResult,
|
|
13
|
+
} from '../types.js';
|
|
14
|
+
|
|
15
|
+
// ── Connection State ────────────────────────────────────────────────
|
|
16
|
+
|
|
17
|
+
let currentDb: Database.Database | null = null;
|
|
18
|
+
let currentDialect: DatabaseDialect = 'sqlite';
|
|
19
|
+
let currentPath: string | null = null;
|
|
20
|
+
|
|
21
|
+
// ── SQLite Connection ───────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
export function connectSqlite(dbPath: string): ConnectionInfo {
|
|
24
|
+
const absPath = resolve(dbPath);
|
|
25
|
+
|
|
26
|
+
if (!existsSync(absPath)) {
|
|
27
|
+
throw new Error(`Database file not found: ${absPath}`);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Close existing connection
|
|
31
|
+
if (currentDb) {
|
|
32
|
+
try { currentDb.close(); } catch { /* ignore */ }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
currentDb = new Database(absPath, { readonly: false });
|
|
36
|
+
currentDialect = 'sqlite';
|
|
37
|
+
currentPath = absPath;
|
|
38
|
+
|
|
39
|
+
// Enable WAL mode for better concurrency
|
|
40
|
+
currentDb.pragma('journal_mode = WAL');
|
|
41
|
+
|
|
42
|
+
const tables = listTableNames();
|
|
43
|
+
const version = currentDb.pragma('user_version') as Array<{ user_version: number }>;
|
|
44
|
+
const sqliteVersion = currentDb.prepare('SELECT sqlite_version() as v').get() as { v: string };
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
connected: true,
|
|
48
|
+
dialect: 'sqlite',
|
|
49
|
+
tables,
|
|
50
|
+
version: `SQLite ${sqliteVersion.v}`,
|
|
51
|
+
path: absPath,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ── Connection Accessors ────────────────────────────────────────────
|
|
56
|
+
|
|
57
|
+
export function getDb(): Database.Database {
|
|
58
|
+
if (!currentDb) {
|
|
59
|
+
throw new Error('No database connected. Use the connect tool first.');
|
|
60
|
+
}
|
|
61
|
+
return currentDb;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function getDialect(): DatabaseDialect {
|
|
65
|
+
return currentDialect;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function isConnected(): boolean {
|
|
69
|
+
return currentDb !== null;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function closeConnection(): void {
|
|
73
|
+
if (currentDb) {
|
|
74
|
+
try { currentDb.close(); } catch { /* ignore */ }
|
|
75
|
+
currentDb = null;
|
|
76
|
+
currentPath = null;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ── Table Operations ────────────────────────────────────────────────
|
|
81
|
+
|
|
82
|
+
function listTableNames(): string[] {
|
|
83
|
+
const db = getDb();
|
|
84
|
+
const rows = db.prepare(
|
|
85
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name"
|
|
86
|
+
).all() as Array<{ name: string }>;
|
|
87
|
+
return rows.map(r => r.name);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function listTables(): TableInfo[] {
|
|
91
|
+
const db = getDb();
|
|
92
|
+
const tableNames = listTableNames();
|
|
93
|
+
const results: TableInfo[] = [];
|
|
94
|
+
|
|
95
|
+
for (const tableName of tableNames) {
|
|
96
|
+
const columns = getColumnInfo(tableName);
|
|
97
|
+
const countRow = db.prepare(`SELECT COUNT(*) as cnt FROM "${tableName}"`).get() as { cnt: number };
|
|
98
|
+
|
|
99
|
+
results.push({
|
|
100
|
+
name: tableName,
|
|
101
|
+
columns,
|
|
102
|
+
rowCount: countRow.cnt,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return results;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function describeTable(tableName: string): TableSchema {
|
|
110
|
+
const db = getDb();
|
|
111
|
+
|
|
112
|
+
// Verify table exists
|
|
113
|
+
const exists = db.prepare(
|
|
114
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name = ?"
|
|
115
|
+
).get(tableName) as { name: string } | undefined;
|
|
116
|
+
|
|
117
|
+
if (!exists) {
|
|
118
|
+
throw new Error(`Table "${tableName}" not found.`);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const columns = getColumnInfo(tableName);
|
|
122
|
+
const indexes = getIndexInfo(tableName);
|
|
123
|
+
const foreignKeys = getForeignKeyInfo(tableName);
|
|
124
|
+
const countRow = db.prepare(`SELECT COUNT(*) as cnt FROM "${tableName}"`).get() as { cnt: number };
|
|
125
|
+
|
|
126
|
+
// Get CREATE TABLE statement
|
|
127
|
+
const createRow = db.prepare(
|
|
128
|
+
"SELECT sql FROM sqlite_master WHERE type='table' AND name = ?"
|
|
129
|
+
).get(tableName) as { sql: string };
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
name: tableName,
|
|
133
|
+
columns,
|
|
134
|
+
rowCount: countRow.cnt,
|
|
135
|
+
indexes,
|
|
136
|
+
foreignKeys,
|
|
137
|
+
createSql: createRow.sql,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function getColumnInfo(tableName: string): ColumnInfo[] {
|
|
142
|
+
const db = getDb();
|
|
143
|
+
const rows = db.pragma(`table_info("${tableName}")`) as Array<{
|
|
144
|
+
cid: number;
|
|
145
|
+
name: string;
|
|
146
|
+
type: string;
|
|
147
|
+
notnull: number;
|
|
148
|
+
dflt_value: string | null;
|
|
149
|
+
pk: number;
|
|
150
|
+
}>;
|
|
151
|
+
|
|
152
|
+
return rows.map(r => ({
|
|
153
|
+
name: r.name,
|
|
154
|
+
type: r.type || 'ANY',
|
|
155
|
+
nullable: r.notnull === 0,
|
|
156
|
+
defaultValue: r.dflt_value,
|
|
157
|
+
primaryKey: r.pk > 0,
|
|
158
|
+
}));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
function getIndexInfo(tableName: string): IndexInfo[] {
|
|
162
|
+
const db = getDb();
|
|
163
|
+
const indexes = db.pragma(`index_list("${tableName}")`) as Array<{
|
|
164
|
+
seq: number;
|
|
165
|
+
name: string;
|
|
166
|
+
unique: number;
|
|
167
|
+
origin: string;
|
|
168
|
+
partial: number;
|
|
169
|
+
}>;
|
|
170
|
+
|
|
171
|
+
return indexes.map(idx => {
|
|
172
|
+
const cols = db.pragma(`index_info("${idx.name}")`) as Array<{
|
|
173
|
+
seqno: number;
|
|
174
|
+
cid: number;
|
|
175
|
+
name: string;
|
|
176
|
+
}>;
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
name: idx.name,
|
|
180
|
+
columns: cols.map(c => c.name),
|
|
181
|
+
unique: idx.unique === 1,
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function getForeignKeyInfo(tableName: string): ForeignKeyInfo[] {
|
|
187
|
+
const db = getDb();
|
|
188
|
+
const fks = db.pragma(`foreign_key_list("${tableName}")`) as Array<{
|
|
189
|
+
id: number;
|
|
190
|
+
seq: number;
|
|
191
|
+
table: string;
|
|
192
|
+
from: string;
|
|
193
|
+
to: string;
|
|
194
|
+
on_update: string;
|
|
195
|
+
on_delete: string;
|
|
196
|
+
match: string;
|
|
197
|
+
}>;
|
|
198
|
+
|
|
199
|
+
return fks.map(fk => ({
|
|
200
|
+
column: fk.from,
|
|
201
|
+
referencedTable: fk.table,
|
|
202
|
+
referencedColumn: fk.to,
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ── Query Execution ─────────────────────────────────────────────────
|
|
207
|
+
|
|
208
|
+
const WRITE_PATTERN = /^\s*(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|TRUNCATE|REPLACE|MERGE)\b/i;
|
|
209
|
+
|
|
210
|
+
export function isWriteQuery(sql: string): boolean {
|
|
211
|
+
return WRITE_PATTERN.test(sql);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function executeQuery(sql: string, params: unknown[] = []): QueryResult {
|
|
215
|
+
const db = getDb();
|
|
216
|
+
const start = performance.now();
|
|
217
|
+
|
|
218
|
+
const stmt = db.prepare(sql);
|
|
219
|
+
let rows: Record<string, unknown>[];
|
|
220
|
+
|
|
221
|
+
if (isWriteQuery(sql)) {
|
|
222
|
+
const info = stmt.run(...params);
|
|
223
|
+
rows = [{ changes: info.changes, lastInsertRowid: Number(info.lastInsertRowid) }];
|
|
224
|
+
} else {
|
|
225
|
+
rows = stmt.all(...params) as Record<string, unknown>[];
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const executionTimeMs = Math.round((performance.now() - start) * 100) / 100;
|
|
229
|
+
|
|
230
|
+
// Extract column names
|
|
231
|
+
const columns = rows.length > 0 ? Object.keys(rows[0]) : [];
|
|
232
|
+
|
|
233
|
+
return {
|
|
234
|
+
rows,
|
|
235
|
+
columns,
|
|
236
|
+
rowCount: rows.length,
|
|
237
|
+
executionTimeMs,
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function executeReadOnlyQuery(sql: string, params: unknown[] = []): QueryResult {
|
|
242
|
+
if (isWriteQuery(sql)) {
|
|
243
|
+
throw new Error(
|
|
244
|
+
'Write operations (INSERT, UPDATE, DELETE, DROP, ALTER, CREATE, TRUNCATE) are not allowed in free tier. ' +
|
|
245
|
+
'Upgrade to Pro for full write access: https://truss.dev/pricing'
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
return executeQuery(sql, params);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ── EXPLAIN ─────────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
export function explainQuery(sql: string): string {
|
|
254
|
+
const db = getDb();
|
|
255
|
+
const rows = db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all() as Array<{
|
|
256
|
+
id: number;
|
|
257
|
+
parent: number;
|
|
258
|
+
notused: number;
|
|
259
|
+
detail: string;
|
|
260
|
+
}>;
|
|
261
|
+
|
|
262
|
+
return rows.map(r => `${' '.repeat(r.id * 2)}${r.detail}`).join('\n');
|
|
263
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { getConfig, getDataDir } from './config.js';
|
|
4
|
+
import type { LicenseStatus, LicenseTier } from '../types.js';
|
|
5
|
+
|
|
6
|
+
const CACHE_FILE = 'db-license-cache.json';
|
|
7
|
+
const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days
|
|
8
|
+
|
|
9
|
+
interface LicenseCache {
|
|
10
|
+
key: string;
|
|
11
|
+
valid: boolean;
|
|
12
|
+
tier: LicenseTier;
|
|
13
|
+
expiresAt: string | null;
|
|
14
|
+
cachedAt: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function getCachePath(): string {
|
|
18
|
+
return join(getDataDir(), CACHE_FILE);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function readCache(): LicenseCache | null {
|
|
22
|
+
try {
|
|
23
|
+
const raw = readFileSync(getCachePath(), 'utf-8');
|
|
24
|
+
const cache = JSON.parse(raw) as LicenseCache;
|
|
25
|
+
if (Date.now() - cache.cachedAt < CACHE_TTL_MS) {
|
|
26
|
+
return cache;
|
|
27
|
+
}
|
|
28
|
+
return null; // expired
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function writeCache(cache: LicenseCache): void {
|
|
35
|
+
try {
|
|
36
|
+
writeFileSync(getCachePath(), JSON.stringify(cache, null, 2));
|
|
37
|
+
} catch {
|
|
38
|
+
// non-fatal
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function isValidKeyFormat(key: string): boolean {
|
|
43
|
+
return /^truss_[0-9a-f]{32}$/.test(key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function validateRemote(key: string): Promise<{ valid: boolean; expiresAt: string | null }> {
|
|
47
|
+
const config = getConfig();
|
|
48
|
+
const url = `${config.trussApiBaseUrl}/validate/${key}`;
|
|
49
|
+
|
|
50
|
+
try {
|
|
51
|
+
const response = await fetch(url, {
|
|
52
|
+
method: 'GET',
|
|
53
|
+
headers: {
|
|
54
|
+
'Accept': 'application/json',
|
|
55
|
+
'User-Agent': 'truss-db-mcp/1.0.0',
|
|
56
|
+
},
|
|
57
|
+
signal: AbortSignal.timeout(5000),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
if (!response.ok) {
|
|
61
|
+
return { valid: false, expiresAt: null };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const body = await response.json() as { valid: boolean; expires_at?: string };
|
|
65
|
+
return {
|
|
66
|
+
valid: body.valid === true,
|
|
67
|
+
expiresAt: body.expires_at ?? null,
|
|
68
|
+
};
|
|
69
|
+
} catch {
|
|
70
|
+
// Network error -- fall back to format check + cache
|
|
71
|
+
return { valid: isValidKeyFormat(key), expiresAt: null };
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function getLicenseStatus(): Promise<LicenseStatus> {
|
|
76
|
+
const config = getConfig();
|
|
77
|
+
const key = config.licenseKey;
|
|
78
|
+
|
|
79
|
+
// No key -> free tier
|
|
80
|
+
if (!key) {
|
|
81
|
+
return { tier: 'free', valid: true, expiresAt: null };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Format check
|
|
85
|
+
if (!isValidKeyFormat(key)) {
|
|
86
|
+
return { tier: 'free', valid: false, expiresAt: null };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Check cache first
|
|
90
|
+
const cached = readCache();
|
|
91
|
+
if (cached && cached.key === key) {
|
|
92
|
+
return { tier: cached.tier, valid: cached.valid, expiresAt: cached.expiresAt };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Remote validation
|
|
96
|
+
const result = await validateRemote(key);
|
|
97
|
+
const tier: LicenseTier = result.valid ? 'pro' : 'free';
|
|
98
|
+
|
|
99
|
+
writeCache({
|
|
100
|
+
key,
|
|
101
|
+
valid: result.valid,
|
|
102
|
+
tier,
|
|
103
|
+
expiresAt: result.expiresAt,
|
|
104
|
+
cachedAt: Date.now(),
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return { tier, valid: result.valid, expiresAt: result.expiresAt };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function requirePro(): Promise<void> {
|
|
111
|
+
const status = await getLicenseStatus();
|
|
112
|
+
if (status.tier !== 'pro') {
|
|
113
|
+
throw new Error(
|
|
114
|
+
'This feature requires a TRUSS Pro license ($25/mo). ' +
|
|
115
|
+
'Get yours at https://truss.dev/pricing and set TRUSS_LICENSE_KEY.'
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
}
|