forked from benborla/mcp-server-mysql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
573 lines (522 loc) · 17.2 KB
/
Copy pathindex.ts
File metadata and controls
573 lines (522 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { log } from "./src/utils/index.js";
import type { TableRow, ColumnRow } from "./src/types/index.js";
import {
ALLOW_DELETE_OPERATION,
ALLOW_DDL_OPERATION,
ALLOW_INSERT_OPERATION,
ALLOW_UPDATE_OPERATION,
SCHEMA_DELETE_PERMISSIONS,
SCHEMA_DDL_PERMISSIONS,
SCHEMA_INSERT_PERMISSIONS,
SCHEMA_UPDATE_PERMISSIONS,
isMultiDbMode,
mcpConfig as config,
MCP_VERSION as version,
IS_REMOTE_MCP,
REMOTE_SECRET_KEY,
PORT,
ENABLE_PII_REDACTION,
PII_EXTRA_COLUMNS,
PII_EXTRA_COLUMN_PATTERNS,
} from "./src/config/index.js";
import { isPIIColumn, DEFAULT_PII_COLUMNS } from "./src/security/redact.js";
import {
safeExit,
getPool,
executeQuery,
executeReadOnlyQuery,
poolPromise,
} from "./src/db/index.js";
import express, { Request, Response } from "express";
import { fileURLToPath } from 'url';
import { realpathSync } from 'fs';
log("info", `Starting MySQL MCP server v${version}...`);
// Update tool description to include multi-DB mode and schema-specific permissions
const toolVersion = `MySQL MCP Server [v${process.env.npm_package_version}]`;
let toolDescription = `[${toolVersion}] Run SQL queries against MySQL database`;
if (isMultiDbMode) {
toolDescription += " (Multi-DB mode enabled)";
}
if (
ALLOW_INSERT_OPERATION ||
ALLOW_UPDATE_OPERATION ||
ALLOW_DELETE_OPERATION ||
ALLOW_DDL_OPERATION
) {
// At least one write operation is enabled
toolDescription += " with support for:";
if (ALLOW_INSERT_OPERATION) {
toolDescription += " INSERT,";
}
if (ALLOW_UPDATE_OPERATION) {
toolDescription += " UPDATE,";
}
if (ALLOW_DELETE_OPERATION) {
toolDescription += " DELETE,";
}
if (ALLOW_DDL_OPERATION) {
toolDescription += " DDL,";
}
// Remove trailing comma and add READ operations
toolDescription = toolDescription.replace(/,$/, "") + " and READ operations";
if (
Object.keys(SCHEMA_INSERT_PERMISSIONS).length > 0 ||
Object.keys(SCHEMA_UPDATE_PERMISSIONS).length > 0 ||
Object.keys(SCHEMA_DELETE_PERMISSIONS).length > 0 ||
Object.keys(SCHEMA_DDL_PERMISSIONS).length > 0
) {
toolDescription += " (Schema-specific permissions enabled)";
}
} else {
// Only read operations are allowed
toolDescription += " (READ-ONLY)";
}
// Determine if we're in read-only mode (no write operations enabled)
const isReadOnly = !(
ALLOW_INSERT_OPERATION ||
ALLOW_UPDATE_OPERATION ||
ALLOW_DELETE_OPERATION ||
ALLOW_DDL_OPERATION
);
// @INFO: Add debug logging for configuration
log(
"info",
"MySQL Configuration:",
JSON.stringify(
{
...(process.env.MYSQL_SOCKET_PATH
? {
socketPath: process.env.MYSQL_SOCKET_PATH,
connectionType: "Unix Socket",
}
: {
host: process.env.MYSQL_HOST || "127.0.0.1",
port: process.env.MYSQL_PORT || "3306",
connectionType: "TCP/IP",
}),
user: config.mysql.user,
password: config.mysql.password ? "******" : "not set",
database: config.mysql.database || "MULTI_DB_MODE",
ssl: process.env.MYSQL_SSL === "true" ? "enabled" : "disabled",
sslCA: process.env.MYSQL_SSL_CA || "not set",
sslCert: process.env.MYSQL_SSL_CERT || "not set",
sslKey: process.env.MYSQL_SSL_KEY || "not set",
multiDbMode: isMultiDbMode ? "enabled" : "disabled",
},
null,
2,
),
);
// Define configuration schema
export const configSchema = z.object({
debug: z.boolean().default(false).describe("Enable debug logging"),
});
// Export the default function that creates and returns the MCP server
export default function createMcpServer({
sessionId,
config,
}: {
sessionId?: string;
config: z.infer<typeof configSchema>;
}) {
// Create the server instance
const server = new Server(
{
name: "MySQL MCP Server",
version: process.env.npm_package_version || "1.0.0",
},
{
capabilities: {
resources: {},
tools: {
mysql_query: {
description: toolDescription,
inputSchema: {
type: "object",
properties: {
sql: {
type: "string",
description: "The SQL query to execute",
},
},
required: ["sql"],
},
annotations: {
readOnlyHint: isReadOnly,
idempotentHint: isReadOnly,
destructiveHint: !isReadOnly,
openWorldHint: false,
title: "MySQL Query",
},
},
},
},
},
);
// Register request handlers for resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
try {
log("info", "Handling ListResourcesRequest");
const connectionInfo = process.env.MYSQL_SOCKET_PATH
? `socket: ${process.env.MYSQL_SOCKET_PATH}`
: `host: ${process.env.MYSQL_HOST || "localhost"}, port: ${
process.env.MYSQL_PORT || 3306
}`;
log("info", `Connection info: ${connectionInfo}`);
// Query to get all tables
const tablesQuery = `
SELECT
table_name as name,
table_schema as \`database\`,
table_comment as description,
table_rows as rowCount,
data_length as dataSize,
index_length as indexSize,
create_time as createTime,
update_time as updateTime
FROM
information_schema.tables
WHERE
table_schema NOT IN ('information_schema', 'mysql', 'performance_schema', 'sys')
ORDER BY
table_schema, table_name
`;
const queryResult = (await executeReadOnlyQuery<any>(tablesQuery));
const tables = JSON.parse(queryResult.content[0].text) as TableRow[];
log("info", `Found ${tables.length} tables`);
// Create resources for each table
const resources = tables.map((table) => ({
uri: `mysql://tables/${table.name}`,
name: table.name,
title: `${table.database}.${table.name}`,
description:
table.description ||
`Table ${table.name} in database ${table.database}`,
mimeType: "application/json",
}));
// Add a resource for the list of tables
resources.push({
uri: "mysql://tables",
name: "Tables",
title: "MySQL Tables",
description: "List of all MySQL tables",
mimeType: "application/json",
});
return { resources };
} catch (error) {
log("error", "Error in ListResourcesRequest handler:", error);
throw error;
}
});
// Register request handler for reading resources
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
try {
log("info", "Handling ReadResourceRequest:", request.params.uri);
// Parse the URI to extract table name and optional database name
const uriParts = request.params.uri.split("/");
const tableName = uriParts.pop();
const dbName = uriParts.length > 0 ? uriParts.pop() : null;
if (!tableName) {
throw new Error(`Invalid resource URI: ${request.params.uri}`);
}
// Modify query to include schema information
let columnsQuery =
"SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ?";
let queryParams = [tableName as string];
if (dbName) {
columnsQuery += " AND table_schema = ?";
queryParams.push(dbName);
}
const results = (await executeQuery(
columnsQuery,
queryParams,
)) as ColumnRow[];
// When PII redaction is enabled, hide PII column names from the schema
// response so the LLM never learns they exist and won't generate SQL
// referencing them. Combined with the SELECT * guard in executeReadOnlyQuery,
// this gives end-to-end protection: the LLM only ever sees safe columns
// and is forced to project them explicitly.
const piiColumnList = [...DEFAULT_PII_COLUMNS, ...PII_EXTRA_COLUMNS];
const filtered = ENABLE_PII_REDACTION
? results.filter(
(col) =>
!isPIIColumn(col.column_name, piiColumnList, PII_EXTRA_COLUMN_PATTERNS),
)
: results;
if (ENABLE_PII_REDACTION && filtered.length !== results.length) {
log(
"info",
`[redact] hid ${results.length - filtered.length} PII column(s) from schema for table "${tableName}"`,
);
}
return {
contents: [
{
uri: request.params.uri,
mimeType: "application/json",
text: JSON.stringify(filtered, null, 2),
},
],
};
} catch (error) {
log("error", "Error in ReadResourceRequest handler:", error);
throw error;
}
});
// Register handler for tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
log("info", "Handling CallToolRequest:", request.params.name);
if (request.params.name !== "mysql_query") {
throw new Error(`Unknown tool: ${request.params.name}`);
}
const sql = request.params.arguments?.sql as string;
return await executeReadOnlyQuery(sql);
} catch (err) {
const error = err as Error;
log("error", "Error in CallToolRequest handler:", error);
return {
content: [{
type: "text",
text: `Error: ${error.message}`
}],
isError: true
};
}
});
// Register handler for listing tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
log("info", "Handling ListToolsRequest");
const toolsResponse = {
tools: [
{
name: "mysql_query",
description: toolDescription,
inputSchema: {
type: "object",
properties: {
sql: {
type: "string",
description: "The SQL query to execute",
},
},
required: ["sql"],
},
annotations: {
readOnlyHint: isReadOnly,
idempotentHint: isReadOnly,
destructiveHint: !isReadOnly,
openWorldHint: false,
title: "MySQL Query",
},
},
],
};
log(
"info",
"ListToolsRequest response:",
JSON.stringify(toolsResponse, null, 2),
);
return toolsResponse;
});
// Initialize database connection and set up shutdown handlers
(async () => {
try {
log("info", "Attempting to test database connection...");
// Test the connection before fully starting the server
const pool = await getPool();
const connection = await pool.getConnection();
log("info", "Database connection test successful");
connection.release();
} catch (error) {
log("error", "Fatal error during server startup:", error);
safeExit(1);
}
})();
// Setup shutdown handlers
const shutdown = async (signal: string): Promise<void> => {
log("error", `Received ${signal}. Shutting down...`);
try {
// Only attempt to close the pool if it was created
if (poolPromise) {
const pool = await poolPromise;
await pool.end();
}
} catch (err) {
log("error", "Error closing pool:", err);
throw err;
}
};
process.on("SIGINT", async () => {
try {
await shutdown("SIGINT");
process.exit(0);
} catch (err) {
log("error", "Error during SIGINT shutdown:", err);
safeExit(1);
}
});
process.on("SIGTERM", async () => {
try {
await shutdown("SIGTERM");
process.exit(0);
} catch (err) {
log("error", "Error during SIGTERM shutdown:", err);
safeExit(1);
}
});
// Add unhandled error listeners
process.on("uncaughtException", (error) => {
log("error", "Uncaught exception:", error);
safeExit(1);
});
process.on("unhandledRejection", (reason, promise) => {
log("error", "Unhandled rejection at:", promise, "reason:", reason);
safeExit(1);
});
return server;
}
/**
* Checks if the current module is the main module (the entry point of the application).
* This function works for both ES Modules (ESM) and CommonJS.
* @returns {boolean} - True if the module is the main module, false otherwise.
*/
const isMainModule = () => {
// 1. Standard check for CommonJS
// `require.main` refers to the application's entry point module.
// If it's the same as the current `module`, this file was executed directly.
if (typeof require !== 'undefined' && require.main === module) {
return true;
}
// 2. Check for ES Modules (ESM)
// `import.meta.url` provides the file URL of the current module.
// `process.argv[1]` provides the path of the executed script.
if (typeof import.meta !== 'undefined' && import.meta.url && process.argv[1]) {
// Convert the `import.meta.url` (e.g., 'file:///path/to/file.js') to a system-standard absolute path.
const currentModulePath = fileURLToPath(import.meta.url);
// Resolve `process.argv[1]` (which can be a relative path) to a standard absolute path.
const mainScriptPath = realpathSync(process.argv[1]);
// Compare the two standardized absolute paths.
return currentModulePath === mainScriptPath;
}
// Fallback if neither of the above conditions are met.
return false;
}
// Start the server if this file is being run directly
if (isMainModule()) {
log("info", "Running in standalone mode");
// Start the server
(async () => {
try {
const mcpServer = createMcpServer({ config: { debug: false } });
if (IS_REMOTE_MCP && REMOTE_SECRET_KEY?.length) {
const app = express();
app.use(express.json());
app.post("/mcp", async (req: Request, res: Response) => {
// In stateless mode, create a new instance of transport and server for each request
// to ensure complete isolation. A single instance would cause request ID collisions
// when multiple clients connect concurrently.
if (
!req.get("Authorization") ||
!req.get("Authorization")?.startsWith("Bearer ") ||
!req.get("Authorization")?.endsWith(REMOTE_SECRET_KEY)
) {
console.error("Missing or invalid Authorization header");
res.status(401).json({
jsonrpc: "2.0",
error: {
code: -32603,
message: "Missing or invalid Authorization header",
},
id: null,
});
return;
}
try {
const server = createMcpServer({ config: { debug: false } });
const transport: StreamableHTTPServerTransport =
new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
});
res.on("close", () => {
log("info", "Request closed");
transport.close();
server.close();
});
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch (error) {
log("error", "Error handling MCP request:", error);
if (!res.headersSent) {
res.status(500).json({
jsonrpc: "2.0",
error: {
code: -32603,
message: (error as any).message,
},
id: null,
});
}
}
});
// SSE notifications not supported in stateless mode
app.get("/mcp", async (req: Request, res: Response) => {
console.log("Received GET MCP request");
res.writeHead(405).end(
JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
}),
);
});
// Session termination not needed in stateless mode
app.delete("/mcp", async (req: Request, res: Response) => {
console.log("Received DELETE MCP request");
res.writeHead(405).end(
JSON.stringify({
jsonrpc: "2.0",
error: {
code: -32000,
message: "Method not allowed.",
},
id: null,
}),
);
});
// Start the server
app.listen(PORT, (error) => {
if (error) {
console.error("Failed to start server:", error);
process.exit(1);
}
console.log(
`MCP Stateless Streamable HTTP Server listening on port ${PORT}`,
);
});
} else {
const transport = new StdioServerTransport();
// Create a server instance directly instead of importing
await mcpServer.connect(transport);
log("info", "Server started and listening on stdio");
}
} catch (error) {
log("error", "Server error:", error);
safeExit(1);
}
})();
}