@berthojoris/mcp-mysql-server 1.44.0 → 1.45.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/CHANGELOG.md +39 -0
- package/DOCUMENTATIONS.md +674 -524
- package/README.md +468 -382
- package/bin/mcp-mysql.js +49 -3
- package/dist/config/runtimeConfig.d.ts +50 -0
- package/dist/config/runtimeConfig.js +173 -0
- package/dist/db/connection.d.ts +32 -0
- package/dist/db/connection.js +169 -8
- package/dist/mcp-server.js +219 -74
- package/dist/security/grantInspector.d.ts +5 -0
- package/dist/security/grantInspector.js +32 -0
- package/dist/server/auditLogger.d.ts +24 -0
- package/dist/server/auditLogger.js +60 -0
- package/dist/server/auth.d.ts +56 -0
- package/dist/server/auth.js +274 -0
- package/dist/server/httpServer.d.ts +22 -0
- package/dist/server/httpServer.js +320 -0
- package/dist/server/rateLimiter.d.ts +15 -0
- package/dist/server/rateLimiter.js +41 -0
- package/dist/server/requestContext.d.ts +12 -0
- package/dist/server/requestContext.js +9 -0
- package/dist/tools/toolAnnotations.d.ts +4 -0
- package/dist/tools/toolAnnotations.js +73 -0
- package/manifest.json +1 -1
- package/package.json +1 -1
package/dist/mcp-server.js
CHANGED
|
@@ -12,6 +12,14 @@ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
|
|
|
12
12
|
const index_1 = require("./index");
|
|
13
13
|
const toolRegistry_1 = require("./tools/toolRegistry");
|
|
14
14
|
const toolArgumentValidation_1 = require("./tools/toolArgumentValidation");
|
|
15
|
+
const toolAnnotations_1 = require("./tools/toolAnnotations");
|
|
16
|
+
const runtimeConfig_1 = require("./config/runtimeConfig");
|
|
17
|
+
const connection_1 = __importDefault(require("./db/connection"));
|
|
18
|
+
const grantInspector_1 = require("./security/grantInspector");
|
|
19
|
+
const auditLogger_1 = require("./server/auditLogger");
|
|
20
|
+
const rateLimiter_1 = require("./server/rateLimiter");
|
|
21
|
+
const requestContext_1 = require("./server/requestContext");
|
|
22
|
+
const httpServer_1 = require("./server/httpServer");
|
|
15
23
|
// Get permissions and categories from environment variables (set by bin/mcp-mysql.js)
|
|
16
24
|
// Layer 1 (Permissions): MCP_PERMISSIONS or MCP_CONFIG (backward compatible)
|
|
17
25
|
// Layer 2 (Categories): MCP_CATEGORIES (optional, for fine-grained control)
|
|
@@ -22,8 +30,11 @@ const SERVER_NAME = "mysql-mcp-server";
|
|
|
22
30
|
const SERVER_VERSION = JSON.parse(fs_1.default.readFileSync(path_1.default.join(__dirname, "..", "package.json"), "utf8")).version;
|
|
23
31
|
// Declare the MySQL MCP instance (will be initialized in main())
|
|
24
32
|
let mysqlMCP;
|
|
25
|
-
//
|
|
26
|
-
|
|
33
|
+
// Created in main() from the runtime configuration
|
|
34
|
+
let auditLogger = new auditLogger_1.AuditLogger("off");
|
|
35
|
+
let toolRateLimiter = new rateLimiter_1.RateLimiter(0);
|
|
36
|
+
// Define all available tools with their schemas (annotations are added from toolAnnotations.ts)
|
|
37
|
+
const TOOLS = (0, toolAnnotations_1.withToolAnnotations)([
|
|
27
38
|
{
|
|
28
39
|
name: "list_databases",
|
|
29
40
|
description: "Lists all databases available on the MySQL server. Use this to discover what databases exist before querying them.",
|
|
@@ -2268,25 +2279,7 @@ const TOOLS = [
|
|
|
2268
2279
|
required: ["table_name"],
|
|
2269
2280
|
},
|
|
2270
2281
|
},
|
|
2271
|
-
];
|
|
2272
|
-
// Create the MCP server
|
|
2273
|
-
const server = new index_js_1.Server({
|
|
2274
|
-
name: SERVER_NAME,
|
|
2275
|
-
version: SERVER_VERSION,
|
|
2276
|
-
}, {
|
|
2277
|
-
capabilities: {
|
|
2278
|
-
tools: {},
|
|
2279
|
-
},
|
|
2280
|
-
});
|
|
2281
|
-
// Handle list tools request - filter tools based on permissions and categories
|
|
2282
|
-
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
|
|
2283
|
-
const enabledTools = (0, toolRegistry_1.getEnabledTools)(mysqlMCP, TOOLS);
|
|
2284
|
-
// Log the filtering results
|
|
2285
|
-
console.error(`Tools available: ${enabledTools.length} of ${TOOLS.length} total tools`);
|
|
2286
|
-
return {
|
|
2287
|
-
tools: enabledTools,
|
|
2288
|
-
};
|
|
2289
|
-
});
|
|
2282
|
+
]);
|
|
2290
2283
|
const TOOL_METHOD_OVERRIDES = {
|
|
2291
2284
|
get_schema_erd: "getSchemaERD",
|
|
2292
2285
|
export_table_to_csv: "exportTableToCSV",
|
|
@@ -2300,6 +2293,7 @@ const getRuntimeToolCatalog = () => {
|
|
|
2300
2293
|
name: tool.name,
|
|
2301
2294
|
description: tool.description,
|
|
2302
2295
|
inputSchema: tool.inputSchema,
|
|
2296
|
+
annotations: tool.annotations,
|
|
2303
2297
|
})),
|
|
2304
2298
|
enabledToolNames: enabledTools.map((tool) => tool.name),
|
|
2305
2299
|
accessProfile: mysqlMCP.getAccessProfile(),
|
|
@@ -2411,21 +2405,52 @@ const executeCursorRequest = async () => {
|
|
|
2411
2405
|
error: "Cursor request must contain either tool/toolName/name with arguments, or query with optional mode.",
|
|
2412
2406
|
};
|
|
2413
2407
|
};
|
|
2414
|
-
|
|
2415
|
-
|
|
2416
|
-
|
|
2408
|
+
const textResult = (text, isError = false) => ({
|
|
2409
|
+
content: [{ type: "text", text }],
|
|
2410
|
+
...(isError ? { isError: true } : {}),
|
|
2411
|
+
});
|
|
2412
|
+
/**
|
|
2413
|
+
* Serialize a tool result within MCP_MAX_RESULT_BYTES. Row arrays are cut to
|
|
2414
|
+
* the longest prefix that fits; other oversized results become an error.
|
|
2415
|
+
*/
|
|
2416
|
+
const serializeResult = (data, maxBytes) => {
|
|
2417
|
+
const text = JSON.stringify(data, null, 2);
|
|
2418
|
+
if (maxBytes <= 0 || text === undefined)
|
|
2419
|
+
return { text };
|
|
2420
|
+
const size = Buffer.byteLength(text);
|
|
2421
|
+
if (size <= maxBytes)
|
|
2422
|
+
return { text };
|
|
2423
|
+
if (Array.isArray(data)) {
|
|
2424
|
+
const wrap = (count) => JSON.stringify({
|
|
2425
|
+
rows: data.slice(0, count),
|
|
2426
|
+
truncated: true,
|
|
2427
|
+
returned_rows: count,
|
|
2428
|
+
total_rows: data.length,
|
|
2429
|
+
message: `Result truncated to ${count} of ${data.length} rows to stay within ${maxBytes} bytes (MCP_MAX_RESULT_BYTES). Use LIMIT/OFFSET or narrower filters to see the rest.`,
|
|
2430
|
+
}, null, 2);
|
|
2431
|
+
let low = 0;
|
|
2432
|
+
let high = data.length;
|
|
2433
|
+
while (low < high) {
|
|
2434
|
+
const mid = Math.ceil((low + high) / 2);
|
|
2435
|
+
if (Buffer.byteLength(wrap(mid)) <= maxBytes)
|
|
2436
|
+
low = mid;
|
|
2437
|
+
else
|
|
2438
|
+
high = mid - 1;
|
|
2439
|
+
}
|
|
2440
|
+
const truncated = wrap(low);
|
|
2441
|
+
if (low > 0 && Buffer.byteLength(truncated) <= maxBytes)
|
|
2442
|
+
return { text: truncated };
|
|
2443
|
+
}
|
|
2444
|
+
return {
|
|
2445
|
+
error: `Result is ${size} bytes, above the ${maxBytes}-byte limit (MCP_MAX_RESULT_BYTES). Narrow the query with LIMIT, fewer columns, or a WHERE clause.`,
|
|
2446
|
+
};
|
|
2447
|
+
};
|
|
2448
|
+
const executeToolCall = async (name, args) => {
|
|
2417
2449
|
// Validate tool arguments before execution
|
|
2418
2450
|
const validation = (0, toolArgumentValidation_1.validateToolArguments)(name, args);
|
|
2419
2451
|
if (!validation.valid) {
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
{
|
|
2423
|
-
type: "text",
|
|
2424
|
-
text: `Validation Error: ${validation.errors?.join(', ') || 'Invalid arguments'}`,
|
|
2425
|
-
},
|
|
2426
|
-
],
|
|
2427
|
-
isError: true,
|
|
2428
|
-
};
|
|
2452
|
+
const message = `Validation Error: ${validation.errors?.join(', ') || 'Invalid arguments'}`;
|
|
2453
|
+
return { status: "invalid", error: message, result: textResult(message, true) };
|
|
2429
2454
|
}
|
|
2430
2455
|
try {
|
|
2431
2456
|
assertToolEnabled(name);
|
|
@@ -2433,15 +2458,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
|
|
|
2433
2458
|
// Handle the result based on status
|
|
2434
2459
|
if (result.status === "error") {
|
|
2435
2460
|
let errorText = `Error: ${"error" in result ? result.error : "Unknown error"}`;
|
|
2436
|
-
return {
|
|
2437
|
-
content: [
|
|
2438
|
-
{
|
|
2439
|
-
type: "text",
|
|
2440
|
-
text: errorText,
|
|
2441
|
-
},
|
|
2442
|
-
],
|
|
2443
|
-
isError: true,
|
|
2444
|
-
};
|
|
2461
|
+
return { status: "error", error: errorText, result: textResult(errorText, true) };
|
|
2445
2462
|
}
|
|
2446
2463
|
// Return successful result - handle different result types
|
|
2447
2464
|
let responseData;
|
|
@@ -2449,7 +2466,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
|
|
|
2449
2466
|
// Standard result with data property
|
|
2450
2467
|
responseData = result.data;
|
|
2451
2468
|
}
|
|
2452
|
-
else if ("transactionId" in result) {
|
|
2469
|
+
else if ("transactionId" in result || "activeTransactions" in result) {
|
|
2453
2470
|
// Transaction result
|
|
2454
2471
|
responseData = {
|
|
2455
2472
|
transactionId: result.transactionId,
|
|
@@ -2469,55 +2486,183 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
|
|
|
2469
2486
|
// Fallback
|
|
2470
2487
|
responseData = result;
|
|
2471
2488
|
}
|
|
2472
|
-
|
|
2473
|
-
|
|
2474
|
-
|
|
2475
|
-
|
|
2476
|
-
|
|
2477
|
-
text: JSON.stringify(responseData, null, 2),
|
|
2478
|
-
},
|
|
2479
|
-
],
|
|
2480
|
-
};
|
|
2489
|
+
const serialized = serializeResult(responseData, (0, runtimeConfig_1.getRuntimeConfig)().maxResultBytes);
|
|
2490
|
+
if ("error" in serialized) {
|
|
2491
|
+
return { status: "error", error: serialized.error, result: textResult(`Error: ${serialized.error}`, true) };
|
|
2492
|
+
}
|
|
2493
|
+
return { status: "success", result: textResult(serialized.text) };
|
|
2481
2494
|
}
|
|
2482
2495
|
catch (error) {
|
|
2483
2496
|
// Check if this is a permission error
|
|
2484
2497
|
if (error.message && error.message.includes("Permission denied")) {
|
|
2485
|
-
return {
|
|
2486
|
-
content: [
|
|
2487
|
-
{
|
|
2488
|
-
type: "text",
|
|
2489
|
-
text: `❌ ${error.message}`,
|
|
2490
|
-
},
|
|
2491
|
-
],
|
|
2492
|
-
isError: true,
|
|
2493
|
-
};
|
|
2498
|
+
return { status: "denied", error: error.message, result: textResult(`❌ ${error.message}`, true) };
|
|
2494
2499
|
}
|
|
2495
2500
|
// Handle other errors with generic message
|
|
2496
2501
|
return {
|
|
2497
|
-
|
|
2498
|
-
|
|
2499
|
-
|
|
2500
|
-
text: `Error executing tool: ${error.message}`,
|
|
2501
|
-
},
|
|
2502
|
-
],
|
|
2503
|
-
isError: true,
|
|
2502
|
+
status: "error",
|
|
2503
|
+
error: error.message,
|
|
2504
|
+
result: textResult(`Error executing tool: ${error.message}`, true),
|
|
2504
2505
|
};
|
|
2505
2506
|
}
|
|
2506
|
-
}
|
|
2507
|
+
};
|
|
2508
|
+
// Handle tool call requests: rate limit, run with the caller's context, audit
|
|
2509
|
+
const handleToolCall = async (request, extra) => {
|
|
2510
|
+
const { name, arguments: args } = request.params;
|
|
2511
|
+
const context = {
|
|
2512
|
+
transport: (0, runtimeConfig_1.getRuntimeConfig)().transport,
|
|
2513
|
+
sessionId: extra?.sessionId,
|
|
2514
|
+
clientId: extra?.authInfo?.clientId,
|
|
2515
|
+
clientIp: extra?.authInfo?.extra?.clientIp,
|
|
2516
|
+
};
|
|
2517
|
+
const startedAt = Date.now();
|
|
2518
|
+
let outcome;
|
|
2519
|
+
const rateLimitKey = context.clientId && context.clientId !== "anonymous" ? context.clientId : context.clientIp || "local";
|
|
2520
|
+
const retryAfterMs = toolRateLimiter.consume(rateLimitKey);
|
|
2521
|
+
if (retryAfterMs > 0) {
|
|
2522
|
+
const message = `Rate limit exceeded (MCP_RATE_LIMIT_PER_MINUTE). Retry in ${Math.ceil(retryAfterMs / 1000)} s.`;
|
|
2523
|
+
outcome = { status: "rate_limited", error: message, result: textResult(`Error: ${message}`, true) };
|
|
2524
|
+
}
|
|
2525
|
+
else {
|
|
2526
|
+
outcome = await (0, requestContext_1.runWithRequestContext)(context, () => executeToolCall(name, args));
|
|
2527
|
+
}
|
|
2528
|
+
auditLogger.log({
|
|
2529
|
+
event: "tool_call",
|
|
2530
|
+
transport: context.transport,
|
|
2531
|
+
session: context.sessionId,
|
|
2532
|
+
client: context.clientId,
|
|
2533
|
+
ip: context.clientIp,
|
|
2534
|
+
tool: name,
|
|
2535
|
+
args: (0, auditLogger_1.summarizeArguments)(args),
|
|
2536
|
+
status: outcome.status,
|
|
2537
|
+
durationMs: Date.now() - startedAt,
|
|
2538
|
+
...(outcome.error ? { error: outcome.error } : {}),
|
|
2539
|
+
});
|
|
2540
|
+
return outcome.result;
|
|
2541
|
+
};
|
|
2542
|
+
// Build an MCP server with all handlers. Stdio uses one; HTTP creates one per session.
|
|
2543
|
+
const createMcpServer = () => {
|
|
2544
|
+
const server = new index_js_1.Server({
|
|
2545
|
+
name: SERVER_NAME,
|
|
2546
|
+
version: SERVER_VERSION,
|
|
2547
|
+
}, {
|
|
2548
|
+
capabilities: {
|
|
2549
|
+
tools: {},
|
|
2550
|
+
},
|
|
2551
|
+
});
|
|
2552
|
+
// Handle list tools request - filter tools based on permissions and categories
|
|
2553
|
+
server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
|
|
2554
|
+
const enabledTools = (0, toolRegistry_1.getEnabledTools)(mysqlMCP, TOOLS);
|
|
2555
|
+
// Log the filtering results
|
|
2556
|
+
console.error(`Tools available: ${enabledTools.length} of ${TOOLS.length} total tools`);
|
|
2557
|
+
return {
|
|
2558
|
+
tools: enabledTools,
|
|
2559
|
+
};
|
|
2560
|
+
});
|
|
2561
|
+
server.setRequestHandler(types_js_1.CallToolRequestSchema, handleToolCall);
|
|
2562
|
+
return server;
|
|
2563
|
+
};
|
|
2564
|
+
const logAccessProfile = () => {
|
|
2565
|
+
const accessProfile = mysqlMCP.getAccessProfile();
|
|
2566
|
+
console.error(`Permissions (resolved): ${accessProfile.permissions}`);
|
|
2567
|
+
if (accessProfile.categories) {
|
|
2568
|
+
console.error(`Categories (resolved): ${accessProfile.categories}`);
|
|
2569
|
+
}
|
|
2570
|
+
console.error(`Filtering mode: ${accessProfile.filteringMode}`);
|
|
2571
|
+
};
|
|
2572
|
+
/**
|
|
2573
|
+
* Warn (or, with MCP_REQUIRE_READONLY_DB_USER, fail) when the MySQL account
|
|
2574
|
+
* can do more than read.
|
|
2575
|
+
*/
|
|
2576
|
+
const checkDatabaseUserGrants = async (runtimeConfig) => {
|
|
2577
|
+
const required = runtimeConfig.requireReadOnlyDbUser;
|
|
2578
|
+
let grants;
|
|
2579
|
+
try {
|
|
2580
|
+
grants = await connection_1.default.getInstance().getCurrentUserGrants();
|
|
2581
|
+
}
|
|
2582
|
+
catch (error) {
|
|
2583
|
+
if (required) {
|
|
2584
|
+
throw new Error(`MCP_REQUIRE_READONLY_DB_USER: could not read grants: ${error.message}`);
|
|
2585
|
+
}
|
|
2586
|
+
console.error(`Warning: could not check MySQL user grants: ${error.message}`);
|
|
2587
|
+
return;
|
|
2588
|
+
}
|
|
2589
|
+
const inspection = (0, grantInspector_1.inspectGrants)(grants);
|
|
2590
|
+
if (inspection.readOnly) {
|
|
2591
|
+
console.error("MySQL user is read-only");
|
|
2592
|
+
return;
|
|
2593
|
+
}
|
|
2594
|
+
const message = `MySQL user has privileges beyond read-only (${inspection.writePrivileges.join(", ")}). ` +
|
|
2595
|
+
"For remote AI clients, connect with a read-only account (see DOCUMENTATIONS.md).";
|
|
2596
|
+
if (required) {
|
|
2597
|
+
throw new Error(`MCP_REQUIRE_READONLY_DB_USER: ${message}`);
|
|
2598
|
+
}
|
|
2599
|
+
console.error(`Warning: ${message}`);
|
|
2600
|
+
};
|
|
2601
|
+
const startHttpTransport = async (runtimeConfig) => {
|
|
2602
|
+
const httpConfig = runtimeConfig.http;
|
|
2603
|
+
mysqlMCP = new index_1.MySQLMCP(permissions, categories);
|
|
2604
|
+
logAccessProfile();
|
|
2605
|
+
await checkDatabaseUserGrants(runtimeConfig);
|
|
2606
|
+
const running = await (0, httpServer_1.startHttpServer)({
|
|
2607
|
+
config: httpConfig,
|
|
2608
|
+
createServer: createMcpServer,
|
|
2609
|
+
auditLogger,
|
|
2610
|
+
onSessionClosed: (sessionId) => {
|
|
2611
|
+
const rolledBack = connection_1.default.getInstance().rollbackTransactionsForSession(sessionId);
|
|
2612
|
+
if (rolledBack > 0) {
|
|
2613
|
+
console.error(`Rolled back ${rolledBack} open transaction(s) of closed session ${sessionId}`);
|
|
2614
|
+
}
|
|
2615
|
+
},
|
|
2616
|
+
});
|
|
2617
|
+
if (httpConfig.auth === "none") {
|
|
2618
|
+
console.error("Warning: HTTP authentication is disabled (MCP_HTTP_AUTH=none)");
|
|
2619
|
+
}
|
|
2620
|
+
if (httpConfig.allowedHosts.length === 0) {
|
|
2621
|
+
console.error("Warning: Host header checks are off; set MCP_HTTP_ALLOWED_HOSTS or MCP_HTTP_PUBLIC_URL");
|
|
2622
|
+
}
|
|
2623
|
+
console.error(`Protections: query timeout ${runtimeConfig.queryTimeoutMs || "off"} ms, ` +
|
|
2624
|
+
`rate limit ${runtimeConfig.rateLimitPerMinute || "off"}/min, ` +
|
|
2625
|
+
`max result ${runtimeConfig.maxResultBytes || "off"} bytes, audit log ${runtimeConfig.auditLog}`);
|
|
2626
|
+
console.error(`MySQL MCP Server running on Streamable HTTP at ${running.url} (auth: ${httpConfig.auth})`);
|
|
2627
|
+
if (httpConfig.resourceUrl) {
|
|
2628
|
+
console.error(`Public endpoint: ${httpConfig.resourceUrl}`);
|
|
2629
|
+
}
|
|
2630
|
+
const shutdown = (signal) => {
|
|
2631
|
+
console.error(`Received ${signal}, shutting down HTTP server`);
|
|
2632
|
+
running
|
|
2633
|
+
.close()
|
|
2634
|
+
.catch(() => undefined)
|
|
2635
|
+
.finally(() => {
|
|
2636
|
+
auditLogger.close();
|
|
2637
|
+
process.exit(0);
|
|
2638
|
+
});
|
|
2639
|
+
};
|
|
2640
|
+
process.once("SIGINT", () => shutdown("SIGINT"));
|
|
2641
|
+
process.once("SIGTERM", () => shutdown("SIGTERM"));
|
|
2642
|
+
};
|
|
2507
2643
|
// Start the server
|
|
2508
2644
|
async function main() {
|
|
2645
|
+
const runtimeConfig = (0, runtimeConfig_1.getRuntimeConfig)();
|
|
2646
|
+
auditLogger = new auditLogger_1.AuditLogger(runtimeConfig.auditLog);
|
|
2647
|
+
toolRateLimiter = new rateLimiter_1.RateLimiter(runtimeConfig.rateLimitPerMinute);
|
|
2648
|
+
if (toolRateLimiter.enabled) {
|
|
2649
|
+
setInterval(() => toolRateLimiter.prune(), 60 * 1000).unref();
|
|
2650
|
+
}
|
|
2651
|
+
if (runtimeConfig.transport === "http") {
|
|
2652
|
+
await startHttpTransport(runtimeConfig);
|
|
2653
|
+
return;
|
|
2654
|
+
}
|
|
2655
|
+
const server = createMcpServer();
|
|
2509
2656
|
const transport = new stdio_js_1.StdioServerTransport();
|
|
2510
2657
|
await server.connect(transport);
|
|
2511
2658
|
// Initialize the MySQL MCP instance AFTER transport is connected
|
|
2512
2659
|
// This ensures the database connection pool is created when the server is ready
|
|
2513
2660
|
mysqlMCP = new index_1.MySQLMCP(permissions, categories);
|
|
2514
2661
|
// Log the effective filtering configuration to stderr
|
|
2515
|
-
|
|
2516
|
-
|
|
2517
|
-
|
|
2518
|
-
console.error(`Categories (resolved): ${accessProfile.categories}`);
|
|
2662
|
+
logAccessProfile();
|
|
2663
|
+
if (runtimeConfig.requireReadOnlyDbUser) {
|
|
2664
|
+
await checkDatabaseUserGrants(runtimeConfig);
|
|
2519
2665
|
}
|
|
2520
|
-
console.error(`Filtering mode: ${accessProfile.filteringMode}`);
|
|
2521
2666
|
// Log to stderr (not stdout, which is used for MCP protocol)
|
|
2522
2667
|
console.error("MySQL MCP Server running on stdio");
|
|
2523
2668
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.inspectGrants = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Classifies the output of SHOW GRANTS FOR CURRENT_USER(). Anything that is
|
|
6
|
+
* not on the read-only list (including role grants, which cannot be resolved
|
|
7
|
+
* here) counts as a write privilege.
|
|
8
|
+
*/
|
|
9
|
+
const READ_ONLY_PRIVILEGES = new Set(["SELECT", "SHOW VIEW", "SHOW DATABASES", "PROCESS", "USAGE"]);
|
|
10
|
+
const inspectGrants = (grantLines) => {
|
|
11
|
+
const writePrivileges = new Set();
|
|
12
|
+
for (const line of grantLines) {
|
|
13
|
+
const match = /^\s*GRANT\s+(.+?)\s+ON\s+/i.exec(line);
|
|
14
|
+
if (!match) {
|
|
15
|
+
// "GRANT `role`@`%` TO ..." assigns a role whose privileges are unknown
|
|
16
|
+
if (/^\s*GRANT\s+/i.test(line))
|
|
17
|
+
writePrivileges.add("ROLE");
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
if (/\bWITH\s+GRANT\s+OPTION\b/i.test(line))
|
|
21
|
+
writePrivileges.add("GRANT OPTION");
|
|
22
|
+
// Column privileges look like "SELECT (`a`, `b`)"; drop the column lists
|
|
23
|
+
const privileges = match[1].replace(/\([^)]*\)/g, "").split(",");
|
|
24
|
+
for (const raw of privileges) {
|
|
25
|
+
const privilege = raw.trim().toUpperCase().replace(/\s+/g, " ");
|
|
26
|
+
if (privilege && !READ_ONLY_PRIVILEGES.has(privilege))
|
|
27
|
+
writePrivileges.add(privilege);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
return { readOnly: writePrivileges.size === 0, writePrivileges: [...writePrivileges] };
|
|
31
|
+
};
|
|
32
|
+
exports.inspectGrants = inspectGrants;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface AuditEntry {
|
|
2
|
+
event: "tool_call" | "auth_failed" | "session_opened" | "session_closed";
|
|
3
|
+
[key: string]: unknown;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Writes one JSON line per event to stderr or a file. Never writes to stdout,
|
|
7
|
+
* which carries the stdio MCP protocol.
|
|
8
|
+
*/
|
|
9
|
+
export declare class AuditLogger {
|
|
10
|
+
private stream?;
|
|
11
|
+
private readonly toStderr;
|
|
12
|
+
readonly enabled: boolean;
|
|
13
|
+
constructor(target: string);
|
|
14
|
+
log(entry: AuditEntry): void;
|
|
15
|
+
close(): void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Argument summary for audit records: the names of all arguments, plus the SQL
|
|
19
|
+
* text (truncated). Other values are omitted because they may hold row data.
|
|
20
|
+
*/
|
|
21
|
+
export declare const summarizeArguments: (args: Record<string, unknown> | undefined) => {
|
|
22
|
+
names: string[];
|
|
23
|
+
sql?: string;
|
|
24
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.summarizeArguments = exports.AuditLogger = void 0;
|
|
7
|
+
const fs_1 = __importDefault(require("fs"));
|
|
8
|
+
const path_1 = __importDefault(require("path"));
|
|
9
|
+
const MAX_SQL_LENGTH = 1000;
|
|
10
|
+
const SQL_ARGUMENT_NAMES = ["query", "sql"];
|
|
11
|
+
/**
|
|
12
|
+
* Writes one JSON line per event to stderr or a file. Never writes to stdout,
|
|
13
|
+
* which carries the stdio MCP protocol.
|
|
14
|
+
*/
|
|
15
|
+
class AuditLogger {
|
|
16
|
+
constructor(target) {
|
|
17
|
+
this.enabled = target !== "off";
|
|
18
|
+
this.toStderr = target === "stderr";
|
|
19
|
+
if (this.enabled && !this.toStderr) {
|
|
20
|
+
const filePath = path_1.default.resolve(target);
|
|
21
|
+
fs_1.default.mkdirSync(path_1.default.dirname(filePath), { recursive: true });
|
|
22
|
+
this.stream = fs_1.default.createWriteStream(filePath, { flags: "a" });
|
|
23
|
+
this.stream.on("error", (error) => {
|
|
24
|
+
console.error(`Audit log write failed: ${error.message}`);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
log(entry) {
|
|
29
|
+
if (!this.enabled)
|
|
30
|
+
return;
|
|
31
|
+
const line = JSON.stringify({ time: new Date().toISOString(), ...entry });
|
|
32
|
+
if (this.toStderr) {
|
|
33
|
+
console.error(`[audit] ${line}`);
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
this.stream?.write(`${line}\n`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
close() {
|
|
40
|
+
this.stream?.end();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
exports.AuditLogger = AuditLogger;
|
|
44
|
+
/**
|
|
45
|
+
* Argument summary for audit records: the names of all arguments, plus the SQL
|
|
46
|
+
* text (truncated). Other values are omitted because they may hold row data.
|
|
47
|
+
*/
|
|
48
|
+
const summarizeArguments = (args) => {
|
|
49
|
+
const input = args || {};
|
|
50
|
+
const summary = { names: Object.keys(input) };
|
|
51
|
+
for (const name of SQL_ARGUMENT_NAMES) {
|
|
52
|
+
const value = input[name];
|
|
53
|
+
if (typeof value === "string") {
|
|
54
|
+
summary.sql = value.length > MAX_SQL_LENGTH ? `${value.slice(0, MAX_SQL_LENGTH)}...` : value;
|
|
55
|
+
break;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return summary;
|
|
59
|
+
};
|
|
60
|
+
exports.summarizeArguments = summarizeArguments;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
|
|
2
|
+
import { HttpConfig, OAuthConfig } from "../config/runtimeConfig";
|
|
3
|
+
/** Authentication failure mapped to an HTTP status and OAuth error code. */
|
|
4
|
+
export declare class AuthError extends Error {
|
|
5
|
+
readonly status: 401 | 403;
|
|
6
|
+
readonly oauthError: "invalid_request" | "invalid_token" | "insufficient_scope";
|
|
7
|
+
constructor(message: string, status: 401 | 403, oauthError: "invalid_request" | "invalid_token" | "insufficient_scope");
|
|
8
|
+
}
|
|
9
|
+
export interface Authenticator {
|
|
10
|
+
/** Validates the Authorization header value (may be undefined). */
|
|
11
|
+
authenticate(authorization: string | undefined): Promise<AuthInfo>;
|
|
12
|
+
}
|
|
13
|
+
export declare class NoAuthenticator implements Authenticator {
|
|
14
|
+
authenticate(): Promise<AuthInfo>;
|
|
15
|
+
}
|
|
16
|
+
/** Static bearer tokens, compared by SHA-256 digest in constant time. */
|
|
17
|
+
export declare class TokenAuthenticator implements Authenticator {
|
|
18
|
+
private readonly digests;
|
|
19
|
+
constructor(tokens: string[]);
|
|
20
|
+
authenticate(authorization: string | undefined): Promise<AuthInfo>;
|
|
21
|
+
}
|
|
22
|
+
type Fetcher = (url: string) => Promise<any>;
|
|
23
|
+
/**
|
|
24
|
+
* OAuth 2.1 resource server: validates JWT access tokens issued by an external
|
|
25
|
+
* authorization server against its JWKS. Tokens are never issued here.
|
|
26
|
+
*/
|
|
27
|
+
export declare class OAuthAuthenticator implements Authenticator {
|
|
28
|
+
private readonly config;
|
|
29
|
+
private readonly fetcher;
|
|
30
|
+
private readonly now;
|
|
31
|
+
private keys;
|
|
32
|
+
private keysFetchedAt;
|
|
33
|
+
private lastAttemptAt;
|
|
34
|
+
private jwksUri?;
|
|
35
|
+
private refreshing?;
|
|
36
|
+
constructor(config: OAuthConfig, fetcher?: Fetcher, now?: () => number);
|
|
37
|
+
authenticate(authorization: string | undefined): Promise<AuthInfo>;
|
|
38
|
+
private verifySignature;
|
|
39
|
+
private validateClaims;
|
|
40
|
+
private extractScopes;
|
|
41
|
+
private findKey;
|
|
42
|
+
private selectKey;
|
|
43
|
+
private refreshKeys;
|
|
44
|
+
private resolveJwksUri;
|
|
45
|
+
}
|
|
46
|
+
export declare const createAuthenticator: (http: HttpConfig) => Authenticator;
|
|
47
|
+
/** RFC 9728 Protected Resource Metadata for this server. */
|
|
48
|
+
export declare const protectedResourceMetadata: (http: HttpConfig) => {
|
|
49
|
+
resource_name: string;
|
|
50
|
+
scopes_supported?: string[] | undefined;
|
|
51
|
+
resource: string | undefined;
|
|
52
|
+
authorization_servers: string[];
|
|
53
|
+
bearer_methods_supported: string[];
|
|
54
|
+
};
|
|
55
|
+
export declare const protectedResourceMetadataUrl: (http: HttpConfig) => string | undefined;
|
|
56
|
+
export {};
|