@50arms/mysql-mcp 0.0.0-stage → 0.1.2
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/dist/index.js +355 -0
- package/package.json +23 -4
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* MCP server exposing a READ-ONLY MySQL surface as first-class tools to
|
|
4
|
+
* Claude Code agents dispatched by danxbot (DX-1309 — let Slack agents run
|
|
5
|
+
* read-only SELECT queries against a prod MySQL DB).
|
|
6
|
+
*
|
|
7
|
+
* Three tools, all read-only, all against a single configured database:
|
|
8
|
+
*
|
|
9
|
+
* - `prod_db_query` — run ONE read-only statement (SELECT/WITH/SHOW/
|
|
10
|
+
* DESCRIBE/DESC/EXPLAIN). Defense-in-depth validation rejects writes +
|
|
11
|
+
* multi-statement payloads. Rows are returned as JSON, capped at 1000.
|
|
12
|
+
* - `prod_db_list_tables` — list table names in the configured database.
|
|
13
|
+
* - `prod_db_describe_table` — describe a single table's columns.
|
|
14
|
+
*
|
|
15
|
+
* Protocol: JSON-RPC 2.0 over stdio (newline-delimited JSON). Handles:
|
|
16
|
+
* `initialize`, `ping`, `tools/list`, `tools/call`. This is a hand-rolled
|
|
17
|
+
* MCP server (no SDK), mirroring `mcp-servers/playwright/src/index.ts`.
|
|
18
|
+
*
|
|
19
|
+
* Security model — this is DEFENSE-IN-DEPTH, not the primary control. The
|
|
20
|
+
* DB user is provisioned GRANT SELECT-only and the server connects to a
|
|
21
|
+
* read replica; the SELECT-only string check here is a second layer so a
|
|
22
|
+
* misconfigured grant can't turn an agent typo into a write. We deliberately
|
|
23
|
+
* do NOT build a full SQL parser (over-engineering for a defense-in-depth
|
|
24
|
+
* layer): a `;` or keyword inside a string literal can false-reject, which
|
|
25
|
+
* is the safe direction to err.
|
|
26
|
+
*
|
|
27
|
+
* Configuration (read once at the entrypoint, fail-loud on missing):
|
|
28
|
+
* - `MYSQL_HOST` — REQUIRED. DB host.
|
|
29
|
+
* - `MYSQL_USER` — REQUIRED. DB user (should be GRANT SELECT-only).
|
|
30
|
+
* - `MYSQL_PASSWORD` — REQUIRED. DB password.
|
|
31
|
+
* - `MYSQL_DATABASE` — REQUIRED. Database name (also the information_schema filter).
|
|
32
|
+
* - `MYSQL_PORT` — optional, defaults to 3306.
|
|
33
|
+
*/
|
|
34
|
+
import { realpathSync } from "node:fs";
|
|
35
|
+
import { createInterface } from "node:readline";
|
|
36
|
+
import { pathToFileURL } from "node:url";
|
|
37
|
+
/** Default MySQL port when MYSQL_PORT is unset. */
|
|
38
|
+
export const MYSQL_DEFAULT_PORT = 3306;
|
|
39
|
+
/** Max rows returned by prod_db_query before truncation. */
|
|
40
|
+
export const MAX_ROWS = 1000;
|
|
41
|
+
/** SQL statement prefixes accepted by prod_db_query (read-only). */
|
|
42
|
+
const READ_ONLY_PREFIXES = [
|
|
43
|
+
"SELECT",
|
|
44
|
+
"WITH",
|
|
45
|
+
"SHOW",
|
|
46
|
+
"DESCRIBE",
|
|
47
|
+
"DESC",
|
|
48
|
+
"EXPLAIN",
|
|
49
|
+
];
|
|
50
|
+
export const TOOLS = [
|
|
51
|
+
{
|
|
52
|
+
name: "prod_db_query",
|
|
53
|
+
description: "Run a single READ-ONLY SQL statement against the production database " +
|
|
54
|
+
"and return the rows as JSON. The statement must begin (after any " +
|
|
55
|
+
"leading comments/whitespace) with SELECT, WITH, SHOW, DESCRIBE, DESC, " +
|
|
56
|
+
"or EXPLAIN — any write (INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/" +
|
|
57
|
+
"TRUNCATE/etc.) is rejected, as is any payload containing a second " +
|
|
58
|
+
"statement. Results are capped at 1000 rows; truncation is noted in " +
|
|
59
|
+
"the response. Required: sql (string).",
|
|
60
|
+
inputSchema: {
|
|
61
|
+
type: "object",
|
|
62
|
+
properties: {
|
|
63
|
+
sql: {
|
|
64
|
+
type: "string",
|
|
65
|
+
description: "The read-only SQL statement to run.",
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
required: ["sql"],
|
|
69
|
+
additionalProperties: false,
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: "prod_db_list_tables",
|
|
74
|
+
description: "List the table names in the configured production database. Takes no " +
|
|
75
|
+
"arguments. Returns a JSON array of table names.",
|
|
76
|
+
inputSchema: {
|
|
77
|
+
type: "object",
|
|
78
|
+
properties: {},
|
|
79
|
+
required: [],
|
|
80
|
+
additionalProperties: false,
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: "prod_db_describe_table",
|
|
85
|
+
description: "Return the column definitions for a single table in the configured " +
|
|
86
|
+
"production database. Required: table (string matching ^[A-Za-z0-9_]+$). " +
|
|
87
|
+
"Returns a JSON array of column metadata rows.",
|
|
88
|
+
inputSchema: {
|
|
89
|
+
type: "object",
|
|
90
|
+
properties: {
|
|
91
|
+
table: {
|
|
92
|
+
type: "string",
|
|
93
|
+
description: "The table name (alphanumeric + underscore only).",
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
required: ["table"],
|
|
97
|
+
additionalProperties: false,
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
];
|
|
101
|
+
function requireObjectArgs(name, args) {
|
|
102
|
+
if (!args || typeof args !== "object" || Array.isArray(args)) {
|
|
103
|
+
throw new Error(`Invalid arguments: expected an object for ${name}`);
|
|
104
|
+
}
|
|
105
|
+
return args;
|
|
106
|
+
}
|
|
107
|
+
function requireNonBlankString(toolName, field, value) {
|
|
108
|
+
if (typeof value !== "string") {
|
|
109
|
+
throw new Error(`${toolName}: field "${field}" is required and must be a string (got ${typeof value})`);
|
|
110
|
+
}
|
|
111
|
+
if (value.trim() === "") {
|
|
112
|
+
throw new Error(`${toolName}: field "${field}" must be a non-empty string`);
|
|
113
|
+
}
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Strip leading whitespace and SQL comments from a statement, returning the
|
|
118
|
+
* remainder. Handles `-- line`, `# line`, and `/* block */` comments that
|
|
119
|
+
* appear BEFORE the first real token. This is only used to find the leading
|
|
120
|
+
* keyword + to detect a real second statement — it is not a tokenizer.
|
|
121
|
+
*/
|
|
122
|
+
export function stripLeadingComments(sql) {
|
|
123
|
+
let s = sql;
|
|
124
|
+
// Loop because comments + whitespace can interleave at the head.
|
|
125
|
+
for (;;) {
|
|
126
|
+
const before = s;
|
|
127
|
+
s = s.replace(/^\s+/, "");
|
|
128
|
+
// Line comment: -- ... or # ... up to end-of-line.
|
|
129
|
+
s = s.replace(/^(--|#)[^\n]*/, "");
|
|
130
|
+
// Block comment: /* ... */ (non-greedy; spans newlines).
|
|
131
|
+
s = s.replace(/^\/\*[\s\S]*?\*\//, "");
|
|
132
|
+
if (s === before)
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
return s;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Validate that `sql` is a single read-only statement. Throws a clear error
|
|
139
|
+
* otherwise. DEFENSE-IN-DEPTH — see the file header; not a full parser.
|
|
140
|
+
*/
|
|
141
|
+
export function assertReadOnlySingleStatement(sql) {
|
|
142
|
+
const stripped = stripLeadingComments(sql);
|
|
143
|
+
if (stripped.trim() === "") {
|
|
144
|
+
throw new Error("prod_db_query: SQL is empty after stripping comments/whitespace");
|
|
145
|
+
}
|
|
146
|
+
const upper = stripped.toUpperCase();
|
|
147
|
+
const ok = READ_ONLY_PREFIXES.some((prefix) => {
|
|
148
|
+
if (!upper.startsWith(prefix))
|
|
149
|
+
return false;
|
|
150
|
+
// The char right after the prefix must be a boundary (whitespace, "(",
|
|
151
|
+
// end-of-string) so "SELECTING" / "DROPLET" can't sneak past a prefix.
|
|
152
|
+
const after = upper.charAt(prefix.length);
|
|
153
|
+
return after === "" || /[\s(]/.test(after);
|
|
154
|
+
});
|
|
155
|
+
if (!ok) {
|
|
156
|
+
throw new Error(`prod_db_query: only read-only statements are allowed (must begin with one of ${READ_ONLY_PREFIXES.join(", ")}); got: ${stripped.slice(0, 40)}`);
|
|
157
|
+
}
|
|
158
|
+
// Multi-statement check. A trailing `;` (optionally followed by only
|
|
159
|
+
// whitespace/comments) is fine; a `;` followed by real content is a second
|
|
160
|
+
// statement and is rejected. A `;` inside a string literal can false-reject
|
|
161
|
+
// here — acceptable per the defense-in-depth contract (header).
|
|
162
|
+
const semi = stripped.indexOf(";");
|
|
163
|
+
if (semi !== -1) {
|
|
164
|
+
const tail = stripLeadingComments(stripped.slice(semi + 1));
|
|
165
|
+
if (tail.trim() !== "") {
|
|
166
|
+
throw new Error("prod_db_query: only a single statement is allowed (found content after ';')");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
async function callQuery(args, deps) {
|
|
171
|
+
const sql = requireNonBlankString("prod_db_query", "sql", args.sql);
|
|
172
|
+
assertReadOnlySingleStatement(sql);
|
|
173
|
+
const [rowsRaw] = await deps.pool.query(sql);
|
|
174
|
+
const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
|
|
175
|
+
const truncated = rows.length > MAX_ROWS;
|
|
176
|
+
const returned = truncated ? rows.slice(0, MAX_ROWS) : rows;
|
|
177
|
+
const payload = {
|
|
178
|
+
row_count: returned.length,
|
|
179
|
+
truncated,
|
|
180
|
+
...(truncated
|
|
181
|
+
? { note: `Result truncated to the first ${MAX_ROWS} rows.` }
|
|
182
|
+
: {}),
|
|
183
|
+
rows: returned,
|
|
184
|
+
};
|
|
185
|
+
return [{ type: "text", text: JSON.stringify(payload) }];
|
|
186
|
+
}
|
|
187
|
+
async function callListTables(deps) {
|
|
188
|
+
const [rowsRaw] = await deps.pool.query("SELECT table_name FROM information_schema.tables WHERE table_schema = ?", [deps.database]);
|
|
189
|
+
const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
|
|
190
|
+
return [{ type: "text", text: JSON.stringify({ rows }) }];
|
|
191
|
+
}
|
|
192
|
+
async function callDescribeTable(args, deps) {
|
|
193
|
+
const table = requireNonBlankString("prod_db_describe_table", "table", args.table);
|
|
194
|
+
if (!/^[A-Za-z0-9_]+$/.test(table)) {
|
|
195
|
+
throw new Error(`prod_db_describe_table: table must match ^[A-Za-z0-9_]+$ (got: ${table})`);
|
|
196
|
+
}
|
|
197
|
+
// `table` is regex-validated AND passed as a bound parameter — belt and
|
|
198
|
+
// suspenders against injection through the information_schema filter.
|
|
199
|
+
const [rowsRaw] = await deps.pool.query("SELECT column_name, data_type, is_nullable, column_key, column_default, extra " +
|
|
200
|
+
"FROM information_schema.columns WHERE table_schema = ? AND table_name = ? " +
|
|
201
|
+
"ORDER BY ordinal_position", [deps.database, table]);
|
|
202
|
+
const rows = Array.isArray(rowsRaw) ? rowsRaw : [];
|
|
203
|
+
return [{ type: "text", text: JSON.stringify({ rows }) }];
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* Exported so unit tests can exercise the validation + query contract
|
|
207
|
+
* directly. Production callers go through this same function via the
|
|
208
|
+
* JSON-RPC `tools/call` dispatcher in `main`.
|
|
209
|
+
*/
|
|
210
|
+
export async function callTool(name, args, deps) {
|
|
211
|
+
switch (name) {
|
|
212
|
+
case "prod_db_query":
|
|
213
|
+
return callQuery(requireObjectArgs("prod_db_query", args), deps);
|
|
214
|
+
case "prod_db_list_tables":
|
|
215
|
+
return callListTables(deps);
|
|
216
|
+
case "prod_db_describe_table":
|
|
217
|
+
return callDescribeTable(requireObjectArgs("prod_db_describe_table", args), deps);
|
|
218
|
+
default:
|
|
219
|
+
throw new Error(`Unknown tool: ${name}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function respond(id, result) {
|
|
223
|
+
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
|
|
224
|
+
}
|
|
225
|
+
function respondError(id, code, message) {
|
|
226
|
+
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }) + "\n");
|
|
227
|
+
}
|
|
228
|
+
export function main(deps) {
|
|
229
|
+
const rl = createInterface({ input: process.stdin, terminal: false });
|
|
230
|
+
rl.on("line", (line) => {
|
|
231
|
+
let msg;
|
|
232
|
+
try {
|
|
233
|
+
msg = JSON.parse(line);
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
return; // Ignore non-JSON lines.
|
|
237
|
+
}
|
|
238
|
+
const id = msg["id"];
|
|
239
|
+
const method = msg["method"];
|
|
240
|
+
const params = msg["params"];
|
|
241
|
+
// Notifications have no id — acknowledge and drop.
|
|
242
|
+
if (id === undefined)
|
|
243
|
+
return;
|
|
244
|
+
(async () => {
|
|
245
|
+
try {
|
|
246
|
+
if (method === "initialize") {
|
|
247
|
+
respond(id, {
|
|
248
|
+
protocolVersion: "2024-11-05",
|
|
249
|
+
capabilities: { tools: {} },
|
|
250
|
+
serverInfo: { name: "danxbot-mysql", version: "0.1.0" },
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
else if (method === "ping") {
|
|
254
|
+
respond(id, {});
|
|
255
|
+
}
|
|
256
|
+
else if (method === "tools/list") {
|
|
257
|
+
respond(id, { tools: TOOLS });
|
|
258
|
+
}
|
|
259
|
+
else if (method === "tools/call") {
|
|
260
|
+
const p = (params ?? {});
|
|
261
|
+
const content = await callTool(p.name, p.arguments, deps);
|
|
262
|
+
respond(id, { content });
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
respondError(id, -32601, `Method not found: ${method}`);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
catch (err) {
|
|
269
|
+
respondError(id, -32000, err instanceof Error ? err.message : String(err));
|
|
270
|
+
}
|
|
271
|
+
})();
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Parse + validate the MySQL connection config from an environment bag.
|
|
276
|
+
* THROWS a clear Error on any missing required var or a bad MYSQL_PORT —
|
|
277
|
+
* it NEVER calls `process.exit`, so it is unit-testable. The entrypoint
|
|
278
|
+
* block below is the only caller that translates a throw into stderr +
|
|
279
|
+
* `process.exit(1)`.
|
|
280
|
+
*/
|
|
281
|
+
export function resolveConfigFromEnv(env) {
|
|
282
|
+
const host = env.MYSQL_HOST;
|
|
283
|
+
const user = env.MYSQL_USER;
|
|
284
|
+
const password = env.MYSQL_PASSWORD;
|
|
285
|
+
const database = env.MYSQL_DATABASE;
|
|
286
|
+
const missing = [
|
|
287
|
+
["MYSQL_HOST", host],
|
|
288
|
+
["MYSQL_USER", user],
|
|
289
|
+
["MYSQL_PASSWORD", password],
|
|
290
|
+
["MYSQL_DATABASE", database],
|
|
291
|
+
]
|
|
292
|
+
.filter(([, v]) => !v)
|
|
293
|
+
.map(([k]) => k);
|
|
294
|
+
if (missing.length > 0) {
|
|
295
|
+
throw new Error(`Missing required environment variable(s): ${missing.join(", ")}`);
|
|
296
|
+
}
|
|
297
|
+
const portRaw = env.MYSQL_PORT;
|
|
298
|
+
const port = portRaw ? parseInt(portRaw, 10) : MYSQL_DEFAULT_PORT;
|
|
299
|
+
if (!Number.isFinite(port) || port <= 0) {
|
|
300
|
+
throw new Error(`MYSQL_PORT must be a positive integer when set (got "${portRaw}")`);
|
|
301
|
+
}
|
|
302
|
+
// The `missing` guard above proved these four are present + non-empty.
|
|
303
|
+
return {
|
|
304
|
+
host: host,
|
|
305
|
+
port,
|
|
306
|
+
user: user,
|
|
307
|
+
password: password,
|
|
308
|
+
database: database,
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Decide whether this module is the process entrypoint (direct invocation),
|
|
313
|
+
* symlink-robustly. Mirrors `mcp-servers/playwright/src/index.ts` —
|
|
314
|
+
* the workspace's `mcp-servers/` is a SYMLINK into the danxbot repo, so
|
|
315
|
+
* `process.argv[1]` carries the symlink path while tsx sets `import.meta.url`
|
|
316
|
+
* to the realpath of the target. realpath-resolving argv1 first makes both
|
|
317
|
+
* sides canonical so the guard holds through the symlink.
|
|
318
|
+
*/
|
|
319
|
+
export function isModuleEntrypoint(importMetaUrl, argv1) {
|
|
320
|
+
if (typeof argv1 !== "string" || argv1 === "")
|
|
321
|
+
return false;
|
|
322
|
+
let resolved;
|
|
323
|
+
try {
|
|
324
|
+
resolved = realpathSync(argv1);
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
resolved = argv1;
|
|
328
|
+
}
|
|
329
|
+
return importMetaUrl === pathToFileURL(resolved).href;
|
|
330
|
+
}
|
|
331
|
+
if (isModuleEntrypoint(import.meta.url, process.argv[1])) {
|
|
332
|
+
let config;
|
|
333
|
+
try {
|
|
334
|
+
config = resolveConfigFromEnv(process.env);
|
|
335
|
+
}
|
|
336
|
+
catch (err) {
|
|
337
|
+
process.stderr.write(`${err instanceof Error ? err.message : String(err)}\n`);
|
|
338
|
+
process.exit(1);
|
|
339
|
+
}
|
|
340
|
+
// Dynamic import keeps mysql2 off the test import path — tests inject a mock
|
|
341
|
+
// pool and never load the driver. The driver only loads at real entrypoint.
|
|
342
|
+
const { createPool } = await import("mysql2/promise");
|
|
343
|
+
const pool = createPool({
|
|
344
|
+
host: config.host,
|
|
345
|
+
port: config.port,
|
|
346
|
+
user: config.user,
|
|
347
|
+
password: config.password,
|
|
348
|
+
database: config.database,
|
|
349
|
+
connectionLimit: 4,
|
|
350
|
+
// Defense-in-depth: never permit multiple statements at the driver level.
|
|
351
|
+
multipleStatements: false,
|
|
352
|
+
waitForConnections: true,
|
|
353
|
+
});
|
|
354
|
+
main({ pool: pool, database: config.database });
|
|
355
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@50arms/mysql-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "MCP server exposing read-only prod_db_query, prod_db_list_tables, and prod_db_describe_table tools to Claude Code agents dispatched by danxbot.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"bin": {
|
|
8
|
+
"mysql-mcp": "dist/index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"README.md"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"prepublishOnly": "bash ../../scripts/assert-tree-contains-origin-main.sh @50arms/mysql-mcp",
|
|
16
|
+
"build": "tsc -p .",
|
|
17
|
+
"prepare": "tsc -p ."
|
|
18
|
+
},
|
|
19
|
+
"dependencies": {
|
|
20
|
+
"mysql2": "^3.22.5"
|
|
21
|
+
},
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=20"
|
|
24
|
+
}
|
|
25
|
+
}
|
package/README.md
DELETED