@aranshayan/mcp-database 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +136 -2
  3. package/dist/index.js +1213 -0
  4. package/package.json +63 -4
package/dist/index.js ADDED
@@ -0,0 +1,1213 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+
6
+ // src/adapters/mysql.ts
7
+ import mysql from "mysql2/promise";
8
+
9
+ // src/serialize.ts
10
+ var MAX_CELL_CHARS = 2e3;
11
+ function toJsonValue(value) {
12
+ if (value === null || value === void 0) return null;
13
+ switch (typeof value) {
14
+ case "bigint": {
15
+ const asNumber = Number(value);
16
+ return Number.isSafeInteger(asNumber) ? asNumber : value.toString();
17
+ }
18
+ case "string":
19
+ return value.length > MAX_CELL_CHARS ? `${value.slice(0, MAX_CELL_CHARS)}\u2026 [truncated, ${value.length} chars]` : value;
20
+ case "number":
21
+ return Number.isFinite(value) ? value : String(value);
22
+ case "boolean":
23
+ return value;
24
+ case "object":
25
+ break;
26
+ default:
27
+ return String(value);
28
+ }
29
+ if (value instanceof Date) {
30
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
31
+ }
32
+ if (value instanceof Uint8Array) {
33
+ const hex = Buffer.from(value.subarray(0, 32)).toString("hex");
34
+ return `<binary ${value.byteLength} bytes${hex ? `: 0x${hex}${value.byteLength > 32 ? "\u2026" : ""}` : ""}>`;
35
+ }
36
+ if (Array.isArray(value)) return value.map(toJsonValue);
37
+ try {
38
+ const json = JSON.stringify(value, (_k, v) => typeof v === "bigint" ? v.toString() : v);
39
+ if (json === void 0) return String(value);
40
+ return json.length > MAX_CELL_CHARS ? `${json.slice(0, MAX_CELL_CHARS)}\u2026 [truncated]` : JSON.parse(json);
41
+ } catch {
42
+ return String(value);
43
+ }
44
+ }
45
+ function toJsonRow(row) {
46
+ return row.map(toJsonValue);
47
+ }
48
+ function redact(message, secrets) {
49
+ let out = message;
50
+ for (const secret of secrets) {
51
+ if (secret) out = out.split(secret).join("***");
52
+ }
53
+ out = out.replace(/([a-z][a-z0-9+.-]*:\/\/[^:\s/@]+:)[^@\s/]+@/gi, "$1***@");
54
+ return out;
55
+ }
56
+
57
+ // src/adapters/mysql.ts
58
+ var int = (n) => Math.max(0, Math.trunc(n));
59
+ var MysqlAdapter = class {
60
+ dialect = "mysql";
61
+ pool;
62
+ constructor(opts) {
63
+ this.pool = mysql.createPool({
64
+ uri: opts.url,
65
+ connectionLimit: opts.poolSize ?? 3,
66
+ multipleStatements: false,
67
+ connectTimeout: 1e4,
68
+ supportBigNumbers: true,
69
+ bigNumberStrings: false,
70
+ dateStrings: false
71
+ });
72
+ this.pool.on("connection", (conn) => {
73
+ conn.on("error", () => {
74
+ });
75
+ });
76
+ }
77
+ async ping() {
78
+ await this.pool.query("SELECT 1");
79
+ }
80
+ quoteIdent(name) {
81
+ return `\`${name.replaceAll("`", "``")}\``;
82
+ }
83
+ async readOnly(fn, timeoutMs) {
84
+ const conn = await this.pool.getConnection();
85
+ let broken = false;
86
+ try {
87
+ if (timeoutMs !== void 0) await applyTimeout(conn, timeoutMs);
88
+ await conn.query("SET SESSION TRANSACTION READ ONLY");
89
+ await conn.query("START TRANSACTION READ ONLY");
90
+ return await fn(conn);
91
+ } catch (err) {
92
+ broken = isConnectionError(err);
93
+ throw err;
94
+ } finally {
95
+ if (broken) conn.destroy();
96
+ else {
97
+ await conn.query("ROLLBACK").catch(() => {
98
+ });
99
+ conn.release();
100
+ }
101
+ }
102
+ }
103
+ async rows(sql, values = []) {
104
+ return this.readOnly(async (conn) => {
105
+ const [rows] = await conn.query(sql, values);
106
+ return rows;
107
+ });
108
+ }
109
+ async listSchemas() {
110
+ const rows = await this.rows(
111
+ "SELECT SCHEMA_NAME AS name FROM information_schema.SCHEMATA WHERE SCHEMA_NAME NOT IN ('mysql','sys','performance_schema','information_schema') ORDER BY 1"
112
+ );
113
+ return rows.map((r) => r.name);
114
+ }
115
+ async listTables(schema) {
116
+ const rows = await this.rows(
117
+ `SELECT TABLE_NAME AS name, TABLE_TYPE AS type, TABLE_ROWS AS est
118
+ FROM information_schema.TABLES
119
+ WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) ORDER BY TABLE_NAME`,
120
+ [schema ?? null]
121
+ );
122
+ return rows.map((r) => ({
123
+ name: r.name,
124
+ type: r.type === "BASE TABLE" ? "table" : r.type.toLowerCase().replace(" ", "_"),
125
+ estimatedRows: r.est === null || r.est === void 0 ? null : Number(r.est)
126
+ }));
127
+ }
128
+ async describeTable(table, schema) {
129
+ const sch = schema ?? null;
130
+ const columns = await this.rows(
131
+ `SELECT COLUMN_NAME AS name, COLUMN_TYPE AS type, IS_NULLABLE AS nullable, COLUMN_DEFAULT AS dflt,
132
+ COLUMN_KEY AS \`key\`, COLUMN_COMMENT AS comment
133
+ FROM information_schema.COLUMNS
134
+ WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION`,
135
+ [sch, table]
136
+ );
137
+ if (columns.length === 0) throw new Error(`Table or view "${schema ?? "current database"}.${table}" not found.`);
138
+ const stats = await this.rows(
139
+ `SELECT INDEX_NAME AS name, NON_UNIQUE AS non_unique, COALESCE(COLUMN_NAME, EXPRESSION) AS col, SEQ_IN_INDEX AS seq
140
+ FROM information_schema.STATISTICS
141
+ WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) AND TABLE_NAME = ? ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
142
+ [sch, table]
143
+ ).catch(
144
+ async () => (
145
+ // MariaDB has no EXPRESSION column.
146
+ this.rows(
147
+ `SELECT INDEX_NAME AS name, NON_UNIQUE AS non_unique, COLUMN_NAME AS col, SEQ_IN_INDEX AS seq
148
+ FROM information_schema.STATISTICS
149
+ WHERE TABLE_SCHEMA = COALESCE(?, DATABASE()) AND TABLE_NAME = ? ORDER BY INDEX_NAME, SEQ_IN_INDEX`,
150
+ [sch, table]
151
+ )
152
+ )
153
+ );
154
+ const byIndex = /* @__PURE__ */ new Map();
155
+ for (const s of stats) {
156
+ const entry = byIndex.get(s.name) ?? { unique: Number(s.non_unique) === 0, cols: [] };
157
+ entry.cols.push(s.col ?? "<expression>");
158
+ byIndex.set(s.name, entry);
159
+ }
160
+ const fkRows = await this.rows(
161
+ `SELECT k.CONSTRAINT_NAME AS name, k.COLUMN_NAME AS col, k.REFERENCED_TABLE_SCHEMA AS ref_schema,
162
+ k.REFERENCED_TABLE_NAME AS ref_table, k.REFERENCED_COLUMN_NAME AS ref_col,
163
+ r.UPDATE_RULE AS on_update, r.DELETE_RULE AS on_delete
164
+ FROM information_schema.KEY_COLUMN_USAGE k
165
+ JOIN information_schema.REFERENTIAL_CONSTRAINTS r
166
+ ON r.CONSTRAINT_SCHEMA = k.CONSTRAINT_SCHEMA AND r.CONSTRAINT_NAME = k.CONSTRAINT_NAME
167
+ WHERE k.TABLE_SCHEMA = COALESCE(?, DATABASE()) AND k.TABLE_NAME = ? AND k.REFERENCED_TABLE_NAME IS NOT NULL
168
+ ORDER BY k.CONSTRAINT_NAME, k.ORDINAL_POSITION`,
169
+ [sch, table]
170
+ );
171
+ const fkByName = /* @__PURE__ */ new Map();
172
+ for (const row of fkRows) fkByName.set(row.name, [...fkByName.get(row.name) ?? [], row]);
173
+ const foreignKeys = [...fkByName.entries()].map(([name, group]) => {
174
+ const first = group[0];
175
+ const actions = [
176
+ first.on_update !== "NO ACTION" && first.on_update !== "RESTRICT" ? `ON UPDATE ${first.on_update}` : "",
177
+ first.on_delete !== "NO ACTION" && first.on_delete !== "RESTRICT" ? `ON DELETE ${first.on_delete}` : ""
178
+ ].filter(Boolean).join(" ");
179
+ return `${name}: FOREIGN KEY (${group.map((g) => g.col).join(", ")}) REFERENCES ${first.ref_schema}.${first.ref_table} (${group.map((g) => g.ref_col).join(", ")})${actions ? ` ${actions}` : ""}`;
180
+ });
181
+ return {
182
+ schema: schema ?? null,
183
+ table,
184
+ columns: columns.map((c) => ({
185
+ name: c.name,
186
+ type: c.type,
187
+ nullable: c.nullable === "YES",
188
+ default: c.dflt,
189
+ primaryKey: c.key === "PRI",
190
+ comment: c.comment || null
191
+ })),
192
+ indexes: [...byIndex.entries()].map(([name, v]) => ({
193
+ name,
194
+ unique: v.unique,
195
+ primary: name === "PRIMARY",
196
+ columns: v.cols
197
+ })),
198
+ foreignKeys
199
+ };
200
+ }
201
+ async query(sql, params, limits) {
202
+ const started = performance.now();
203
+ return this.readOnly(async (conn) => {
204
+ const [result, fields] = await conn.query({ sql, values: params, rowsAsArray: true });
205
+ const all = Array.isArray(result) ? result : [];
206
+ const truncated = all.length > limits.maxRows;
207
+ const columns = Array.isArray(fields) ? fields.map((f) => f.name) : [];
208
+ return {
209
+ columns,
210
+ rows: (truncated ? all.slice(0, limits.maxRows) : all).map(toJsonRow),
211
+ truncated,
212
+ durationMs: Math.round(performance.now() - started)
213
+ };
214
+ }, limits.timeoutMs);
215
+ }
216
+ async execute(sql, params, limits) {
217
+ const started = performance.now();
218
+ const conn = await this.pool.getConnection();
219
+ let broken = false;
220
+ try {
221
+ await applyTimeout(conn, limits.timeoutMs);
222
+ await conn.query("SET SESSION TRANSACTION READ WRITE");
223
+ await conn.query("START TRANSACTION");
224
+ const [result] = await conn.query({ sql, values: params });
225
+ await conn.query("COMMIT");
226
+ const header = result;
227
+ return {
228
+ affectedRows: header.affectedRows ?? null,
229
+ lastInsertId: header.insertId ? header.insertId : null,
230
+ durationMs: Math.round(performance.now() - started)
231
+ };
232
+ } catch (err) {
233
+ broken = isConnectionError(err);
234
+ if (!broken) await conn.query("ROLLBACK").catch(() => {
235
+ });
236
+ throw err;
237
+ } finally {
238
+ if (broken) conn.destroy();
239
+ else conn.release();
240
+ }
241
+ }
242
+ async close() {
243
+ await this.pool.end();
244
+ }
245
+ };
246
+ async function applyTimeout(conn, timeoutMs) {
247
+ try {
248
+ await conn.query(`SET SESSION MAX_EXECUTION_TIME = ${int(timeoutMs)}`);
249
+ } catch {
250
+ try {
251
+ await conn.query(`SET SESSION max_statement_time = ${Math.max(1, Math.ceil(timeoutMs / 1e3))}`);
252
+ } catch {
253
+ }
254
+ }
255
+ }
256
+ function isConnectionError(err) {
257
+ const code = err?.code ?? "";
258
+ return /^(ECONN|EPIPE|ETIMEDOUT|PROTOCOL_|ER_SERVER_SHUTDOWN)/.test(code);
259
+ }
260
+
261
+ // src/adapters/postgres.ts
262
+ import pg from "pg";
263
+ import Cursor from "pg-cursor";
264
+ var int2 = (n) => Math.max(0, Math.trunc(n));
265
+ var PostgresAdapter = class {
266
+ dialect = "postgres";
267
+ pool;
268
+ constructor(opts) {
269
+ this.pool = new pg.Pool({
270
+ connectionString: opts.url,
271
+ max: opts.poolSize ?? 3,
272
+ application_name: "mcp-database",
273
+ connectionTimeoutMillis: 1e4,
274
+ idleTimeoutMillis: 3e4
275
+ });
276
+ this.pool.on("error", () => {
277
+ });
278
+ }
279
+ async ping() {
280
+ await this.pool.query("SELECT 1");
281
+ }
282
+ quoteIdent(name) {
283
+ return `"${name.replaceAll('"', '""')}"`;
284
+ }
285
+ async rows(text, values = []) {
286
+ const client = await this.pool.connect();
287
+ try {
288
+ await client.query("BEGIN READ ONLY");
289
+ const res = await client.query(text, values);
290
+ return res.rows;
291
+ } finally {
292
+ await client.query("ROLLBACK").catch(() => {
293
+ });
294
+ client.release();
295
+ }
296
+ }
297
+ async listSchemas() {
298
+ const rows = await this.rows(
299
+ `SELECT schema_name FROM information_schema.schemata
300
+ WHERE schema_name NOT IN ('pg_catalog', 'information_schema')
301
+ AND schema_name NOT LIKE 'pg\\_toast%' AND schema_name NOT LIKE 'pg\\_temp%'
302
+ ORDER BY schema_name`
303
+ );
304
+ return rows.map((r) => r.schema_name);
305
+ }
306
+ async listTables(schema) {
307
+ const rows = await this.rows(
308
+ `SELECT c.relname AS name,
309
+ CASE c.relkind WHEN 'r' THEN 'table' WHEN 'v' THEN 'view' WHEN 'm' THEN 'materialized_view'
310
+ WHEN 'p' THEN 'partitioned_table' WHEN 'f' THEN 'foreign_table' END AS type,
311
+ CASE WHEN c.reltuples >= 0 THEN c.reltuples::bigint::text END AS estimated_rows
312
+ FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
313
+ WHERE n.nspname = COALESCE($1::text, current_schema()) AND c.relkind IN ('r', 'v', 'm', 'p', 'f')
314
+ ORDER BY c.relname`,
315
+ [schema ?? null]
316
+ );
317
+ return rows.map((r) => ({
318
+ name: r.name,
319
+ type: r.type,
320
+ estimatedRows: r.estimated_rows === null ? null : Number(r.estimated_rows)
321
+ }));
322
+ }
323
+ async describeTable(table, schema) {
324
+ const sch = schema ?? null;
325
+ const columns = await this.rows(
326
+ `SELECT a.attname AS name,
327
+ format_type(a.atttypid, a.atttypmod) AS type,
328
+ NOT a.attnotnull AS nullable,
329
+ pg_get_expr(d.adbin, d.adrelid) AS "default",
330
+ col_description(a.attrelid, a.attnum) AS comment
331
+ FROM pg_attribute a
332
+ JOIN pg_class c ON c.oid = a.attrelid
333
+ JOIN pg_namespace n ON n.oid = c.relnamespace
334
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
335
+ WHERE n.nspname = COALESCE($1::text, current_schema()) AND c.relname = $2
336
+ AND a.attnum > 0 AND NOT a.attisdropped
337
+ ORDER BY a.attnum`,
338
+ [sch, table]
339
+ );
340
+ if (columns.length === 0) throw new Error(`Table or view "${schema ?? "current schema"}.${table}" not found.`);
341
+ const indexes = await this.rows(
342
+ `SELECT i.relname AS name, ix.indisunique AS "unique", ix.indisprimary AS "primary",
343
+ ARRAY(SELECT pg_get_indexdef(ix.indexrelid, k + 1, true)
344
+ FROM generate_subscripts(ix.indkey, 1) AS k ORDER BY k) AS columns
345
+ FROM pg_index ix
346
+ JOIN pg_class i ON i.oid = ix.indexrelid
347
+ JOIN pg_class t ON t.oid = ix.indrelid
348
+ JOIN pg_namespace n ON n.oid = t.relnamespace
349
+ WHERE n.nspname = COALESCE($1::text, current_schema()) AND t.relname = $2
350
+ ORDER BY i.relname`,
351
+ [sch, table]
352
+ );
353
+ const fks = await this.rows(
354
+ `SELECT con.conname AS name, pg_get_constraintdef(con.oid) AS definition
355
+ FROM pg_constraint con
356
+ JOIN pg_class c ON c.oid = con.conrelid
357
+ JOIN pg_namespace n ON n.oid = c.relnamespace
358
+ WHERE con.contype = 'f' AND n.nspname = COALESCE($1::text, current_schema()) AND c.relname = $2
359
+ ORDER BY con.conname`,
360
+ [sch, table]
361
+ );
362
+ const pkColumns = new Set(indexes.filter((i) => i.primary).flatMap((i) => i.columns));
363
+ return {
364
+ schema: schema ?? null,
365
+ table,
366
+ columns: columns.map((c) => ({
367
+ name: c.name,
368
+ type: c.type,
369
+ nullable: c.nullable,
370
+ default: c.default,
371
+ primaryKey: pkColumns.has(c.name),
372
+ comment: c.comment
373
+ })),
374
+ indexes,
375
+ foreignKeys: fks.map((f) => `${f.name}: ${f.definition}`)
376
+ };
377
+ }
378
+ async query(sql, params, limits) {
379
+ const started = performance.now();
380
+ const client = await this.pool.connect();
381
+ let broken = false;
382
+ try {
383
+ await client.query("BEGIN READ ONLY");
384
+ await client.query(`SET LOCAL statement_timeout = ${int2(limits.timeoutMs)}`);
385
+ const cursor = client.query(new Cursor(sql, params, { rowMode: "array" }));
386
+ try {
387
+ const batch = await cursor.read(limits.maxRows + 1);
388
+ const truncated = batch.length > limits.maxRows;
389
+ const rows = (truncated ? batch.slice(0, limits.maxRows) : batch).map(toJsonRow);
390
+ const fields = cursor._result?.fields ?? [];
391
+ return {
392
+ columns: fields.map((f) => f.name),
393
+ rows,
394
+ truncated,
395
+ durationMs: Math.round(performance.now() - started)
396
+ };
397
+ } finally {
398
+ await cursor.close().catch(() => {
399
+ });
400
+ }
401
+ } catch (err) {
402
+ broken = isConnectionError2(err);
403
+ throw err;
404
+ } finally {
405
+ if (!broken) await client.query("ROLLBACK").catch(() => {
406
+ });
407
+ client.release(broken ? true : void 0);
408
+ }
409
+ }
410
+ async execute(sql, params, limits) {
411
+ const started = performance.now();
412
+ const client = await this.pool.connect();
413
+ let broken = false;
414
+ try {
415
+ await client.query("BEGIN");
416
+ await client.query(`SET LOCAL statement_timeout = ${int2(limits.timeoutMs)}`);
417
+ const res = await client.query({ text: sql, values: params, rowMode: "array" });
418
+ await client.query("COMMIT");
419
+ const returning = res.fields && res.fields.length > 0 && Array.isArray(res.rows) ? {
420
+ columns: res.fields.map((f) => f.name),
421
+ rows: res.rows.slice(0, limits.maxRows).map(toJsonRow),
422
+ truncated: res.rows.length > limits.maxRows,
423
+ durationMs: 0
424
+ } : void 0;
425
+ return {
426
+ affectedRows: res.rowCount,
427
+ lastInsertId: null,
428
+ returning,
429
+ durationMs: Math.round(performance.now() - started)
430
+ };
431
+ } catch (err) {
432
+ broken = isConnectionError2(err);
433
+ if (!broken) await client.query("ROLLBACK").catch(() => {
434
+ });
435
+ throw err;
436
+ } finally {
437
+ client.release(broken ? true : void 0);
438
+ }
439
+ }
440
+ async close() {
441
+ await this.pool.end();
442
+ }
443
+ };
444
+ function isConnectionError2(err) {
445
+ const code = err?.code ?? "";
446
+ return /^(ECONN|EPIPE|ETIMEDOUT|57P0[1-3]|08)/.test(code);
447
+ }
448
+
449
+ // src/adapters/sqlite-runner.ts
450
+ import { spawn } from "node:child_process";
451
+ var CHILD_SOURCE = String.raw`
452
+ const { DatabaseSync } = require("node:sqlite");
453
+ let db = null;
454
+ process.on("message", (msg) => {
455
+ try {
456
+ if (msg.type === "open") {
457
+ db = new DatabaseSync(msg.path, { readOnly: true });
458
+ db.exec("PRAGMA query_only = ON");
459
+ process.send({ id: msg.id, ok: true });
460
+ return;
461
+ }
462
+ const stmt = db.prepare(msg.sql);
463
+ stmt.setReadBigInts(true);
464
+ stmt.setReturnArrays(true);
465
+ const columns = stmt.columns().map((c) => c.name);
466
+ const rows = [];
467
+ let truncated = false;
468
+ for (const row of stmt.iterate(...msg.params)) {
469
+ if (rows.length >= msg.maxRows) { truncated = true; break; }
470
+ rows.push(row);
471
+ }
472
+ process.send({ id: msg.id, ok: true, columns, rows, truncated });
473
+ } catch (err) {
474
+ process.send({ id: msg.id, ok: false, message: err instanceof Error ? err.message : String(err) });
475
+ }
476
+ });
477
+ process.on("disconnect", () => process.exit(0));
478
+ `;
479
+ var SqliteTimeoutError = class extends Error {
480
+ constructor(timeoutMs) {
481
+ super(
482
+ `Query stopped after the ${timeoutMs} ms timeout. Add a LIMIT, narrow the WHERE clause, or check recursive CTEs for a missing stop condition.`
483
+ );
484
+ this.name = "SqliteTimeoutError";
485
+ }
486
+ };
487
+ var SqliteQueryRunner = class {
488
+ constructor(path) {
489
+ this.path = path;
490
+ }
491
+ path;
492
+ child = null;
493
+ nextId = 1;
494
+ pending = /* @__PURE__ */ new Map();
495
+ /** Serialises queries: the child handles one statement at a time. */
496
+ queue = Promise.resolve();
497
+ closed = false;
498
+ /** Process id of the current query process, if one is running. Used by tests. */
499
+ get pid() {
500
+ return this.child?.pid;
501
+ }
502
+ run(sql, params, maxRows, timeoutMs) {
503
+ const task = this.queue.then(() => this.runNow(sql, params, maxRows, timeoutMs));
504
+ this.queue = task.catch(() => void 0);
505
+ return task;
506
+ }
507
+ async close() {
508
+ this.closed = true;
509
+ this.kill(new Error("Database connection closed."));
510
+ }
511
+ async runNow(sql, params, maxRows, timeoutMs) {
512
+ if (this.closed) throw new Error("Database connection closed.");
513
+ if (!this.child) await this.start();
514
+ const reply = await this.request({ type: "query", sql, params, maxRows }, timeoutMs);
515
+ return { columns: reply.columns ?? [], rows: reply.rows ?? [], truncated: reply.truncated ?? false };
516
+ }
517
+ async start() {
518
+ const child = spawn(process.execPath, ["--disable-warning=ExperimentalWarning", "-e", CHILD_SOURCE], {
519
+ // stdout belongs to the MCP protocol in the parent, so the child must never write to it.
520
+ stdio: ["ignore", "ignore", "inherit", "ipc"],
521
+ // Structured clone keeps BigInt and Uint8Array values intact.
522
+ serialization: "advanced"
523
+ });
524
+ this.child = child;
525
+ child.unref();
526
+ child.channel?.unref();
527
+ const killOnExit = () => {
528
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
529
+ };
530
+ process.once("exit", killOnExit);
531
+ child.once("exit", () => process.removeListener("exit", killOnExit));
532
+ child.on("message", (reply) => {
533
+ const waiter = this.pending.get(reply.id);
534
+ if (!waiter) return;
535
+ this.pending.delete(reply.id);
536
+ waiter.resolve(reply);
537
+ });
538
+ child.on("exit", () => {
539
+ if (this.child !== child) return;
540
+ this.child = null;
541
+ this.failPending(new Error("SQLite query process exited unexpectedly."));
542
+ });
543
+ child.on("error", (err) => {
544
+ if (this.child !== child) return;
545
+ this.child = null;
546
+ this.failPending(err);
547
+ });
548
+ try {
549
+ await this.request({ type: "open", path: this.path }, 1e4);
550
+ } catch (err) {
551
+ this.kill(null);
552
+ throw err;
553
+ }
554
+ }
555
+ request(message, timeoutMs) {
556
+ const child = this.child;
557
+ if (!child) return Promise.reject(new Error("SQLite query process is not running."));
558
+ const id = this.nextId++;
559
+ return new Promise((resolve, reject) => {
560
+ const timer = setTimeout(() => {
561
+ this.pending.delete(id);
562
+ this.kill(null);
563
+ reject(new SqliteTimeoutError(timeoutMs));
564
+ }, timeoutMs);
565
+ this.pending.set(id, {
566
+ resolve: (reply) => {
567
+ clearTimeout(timer);
568
+ if (reply.ok) resolve(reply);
569
+ else reject(new Error(reply.message ?? "SQLite query failed."));
570
+ },
571
+ reject: (err) => {
572
+ clearTimeout(timer);
573
+ reject(err);
574
+ }
575
+ });
576
+ child.send({ ...message, id });
577
+ });
578
+ }
579
+ kill(reason) {
580
+ const child = this.child;
581
+ this.child = null;
582
+ if (reason) this.failPending(reason);
583
+ if (child && child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
584
+ }
585
+ failPending(err) {
586
+ const waiters = [...this.pending.values()];
587
+ this.pending.clear();
588
+ for (const w of waiters) w.reject(err);
589
+ }
590
+ };
591
+
592
+ // src/adapters/sqlite.ts
593
+ function bind(params) {
594
+ return params.map((p) => typeof p === "boolean" ? p ? 1 : 0 : p);
595
+ }
596
+ var SqliteAdapter = class _SqliteAdapter {
597
+ constructor(opts, db, runner) {
598
+ this.opts = opts;
599
+ this.db = db;
600
+ this.runner = runner;
601
+ }
602
+ opts;
603
+ db;
604
+ runner;
605
+ dialect = "sqlite";
606
+ /** `node:sqlite` is loaded lazily so PostgreSQL / MySQL users never trigger its experimental-feature warning. */
607
+ static async open(opts) {
608
+ const { DatabaseSync: Database } = await import("node:sqlite");
609
+ const inMemory = opts.path === ":memory:";
610
+ const db = new Database(opts.path, { readOnly: !opts.writable && !inMemory });
611
+ if (!opts.writable) db.exec("PRAGMA query_only = ON");
612
+ return new _SqliteAdapter(opts, db, inMemory ? null : new SqliteQueryRunner(opts.path));
613
+ }
614
+ async ping() {
615
+ this.db.prepare("SELECT 1").get();
616
+ }
617
+ /** Process id of the query process, if one is running. Used by tests. */
618
+ get queryProcessId() {
619
+ return this.runner?.pid;
620
+ }
621
+ quoteIdent(name) {
622
+ return `"${name.replaceAll('"', '""')}"`;
623
+ }
624
+ async listSchemas() {
625
+ const rows = this.db.prepare("SELECT name FROM pragma_database_list ORDER BY seq").all();
626
+ return rows.map((r) => r.name);
627
+ }
628
+ async listTables(schema = "main") {
629
+ const rows = this.db.prepare(
630
+ `SELECT name, type FROM ${this.quoteIdent(schema)}.sqlite_master
631
+ WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'
632
+ ORDER BY name`
633
+ ).all();
634
+ return rows.map((r) => ({ name: r.name, type: r.type, estimatedRows: null }));
635
+ }
636
+ async describeTable(table, schema = "main") {
637
+ const cols = this.db.prepare('SELECT name, type, "notnull" AS not_null, dflt_value, pk FROM pragma_table_xinfo(?, ?) ORDER BY cid').all(table, schema);
638
+ if (cols.length === 0) throw new Error(`Table or view "${schema}.${table}" not found.`);
639
+ const indexList = this.db.prepare('SELECT name, "unique" AS uniq, origin FROM pragma_index_list(?, ?)').all(table, schema);
640
+ const indexes = indexList.map((ix) => {
641
+ const info = this.db.prepare("SELECT name FROM pragma_index_info(?, ?) ORDER BY seqno").all(ix.name, schema);
642
+ return {
643
+ name: ix.name,
644
+ unique: ix.uniq === 1,
645
+ primary: ix.origin === "pk",
646
+ columns: info.map((c) => c.name ?? "<expression>")
647
+ };
648
+ });
649
+ const fkRows = this.db.prepare('SELECT id, "table" AS ref_table, "from" AS from_col, "to" AS to_col, on_update, on_delete FROM pragma_foreign_key_list(?, ?) ORDER BY id, seq').all(table, schema);
650
+ const fkById = /* @__PURE__ */ new Map();
651
+ for (const row of fkRows) fkById.set(row.id, [...fkById.get(row.id) ?? [], row]);
652
+ const foreignKeys = [...fkById.values()].map((group) => {
653
+ const first = group[0];
654
+ const cols2 = group.map((g) => g.from_col).join(", ");
655
+ const refs = group.map((g) => g.to_col ?? "?").join(", ");
656
+ const actions = [
657
+ first.on_update !== "NO ACTION" ? `ON UPDATE ${first.on_update}` : "",
658
+ first.on_delete !== "NO ACTION" ? `ON DELETE ${first.on_delete}` : ""
659
+ ].filter(Boolean).join(" ");
660
+ return `FOREIGN KEY (${cols2}) REFERENCES ${first.ref_table} (${refs})${actions ? ` ${actions}` : ""}`;
661
+ });
662
+ return {
663
+ schema,
664
+ table,
665
+ columns: cols.map((c) => ({
666
+ name: c.name,
667
+ type: c.type || "ANY",
668
+ nullable: c.not_null === 0 && c.pk === 0,
669
+ default: c.dflt_value,
670
+ primaryKey: c.pk > 0
671
+ })),
672
+ indexes,
673
+ foreignKeys
674
+ };
675
+ }
676
+ async query(sql, params, limits) {
677
+ const started = performance.now();
678
+ if (this.runner) {
679
+ const result = await this.runner.run(sql, bind(params), limits.maxRows, limits.timeoutMs);
680
+ return {
681
+ columns: result.columns,
682
+ rows: result.rows.map((row) => toJsonRow(row)),
683
+ truncated: result.truncated,
684
+ durationMs: Math.round(performance.now() - started)
685
+ };
686
+ }
687
+ const stmt = this.db.prepare(sql);
688
+ stmt.setReadBigInts(true);
689
+ stmt.setReturnArrays(true);
690
+ const columns = stmt.columns().map((c) => c.name);
691
+ const rows = [];
692
+ let truncated = false;
693
+ for (const row of stmt.iterate(...bind(params))) {
694
+ if (rows.length >= limits.maxRows) {
695
+ truncated = true;
696
+ break;
697
+ }
698
+ rows.push(toJsonRow(row));
699
+ }
700
+ return { columns, rows, truncated, durationMs: Math.round(performance.now() - started) };
701
+ }
702
+ async execute(sql, params, _limits) {
703
+ if (!this.opts.writable) throw new Error("Database is opened read-only.");
704
+ const started = performance.now();
705
+ const result = this.db.prepare(sql).run(...bind(params));
706
+ return {
707
+ affectedRows: Number(result.changes),
708
+ lastInsertId: Number(result.lastInsertRowid) || null,
709
+ durationMs: Math.round(performance.now() - started)
710
+ };
711
+ }
712
+ async close() {
713
+ await this.runner?.close();
714
+ this.db.close();
715
+ }
716
+ };
717
+
718
+ // src/adapters/index.ts
719
+ async function createAdapter(config, poolSize) {
720
+ switch (config.dialect) {
721
+ case "postgres":
722
+ return new PostgresAdapter({ url: config.url, poolSize });
723
+ case "mysql":
724
+ return new MysqlAdapter({ url: config.url, poolSize });
725
+ case "sqlite":
726
+ return SqliteAdapter.open({ path: config.url, writable: config.allowWrites });
727
+ }
728
+ }
729
+
730
+ // src/config.ts
731
+ import { parseArgs } from "node:util";
732
+ var ConfigError = class extends Error {
733
+ constructor(message) {
734
+ super(message);
735
+ this.name = "ConfigError";
736
+ }
737
+ };
738
+ var HELP = `mcp-database \u2014 safe MCP server for PostgreSQL, MySQL and SQLite
739
+
740
+ Usage:
741
+ DATABASE_URL=postgres://user:pass@host/db npx @aranshayan/mcp-database
742
+ npx @aranshayan/mcp-database sqlite:///absolute/path/app.db
743
+
744
+ Connection (prefer the environment variable; command-line arguments are visible in process lists):
745
+ DATABASE_URL postgres://\u2026, postgresql://\u2026, mysql://\u2026, mariadb://\u2026, sqlite:///path, or a *.db/*.sqlite file
746
+ --url <url> same as DATABASE_URL
747
+
748
+ Safety:
749
+ --read-write enable the \`execute\` tool (INSERT/UPDATE/DELETE). Default: read-only
750
+ --allow-ddl with --read-write, also allow CREATE/ALTER/DROP/TRUNCATE
751
+ --max-rows <n> rows returned per query (default 200, max 5000)
752
+ --timeout-ms <n> statement timeout in milliseconds (default 15000)
753
+
754
+ Environment equivalents:
755
+ MCP_DATABASE_READ_WRITE=1 MCP_DATABASE_ALLOW_DDL=1 MCP_DATABASE_MAX_ROWS=\u2026 MCP_DATABASE_TIMEOUT_MS=\u2026
756
+
757
+ -h, --help show this help
758
+ -v, --version show version
759
+ `;
760
+ var truthy = (v) => v !== void 0 && /^(1|true|yes|on)$/i.test(v.trim());
761
+ function intOption(raw, fallback, min, max, label) {
762
+ if (raw === void 0 || raw === "") return fallback;
763
+ const n = Number(raw);
764
+ if (!Number.isInteger(n) || n < min || n > max) {
765
+ throw new ConfigError(`${label} must be an integer between ${min} and ${max} (got "${raw}").`);
766
+ }
767
+ return n;
768
+ }
769
+ function detectDialect(url) {
770
+ const lower = url.toLowerCase();
771
+ if (lower.startsWith("postgres://") || lower.startsWith("postgresql://")) return { dialect: "postgres", url };
772
+ if (lower.startsWith("mysql://") || lower.startsWith("mariadb://")) {
773
+ return { dialect: "mysql", url: lower.startsWith("mariadb://") ? `mysql://${url.slice("mariadb://".length)}` : url };
774
+ }
775
+ if (lower.startsWith("sqlite:")) {
776
+ let path = url.slice("sqlite:".length);
777
+ if (path.startsWith("//")) path = path.slice(2);
778
+ if (path === "") throw new ConfigError("sqlite: URL needs a path, e.g. sqlite:///absolute/path/app.db");
779
+ return { dialect: "sqlite", url: path };
780
+ }
781
+ if (/\.(db|sqlite|sqlite3)$/i.test(url) || url === ":memory:") return { dialect: "sqlite", url };
782
+ throw new ConfigError(
783
+ "Unsupported connection string. Use postgres://, mysql://, sqlite:///path or a path ending in .db/.sqlite/.sqlite3."
784
+ );
785
+ }
786
+ function parseConfig(argv, env) {
787
+ const { values, positionals } = parseArgs({
788
+ args: argv,
789
+ allowPositionals: true,
790
+ options: {
791
+ url: { type: "string" },
792
+ "read-write": { type: "boolean", default: false },
793
+ "allow-ddl": { type: "boolean", default: false },
794
+ "max-rows": { type: "string" },
795
+ "timeout-ms": { type: "string" },
796
+ help: { type: "boolean", short: "h", default: false },
797
+ version: { type: "boolean", short: "v", default: false }
798
+ }
799
+ });
800
+ if (values.help) return "help";
801
+ if (values.version) return "version";
802
+ const raw = values.url ?? positionals[0] ?? env.DATABASE_URL ?? env.MCP_DATABASE_URL;
803
+ if (!raw) {
804
+ throw new ConfigError("No database configured. Set DATABASE_URL or pass a connection string. Run with --help for details.");
805
+ }
806
+ const { dialect, url } = detectDialect(raw);
807
+ const allowWrites = values["read-write"] || truthy(env.MCP_DATABASE_READ_WRITE);
808
+ const allowDdl = values["allow-ddl"] || truthy(env.MCP_DATABASE_ALLOW_DDL);
809
+ if (allowDdl && !allowWrites) {
810
+ throw new ConfigError("--allow-ddl requires --read-write.");
811
+ }
812
+ return {
813
+ dialect,
814
+ url,
815
+ allowWrites,
816
+ allowDdl,
817
+ maxRows: intOption(values["max-rows"] ?? env.MCP_DATABASE_MAX_ROWS, 200, 1, 5e3, "--max-rows"),
818
+ timeoutMs: intOption(values["timeout-ms"] ?? env.MCP_DATABASE_TIMEOUT_MS, 15e3, 100, 6e5, "--timeout-ms")
819
+ };
820
+ }
821
+
822
+ // src/server.ts
823
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
824
+ import { z } from "zod";
825
+
826
+ // src/sql-guard.ts
827
+ var GuardError = class extends Error {
828
+ constructor(message) {
829
+ super(message);
830
+ this.name = "GuardError";
831
+ }
832
+ };
833
+ var IDENT_PLACEHOLDER = "_ident_";
834
+ var STRING_PLACEHOLDER = "''";
835
+ function sanitize(sql, dialect) {
836
+ let out = "";
837
+ let i = 0;
838
+ const n = sql.length;
839
+ while (i < n) {
840
+ const ch = sql[i];
841
+ const next = sql[i + 1];
842
+ if (ch === "-" && next === "-") {
843
+ const after = sql[i + 2];
844
+ const isComment = dialect !== "mysql" || after === void 0 || /[\s\x00-\x1f]/.test(after);
845
+ if (isComment) {
846
+ i += 2;
847
+ while (i < n && sql[i] !== "\n") i++;
848
+ out += " ";
849
+ continue;
850
+ }
851
+ }
852
+ if (ch === "#" && dialect === "mysql") {
853
+ while (i < n && sql[i] !== "\n") i++;
854
+ out += " ";
855
+ continue;
856
+ }
857
+ if (ch === "/" && next === "*") {
858
+ let depth = 1;
859
+ i += 2;
860
+ while (i < n && depth > 0) {
861
+ if (sql[i] === "/" && sql[i + 1] === "*" && dialect === "postgres") {
862
+ depth++;
863
+ i += 2;
864
+ } else if (sql[i] === "*" && sql[i + 1] === "/") {
865
+ depth--;
866
+ i += 2;
867
+ } else {
868
+ i++;
869
+ }
870
+ }
871
+ out += " ";
872
+ continue;
873
+ }
874
+ if (ch === "$" && dialect === "postgres") {
875
+ const m = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i));
876
+ if (m) {
877
+ const delim = m[0];
878
+ const end = sql.indexOf(delim, i + delim.length);
879
+ i = end === -1 ? n : end + delim.length;
880
+ out += STRING_PLACEHOLDER;
881
+ continue;
882
+ }
883
+ }
884
+ if (ch === "'" || ch === '"' && dialect === "mysql") {
885
+ const quote = ch;
886
+ const backslashEscapes = dialect === "mysql" || dialect === "postgres" && /[eE]$/.test(out) && !/[A-Za-z0-9_]$/.test(out.slice(0, -1));
887
+ i++;
888
+ while (i < n) {
889
+ const c = sql[i];
890
+ if (backslashEscapes && c === "\\") {
891
+ i += 2;
892
+ continue;
893
+ }
894
+ if (c === quote) {
895
+ if (sql[i + 1] === quote) {
896
+ i += 2;
897
+ continue;
898
+ }
899
+ i++;
900
+ break;
901
+ }
902
+ i++;
903
+ }
904
+ out += STRING_PLACEHOLDER;
905
+ continue;
906
+ }
907
+ if (ch === '"' || ch === "`" || ch === "[" && dialect === "sqlite") {
908
+ const close = ch === "[" ? "]" : ch;
909
+ i++;
910
+ while (i < n) {
911
+ if (sql[i] === close) {
912
+ if (close !== "]" && sql[i + 1] === close) {
913
+ i += 2;
914
+ continue;
915
+ }
916
+ i++;
917
+ break;
918
+ }
919
+ i++;
920
+ }
921
+ out += IDENT_PLACEHOLDER;
922
+ continue;
923
+ }
924
+ out += ch;
925
+ i++;
926
+ }
927
+ return out;
928
+ }
929
+ var READ_KEYWORDS = /* @__PURE__ */ new Set(["select", "with", "values", "table", "show", "describe", "desc", "explain", "pragma"]);
930
+ var WRITE_KEYWORDS = /* @__PURE__ */ new Set(["insert", "update", "delete", "replace", "merge", "upsert"]);
931
+ var DDL_KEYWORDS = /* @__PURE__ */ new Set([
932
+ "create",
933
+ "alter",
934
+ "drop",
935
+ "truncate",
936
+ "rename",
937
+ "comment",
938
+ "grant",
939
+ "revoke",
940
+ "reindex",
941
+ "vacuum",
942
+ "analyze",
943
+ "optimize",
944
+ "cluster",
945
+ "refresh"
946
+ ]);
947
+ var SAFE_PRAGMAS = /* @__PURE__ */ new Set([
948
+ "table_info",
949
+ "table_xinfo",
950
+ "table_list",
951
+ "index_list",
952
+ "index_info",
953
+ "index_xinfo",
954
+ "foreign_key_list",
955
+ "foreign_key_check",
956
+ "database_list",
957
+ "collation_list",
958
+ "compile_options",
959
+ "function_list",
960
+ "module_list",
961
+ "user_version",
962
+ "schema_version",
963
+ "freelist_count",
964
+ "page_count",
965
+ "page_size",
966
+ "encoding"
967
+ ]);
968
+ var EMBEDDED_WRITE = /\b(insert\s+into|delete\s+from|merge\s+into|replace\s+into)\b|\bupdate\b[\s\S]*?\bset\b/;
969
+ var DENYLIST = [
970
+ [/\binto\s+(outfile|dumpfile)\b/, "SELECT ... INTO OUTFILE/DUMPFILE writes files on the database server"],
971
+ [/\bload_file\s*\(/, "LOAD_FILE() reads files from the database server"],
972
+ [/\bload\s+data\b/, "LOAD DATA is not allowed"],
973
+ [/\b(pg_read_file|pg_read_binary_file|pg_ls_dir|pg_stat_file|lo_import|lo_export)\s*\(/, "server-side file access functions are not allowed"],
974
+ [/\b(pg_terminate_backend|pg_cancel_backend|pg_reload_conf|pg_rotate_logfile)\s*\(/, "backend control functions are not allowed"],
975
+ [/\bdblink(_exec|_connect)?\s*\(/, "dblink is not allowed"],
976
+ [/\bload_extension\s*\(/, "load_extension() is not allowed"],
977
+ [/\b(readfile|writefile)\s*\(/, "file I/O functions are not allowed"],
978
+ [/\b(sys_exec|sys_eval)\s*\(/, "command execution functions are not allowed"]
979
+ ];
980
+ function analyze(sql, dialect) {
981
+ const blocked = (reason, keyword2 = "") => ({ kind: "blocked", keyword: keyword2, reason, hasWhere: false });
982
+ if (sql.trim() === "") return blocked("Empty statement.");
983
+ if (dialect === "mysql" && sql.includes("/*!")) {
984
+ return blocked("MySQL executable comments (/*! ... */) are not allowed.");
985
+ }
986
+ const clean = sanitize(sql, dialect).toLowerCase();
987
+ const statements = clean.split(";").map((s) => s.trim()).filter((s) => s.length > 0);
988
+ if (statements.length === 0) return blocked("Empty statement.");
989
+ if (statements.length > 1) {
990
+ return blocked("Multiple statements are not allowed. Send one statement per call.");
991
+ }
992
+ const stmt = statements[0];
993
+ const keywordMatch = /^[a-z_]+/.exec(stmt);
994
+ const keyword = keywordMatch ? keywordMatch[0] : "";
995
+ if (!keyword) return blocked("Could not determine the statement type.");
996
+ for (const [pattern, reason] of DENYLIST) {
997
+ if (pattern.test(stmt)) return blocked(reason, keyword);
998
+ }
999
+ const hasWhere = /\bwhere\b/.test(stmt);
1000
+ if (READ_KEYWORDS.has(keyword)) {
1001
+ if (keyword === "pragma") {
1002
+ if (dialect !== "sqlite") return blocked("PRAGMA is only available on SQLite.", keyword);
1003
+ const m = /^pragma\s+(?:[a-z_]+\.)?([a-z_]+)\s*(\(|=)?/.exec(stmt);
1004
+ const name = m?.[1] ?? "";
1005
+ if (m?.[2] === "=" || !SAFE_PRAGMAS.has(name)) {
1006
+ return blocked(`PRAGMA ${name || "(unknown)"} is not allowed. Allowed: ${[...SAFE_PRAGMAS].join(", ")}.`, keyword);
1007
+ }
1008
+ return { kind: "read", keyword, hasWhere };
1009
+ }
1010
+ if ((keyword === "with" || keyword === "explain") && EMBEDDED_WRITE.test(stmt)) {
1011
+ return { kind: "write", keyword, hasWhere };
1012
+ }
1013
+ return { kind: "read", keyword, hasWhere };
1014
+ }
1015
+ if (WRITE_KEYWORDS.has(keyword)) return { kind: "write", keyword, hasWhere };
1016
+ if (DDL_KEYWORDS.has(keyword)) return { kind: "ddl", keyword, hasWhere };
1017
+ return blocked(`Statement type "${keyword.toUpperCase()}" is not allowed.`, keyword);
1018
+ }
1019
+ function assertReadOnly(sql, dialect) {
1020
+ const a = analyze(sql, dialect);
1021
+ if (a.kind === "blocked") throw new GuardError(a.reason ?? "Statement blocked.");
1022
+ if (a.kind !== "read") {
1023
+ throw new GuardError(
1024
+ `This tool only runs read-only statements (SELECT / WITH / SHOW / EXPLAIN / VALUES). Got ${a.keyword.toUpperCase()}. Use the \`execute\` tool for writes (requires the server to be started with --read-write).`
1025
+ );
1026
+ }
1027
+ }
1028
+ function assertWritable(sql, dialect, opts) {
1029
+ const a = analyze(sql, dialect);
1030
+ if (a.kind === "blocked") throw new GuardError(a.reason ?? "Statement blocked.");
1031
+ if (a.kind === "read") {
1032
+ throw new GuardError("This is a read-only statement. Use the `query` tool instead.");
1033
+ }
1034
+ if (a.kind === "ddl" && !opts.allowDdl) {
1035
+ throw new GuardError(
1036
+ `${a.keyword.toUpperCase()} is a schema-changing statement. Start the server with --allow-ddl to permit DDL.`
1037
+ );
1038
+ }
1039
+ if (a.kind === "write" && (a.keyword === "update" || a.keyword === "delete") && !a.hasWhere) {
1040
+ throw new GuardError(
1041
+ `${a.keyword.toUpperCase()} without a WHERE clause is refused. Add a WHERE clause (use WHERE 1=1 if you really mean every row).`
1042
+ );
1043
+ }
1044
+ return a.kind;
1045
+ }
1046
+
1047
+ // src/version.ts
1048
+ var VERSION = "0.1.0";
1049
+ var NAME = "mcp-database";
1050
+
1051
+ // src/server.ts
1052
+ var PLACEHOLDERS = { postgres: "$1, $2, \u2026", mysql: "?", sqlite: "?" };
1053
+ var paramsSchema = z.array(z.union([z.string(), z.number(), z.boolean(), z.null()])).optional().describe("Values for the statement's placeholders. Always pass user-supplied values here instead of inlining them into the SQL.");
1054
+ function createServer(adapter, opts) {
1055
+ const limits = { maxRows: opts.maxRows, timeoutMs: opts.timeoutMs };
1056
+ const placeholder = PLACEHOLDERS[adapter.dialect];
1057
+ const ok = (data) => ({ content: [{ type: "text", text: JSON.stringify(data) }] });
1058
+ const fail = (err) => {
1059
+ const message = err instanceof Error ? err.message : String(err);
1060
+ return { isError: true, content: [{ type: "text", text: redact(message, opts.secrets ?? []) }] };
1061
+ };
1062
+ const guarded = (fn) => async (args) => {
1063
+ try {
1064
+ return ok(await fn(args));
1065
+ } catch (err) {
1066
+ return fail(err);
1067
+ }
1068
+ };
1069
+ const mode = opts.allowWrites ? opts.allowDdl ? "read-write (DDL allowed)" : "read-write (DDL disabled)" : "read-only";
1070
+ const server = new McpServer(
1071
+ { name: NAME, version: VERSION },
1072
+ {
1073
+ instructions: `Connected to a ${adapter.dialect} database in ${mode} mode. Explore with list_schemas \u2192 list_tables \u2192 describe_table, then run SELECTs with the query tool. Use placeholders (${placeholder}) with the params argument. Results are capped at ${opts.maxRows} rows \u2014 add LIMIT / WHERE / aggregation instead of paging through large tables.`
1074
+ }
1075
+ );
1076
+ server.registerTool(
1077
+ "list_schemas",
1078
+ {
1079
+ title: "List schemas",
1080
+ description: "List the schemas (databases for MySQL, attached databases for SQLite) available on this connection.",
1081
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1082
+ },
1083
+ guarded(async () => ({ schemas: await adapter.listSchemas() }))
1084
+ );
1085
+ server.registerTool(
1086
+ "list_tables",
1087
+ {
1088
+ title: "List tables",
1089
+ description: "List tables and views in a schema with their type and (where the engine provides it) an estimated row count. Defaults to the current schema / database.",
1090
+ inputSchema: { schema: z.string().optional().describe("Schema name. Omit for the default.") },
1091
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1092
+ },
1093
+ guarded(async ({ schema }) => ({ tables: await adapter.listTables(schema) }))
1094
+ );
1095
+ server.registerTool(
1096
+ "describe_table",
1097
+ {
1098
+ title: "Describe table",
1099
+ description: "Show a table's columns (type, nullability, default, primary key), indexes and foreign keys.",
1100
+ inputSchema: {
1101
+ table: z.string().min(1).describe("Table or view name (not quoted)."),
1102
+ schema: z.string().optional().describe("Schema name. Omit for the default.")
1103
+ },
1104
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1105
+ },
1106
+ guarded(async ({ table, schema }) => adapter.describeTable(table, schema))
1107
+ );
1108
+ server.registerTool(
1109
+ "sample_rows",
1110
+ {
1111
+ title: "Sample rows",
1112
+ description: "Preview the first rows of a table or view. Quick way to see what the data looks like.",
1113
+ inputSchema: {
1114
+ table: z.string().min(1).describe("Table or view name (not quoted)."),
1115
+ schema: z.string().optional().describe("Schema name. Omit for the default."),
1116
+ limit: z.number().int().min(1).max(100).default(10).describe("Number of rows (1\u2013100).")
1117
+ },
1118
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1119
+ },
1120
+ guarded(async ({ table, schema, limit }) => {
1121
+ const target = schema ? `${adapter.quoteIdent(schema)}.${adapter.quoteIdent(table)}` : adapter.quoteIdent(table);
1122
+ const n = Math.min(Math.max(1, Math.trunc(limit ?? 10)), 100);
1123
+ return withCounts(await adapter.query(`SELECT * FROM ${target} LIMIT ${n}`, [], { ...limits, maxRows: n }));
1124
+ })
1125
+ );
1126
+ server.registerTool(
1127
+ "query",
1128
+ {
1129
+ title: "Run read-only query",
1130
+ description: `Run ONE read-only SQL statement (SELECT / WITH / VALUES / SHOW / EXPLAIN) against the ${adapter.dialect} database. Placeholders: ${placeholder}. At most ${opts.maxRows} rows are returned (truncated=true when there were more). Writes and multiple statements are rejected.`,
1131
+ inputSchema: {
1132
+ sql: z.string().min(1).describe("A single read-only SQL statement."),
1133
+ params: paramsSchema
1134
+ },
1135
+ annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }
1136
+ },
1137
+ guarded(async ({ sql, params }) => {
1138
+ assertReadOnly(sql, adapter.dialect);
1139
+ return withCounts(await adapter.query(sql, params ?? [], limits));
1140
+ })
1141
+ );
1142
+ if (opts.allowWrites) {
1143
+ server.registerTool(
1144
+ "execute",
1145
+ {
1146
+ title: "Run write statement",
1147
+ description: `Run ONE data-modifying statement (INSERT / UPDATE / DELETE${opts.allowDdl ? " / DDL" : ""}) inside a transaction that is committed on success. Placeholders: ${placeholder}. UPDATE and DELETE must have a WHERE clause. Confirm with the user before running anything destructive.`,
1148
+ inputSchema: {
1149
+ sql: z.string().min(1).describe("A single write statement."),
1150
+ params: paramsSchema
1151
+ },
1152
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false }
1153
+ },
1154
+ guarded(async ({ sql, params }) => {
1155
+ assertWritable(sql, adapter.dialect, { allowDdl: opts.allowDdl });
1156
+ const result = await adapter.execute(sql, params ?? [], limits);
1157
+ return result.returning ? { ...result, returning: withCounts(result.returning) } : result;
1158
+ })
1159
+ );
1160
+ }
1161
+ return server;
1162
+ }
1163
+ function withCounts(result) {
1164
+ return { ...result, rowCount: result.rows.length };
1165
+ }
1166
+
1167
+ // src/index.ts
1168
+ async function main() {
1169
+ const parsed = parseConfig(process.argv.slice(2), process.env);
1170
+ if (parsed === "help") {
1171
+ process.stdout.write(HELP);
1172
+ return;
1173
+ }
1174
+ if (parsed === "version") {
1175
+ process.stdout.write(`${NAME} ${VERSION}
1176
+ `);
1177
+ return;
1178
+ }
1179
+ const config = parsed;
1180
+ const adapter = await createAdapter(config);
1181
+ const secrets = [config.url];
1182
+ try {
1183
+ await adapter.ping();
1184
+ } catch (err) {
1185
+ await adapter.close().catch(() => {
1186
+ });
1187
+ throw new Error(`Could not connect to the ${config.dialect} database: ${redact(err instanceof Error ? err.message : String(err), secrets)}`);
1188
+ }
1189
+ const server = createServer(adapter, { ...config, secrets });
1190
+ const transport = new StdioServerTransport();
1191
+ let closing = false;
1192
+ const shutdown = async () => {
1193
+ if (closing) return;
1194
+ closing = true;
1195
+ await server.close().catch(() => {
1196
+ });
1197
+ await adapter.close().catch(() => {
1198
+ });
1199
+ process.exit(0);
1200
+ };
1201
+ process.on("SIGINT", shutdown);
1202
+ process.on("SIGTERM", shutdown);
1203
+ process.stdin.on("close", shutdown);
1204
+ await server.connect(transport);
1205
+ console.error(
1206
+ `${NAME} ${VERSION} ready: ${config.dialect}, ${config.allowWrites ? config.allowDdl ? "read-write+ddl" : "read-write" : "read-only"}, max ${config.maxRows} rows`
1207
+ );
1208
+ }
1209
+ main().catch((err) => {
1210
+ const message = err instanceof ConfigError ? err.message : err instanceof Error ? err.message : String(err);
1211
+ console.error(`${NAME}: ${message}`);
1212
+ process.exit(1);
1213
+ });