@berthojoris/mcp-mysql-server 1.44.0 → 1.46.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.
@@ -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
- // Define all available tools with their schemas
26
- const TOOLS = [
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.",
@@ -1965,7 +1976,7 @@ const TOOLS = [
1965
1976
  },
1966
1977
  {
1967
1978
  name: "optimize_table",
1968
- description: "Optimizes a table to reclaim unused space and defragment data.",
1979
+ description: "Optimizes a table to reclaim unused space and defragment data. Rebuilds the table, so it requires 'ddl' permission.",
1969
1980
  inputSchema: {
1970
1981
  type: "object",
1971
1982
  properties: {
@@ -2006,7 +2017,7 @@ const TOOLS = [
2006
2017
  },
2007
2018
  {
2008
2019
  name: "repair_table",
2009
- description: "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only).",
2020
+ description: "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only). Requires 'ddl' permission.",
2010
2021
  inputSchema: {
2011
2022
  type: "object",
2012
2023
  properties: {
@@ -2062,17 +2073,13 @@ const TOOLS = [
2062
2073
  },
2063
2074
  {
2064
2075
  name: "flush_table",
2065
- description: "Flushes table(s) - closes and reopens them.",
2076
+ description: "Flushes table(s) in the connected database - closes and reopens them. Requires 'ddl' permission.",
2066
2077
  inputSchema: {
2067
2078
  type: "object",
2068
2079
  properties: {
2069
2080
  table_name: {
2070
2081
  type: "string",
2071
- description: "Optional: specific table (omit for all tables)",
2072
- },
2073
- with_read_lock: {
2074
- type: "boolean",
2075
- description: "Acquire read lock after flushing",
2082
+ description: "Optional: specific table (omit for all tables in the connected database)",
2076
2083
  },
2077
2084
  database: {
2078
2085
  type: "string",
@@ -2252,7 +2259,7 @@ const TOOLS = [
2252
2259
  },
2253
2260
  {
2254
2261
  name: "optimize_fulltext",
2255
- description: "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance.",
2262
+ description: "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance. Rebuilds the table, so it requires 'ddl' permission.",
2256
2263
  inputSchema: {
2257
2264
  type: "object",
2258
2265
  properties: {
@@ -2268,25 +2275,7 @@ const TOOLS = [
2268
2275
  required: ["table_name"],
2269
2276
  },
2270
2277
  },
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
- });
2278
+ ]);
2290
2279
  const TOOL_METHOD_OVERRIDES = {
2291
2280
  get_schema_erd: "getSchemaERD",
2292
2281
  export_table_to_csv: "exportTableToCSV",
@@ -2300,6 +2289,7 @@ const getRuntimeToolCatalog = () => {
2300
2289
  name: tool.name,
2301
2290
  description: tool.description,
2302
2291
  inputSchema: tool.inputSchema,
2292
+ annotations: tool.annotations,
2303
2293
  })),
2304
2294
  enabledToolNames: enabledTools.map((tool) => tool.name),
2305
2295
  accessProfile: mysqlMCP.getAccessProfile(),
@@ -2411,21 +2401,52 @@ const executeCursorRequest = async () => {
2411
2401
  error: "Cursor request must contain either tool/toolName/name with arguments, or query with optional mode.",
2412
2402
  };
2413
2403
  };
2414
- // Handle tool call requests
2415
- server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
2416
- const { name, arguments: args } = request.params;
2404
+ const textResult = (text, isError = false) => ({
2405
+ content: [{ type: "text", text }],
2406
+ ...(isError ? { isError: true } : {}),
2407
+ });
2408
+ /**
2409
+ * Serialize a tool result within MCP_MAX_RESULT_BYTES. Row arrays are cut to
2410
+ * the longest prefix that fits; other oversized results become an error.
2411
+ */
2412
+ const serializeResult = (data, maxBytes) => {
2413
+ const text = JSON.stringify(data, null, 2);
2414
+ if (maxBytes <= 0 || text === undefined)
2415
+ return { text };
2416
+ const size = Buffer.byteLength(text);
2417
+ if (size <= maxBytes)
2418
+ return { text };
2419
+ if (Array.isArray(data)) {
2420
+ const wrap = (count) => JSON.stringify({
2421
+ rows: data.slice(0, count),
2422
+ truncated: true,
2423
+ returned_rows: count,
2424
+ total_rows: data.length,
2425
+ 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.`,
2426
+ }, null, 2);
2427
+ let low = 0;
2428
+ let high = data.length;
2429
+ while (low < high) {
2430
+ const mid = Math.ceil((low + high) / 2);
2431
+ if (Buffer.byteLength(wrap(mid)) <= maxBytes)
2432
+ low = mid;
2433
+ else
2434
+ high = mid - 1;
2435
+ }
2436
+ const truncated = wrap(low);
2437
+ if (low > 0 && Buffer.byteLength(truncated) <= maxBytes)
2438
+ return { text: truncated };
2439
+ }
2440
+ return {
2441
+ 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.`,
2442
+ };
2443
+ };
2444
+ const executeToolCall = async (name, args) => {
2417
2445
  // Validate tool arguments before execution
2418
2446
  const validation = (0, toolArgumentValidation_1.validateToolArguments)(name, args);
2419
2447
  if (!validation.valid) {
2420
- return {
2421
- content: [
2422
- {
2423
- type: "text",
2424
- text: `Validation Error: ${validation.errors?.join(', ') || 'Invalid arguments'}`,
2425
- },
2426
- ],
2427
- isError: true,
2428
- };
2448
+ const message = `Validation Error: ${validation.errors?.join(', ') || 'Invalid arguments'}`;
2449
+ return { status: "invalid", error: message, result: textResult(message, true) };
2429
2450
  }
2430
2451
  try {
2431
2452
  assertToolEnabled(name);
@@ -2433,15 +2454,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
2433
2454
  // Handle the result based on status
2434
2455
  if (result.status === "error") {
2435
2456
  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
- };
2457
+ return { status: "error", error: errorText, result: textResult(errorText, true) };
2445
2458
  }
2446
2459
  // Return successful result - handle different result types
2447
2460
  let responseData;
@@ -2449,7 +2462,7 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
2449
2462
  // Standard result with data property
2450
2463
  responseData = result.data;
2451
2464
  }
2452
- else if ("transactionId" in result) {
2465
+ else if ("transactionId" in result || "activeTransactions" in result) {
2453
2466
  // Transaction result
2454
2467
  responseData = {
2455
2468
  transactionId: result.transactionId,
@@ -2469,55 +2482,183 @@ server.setRequestHandler(types_js_1.CallToolRequestSchema, async (request) => {
2469
2482
  // Fallback
2470
2483
  responseData = result;
2471
2484
  }
2472
- // If no query log, return data as before
2473
- return {
2474
- content: [
2475
- {
2476
- type: "text",
2477
- text: JSON.stringify(responseData, null, 2),
2478
- },
2479
- ],
2480
- };
2485
+ const serialized = serializeResult(responseData, (0, runtimeConfig_1.getRuntimeConfig)().maxResultBytes);
2486
+ if ("error" in serialized) {
2487
+ return { status: "error", error: serialized.error, result: textResult(`Error: ${serialized.error}`, true) };
2488
+ }
2489
+ return { status: "success", result: textResult(serialized.text) };
2481
2490
  }
2482
2491
  catch (error) {
2483
2492
  // Check if this is a permission error
2484
2493
  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
- };
2494
+ return { status: "denied", error: error.message, result: textResult(`❌ ${error.message}`, true) };
2494
2495
  }
2495
2496
  // Handle other errors with generic message
2496
2497
  return {
2497
- content: [
2498
- {
2499
- type: "text",
2500
- text: `Error executing tool: ${error.message}`,
2501
- },
2502
- ],
2503
- isError: true,
2498
+ status: "error",
2499
+ error: error.message,
2500
+ result: textResult(`Error executing tool: ${error.message}`, true),
2504
2501
  };
2505
2502
  }
2506
- });
2503
+ };
2504
+ // Handle tool call requests: rate limit, run with the caller's context, audit
2505
+ const handleToolCall = async (request, extra) => {
2506
+ const { name, arguments: args } = request.params;
2507
+ const context = {
2508
+ transport: (0, runtimeConfig_1.getRuntimeConfig)().transport,
2509
+ sessionId: extra?.sessionId,
2510
+ clientId: extra?.authInfo?.clientId,
2511
+ clientIp: extra?.authInfo?.extra?.clientIp,
2512
+ };
2513
+ const startedAt = Date.now();
2514
+ let outcome;
2515
+ const rateLimitKey = context.clientId && context.clientId !== "anonymous" ? context.clientId : context.clientIp || "local";
2516
+ const retryAfterMs = toolRateLimiter.consume(rateLimitKey);
2517
+ if (retryAfterMs > 0) {
2518
+ const message = `Rate limit exceeded (MCP_RATE_LIMIT_PER_MINUTE). Retry in ${Math.ceil(retryAfterMs / 1000)} s.`;
2519
+ outcome = { status: "rate_limited", error: message, result: textResult(`Error: ${message}`, true) };
2520
+ }
2521
+ else {
2522
+ outcome = await (0, requestContext_1.runWithRequestContext)(context, () => executeToolCall(name, args));
2523
+ }
2524
+ auditLogger.log({
2525
+ event: "tool_call",
2526
+ transport: context.transport,
2527
+ session: context.sessionId,
2528
+ client: context.clientId,
2529
+ ip: context.clientIp,
2530
+ tool: name,
2531
+ args: (0, auditLogger_1.summarizeArguments)(args),
2532
+ status: outcome.status,
2533
+ durationMs: Date.now() - startedAt,
2534
+ ...(outcome.error ? { error: outcome.error } : {}),
2535
+ });
2536
+ return outcome.result;
2537
+ };
2538
+ // Build an MCP server with all handlers. Stdio uses one; HTTP creates one per session.
2539
+ const createMcpServer = () => {
2540
+ const server = new index_js_1.Server({
2541
+ name: SERVER_NAME,
2542
+ version: SERVER_VERSION,
2543
+ }, {
2544
+ capabilities: {
2545
+ tools: {},
2546
+ },
2547
+ });
2548
+ // Handle list tools request - filter tools based on permissions and categories
2549
+ server.setRequestHandler(types_js_1.ListToolsRequestSchema, async () => {
2550
+ const enabledTools = (0, toolRegistry_1.getEnabledTools)(mysqlMCP, TOOLS);
2551
+ // Log the filtering results
2552
+ console.error(`Tools available: ${enabledTools.length} of ${TOOLS.length} total tools`);
2553
+ return {
2554
+ tools: enabledTools,
2555
+ };
2556
+ });
2557
+ server.setRequestHandler(types_js_1.CallToolRequestSchema, handleToolCall);
2558
+ return server;
2559
+ };
2560
+ const logAccessProfile = () => {
2561
+ const accessProfile = mysqlMCP.getAccessProfile();
2562
+ console.error(`Permissions (resolved): ${accessProfile.permissions}`);
2563
+ if (accessProfile.categories) {
2564
+ console.error(`Categories (resolved): ${accessProfile.categories}`);
2565
+ }
2566
+ console.error(`Filtering mode: ${accessProfile.filteringMode}`);
2567
+ };
2568
+ /**
2569
+ * Warn (or, with MCP_REQUIRE_READONLY_DB_USER, fail) when the MySQL account
2570
+ * can do more than read.
2571
+ */
2572
+ const checkDatabaseUserGrants = async (runtimeConfig) => {
2573
+ const required = runtimeConfig.requireReadOnlyDbUser;
2574
+ let grants;
2575
+ try {
2576
+ grants = await connection_1.default.getInstance().getCurrentUserGrants();
2577
+ }
2578
+ catch (error) {
2579
+ if (required) {
2580
+ throw new Error(`MCP_REQUIRE_READONLY_DB_USER: could not read grants: ${error.message}`);
2581
+ }
2582
+ console.error(`Warning: could not check MySQL user grants: ${error.message}`);
2583
+ return;
2584
+ }
2585
+ const inspection = (0, grantInspector_1.inspectGrants)(grants);
2586
+ if (inspection.readOnly) {
2587
+ console.error("MySQL user is read-only");
2588
+ return;
2589
+ }
2590
+ const message = `MySQL user has privileges beyond read-only (${inspection.writePrivileges.join(", ")}). ` +
2591
+ "For remote AI clients, connect with a read-only account (see DOCUMENTATIONS.md).";
2592
+ if (required) {
2593
+ throw new Error(`MCP_REQUIRE_READONLY_DB_USER: ${message}`);
2594
+ }
2595
+ console.error(`Warning: ${message}`);
2596
+ };
2597
+ const startHttpTransport = async (runtimeConfig) => {
2598
+ const httpConfig = runtimeConfig.http;
2599
+ mysqlMCP = new index_1.MySQLMCP(permissions, categories);
2600
+ logAccessProfile();
2601
+ await checkDatabaseUserGrants(runtimeConfig);
2602
+ const running = await (0, httpServer_1.startHttpServer)({
2603
+ config: httpConfig,
2604
+ createServer: createMcpServer,
2605
+ auditLogger,
2606
+ onSessionClosed: (sessionId) => {
2607
+ const rolledBack = connection_1.default.getInstance().rollbackTransactionsForSession(sessionId);
2608
+ if (rolledBack > 0) {
2609
+ console.error(`Rolled back ${rolledBack} open transaction(s) of closed session ${sessionId}`);
2610
+ }
2611
+ },
2612
+ });
2613
+ if (httpConfig.auth === "none") {
2614
+ console.error("Warning: HTTP authentication is disabled (MCP_HTTP_AUTH=none)");
2615
+ }
2616
+ if (httpConfig.allowedHosts.length === 0) {
2617
+ console.error("Warning: Host header checks are off; set MCP_HTTP_ALLOWED_HOSTS or MCP_HTTP_PUBLIC_URL");
2618
+ }
2619
+ console.error(`Protections: query timeout ${runtimeConfig.queryTimeoutMs || "off"} ms, ` +
2620
+ `rate limit ${runtimeConfig.rateLimitPerMinute || "off"}/min, ` +
2621
+ `max result ${runtimeConfig.maxResultBytes || "off"} bytes, audit log ${runtimeConfig.auditLog}`);
2622
+ console.error(`MySQL MCP Server running on Streamable HTTP at ${running.url} (auth: ${httpConfig.auth})`);
2623
+ if (httpConfig.resourceUrl) {
2624
+ console.error(`Public endpoint: ${httpConfig.resourceUrl}`);
2625
+ }
2626
+ const shutdown = (signal) => {
2627
+ console.error(`Received ${signal}, shutting down HTTP server`);
2628
+ running
2629
+ .close()
2630
+ .catch(() => undefined)
2631
+ .finally(() => {
2632
+ auditLogger.close();
2633
+ process.exit(0);
2634
+ });
2635
+ };
2636
+ process.once("SIGINT", () => shutdown("SIGINT"));
2637
+ process.once("SIGTERM", () => shutdown("SIGTERM"));
2638
+ };
2507
2639
  // Start the server
2508
2640
  async function main() {
2641
+ const runtimeConfig = (0, runtimeConfig_1.getRuntimeConfig)();
2642
+ auditLogger = new auditLogger_1.AuditLogger(runtimeConfig.auditLog);
2643
+ toolRateLimiter = new rateLimiter_1.RateLimiter(runtimeConfig.rateLimitPerMinute);
2644
+ if (toolRateLimiter.enabled) {
2645
+ setInterval(() => toolRateLimiter.prune(), 60 * 1000).unref();
2646
+ }
2647
+ if (runtimeConfig.transport === "http") {
2648
+ await startHttpTransport(runtimeConfig);
2649
+ return;
2650
+ }
2651
+ const server = createMcpServer();
2509
2652
  const transport = new stdio_js_1.StdioServerTransport();
2510
2653
  await server.connect(transport);
2511
2654
  // Initialize the MySQL MCP instance AFTER transport is connected
2512
2655
  // This ensures the database connection pool is created when the server is ready
2513
2656
  mysqlMCP = new index_1.MySQLMCP(permissions, categories);
2514
2657
  // Log the effective filtering configuration to stderr
2515
- const accessProfile = mysqlMCP.getAccessProfile();
2516
- console.error(`Permissions (resolved): ${accessProfile.permissions}`);
2517
- if (accessProfile.categories) {
2518
- console.error(`Categories (resolved): ${accessProfile.categories}`);
2658
+ logAccessProfile();
2659
+ if (runtimeConfig.requireReadOnlyDbUser) {
2660
+ await checkDatabaseUserGrants(runtimeConfig);
2519
2661
  }
2520
- console.error(`Filtering mode: ${accessProfile.filteringMode}`);
2521
2662
  // Log to stderr (not stdout, which is used for MCP protocol)
2522
2663
  console.error("MySQL MCP Server running on stdio");
2523
2664
  }
@@ -76,15 +76,23 @@ export declare class QueryOptimizer {
76
76
  * Escape special regex characters in a string
77
77
  */
78
78
  private escapeRegex;
79
- /**
80
- * Sanitize identifier (table name, index name) to prevent injection
81
- * Only allows alphanumeric characters, underscores, and dots (for schema.table)
82
- */
83
- private sanitizeIdentifier;
84
79
  /**
85
80
  * Validate that an identifier is safe to use
86
81
  */
87
82
  private isValidIdentifier;
83
+ /**
84
+ * Return the values that are safe identifiers. Hints are added after the
85
+ * query has been validated, so anything else is dropped rather than quoted.
86
+ */
87
+ private safeIdentifiers;
88
+ /**
89
+ * Return a SEMIJOIN/SUBQUERY strategy list if every strategy is allowed
90
+ */
91
+ private safeStrategy;
92
+ /**
93
+ * Return a positive integer no larger than max, or null
94
+ */
95
+ private safePositiveInteger;
88
96
  /**
89
97
  * Apply optimizer hints to a SELECT query
90
98
  */
@@ -28,14 +28,6 @@ class QueryOptimizer {
28
28
  escapeRegex(str) {
29
29
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
30
  }
31
- /**
32
- * Sanitize identifier (table name, index name) to prevent injection
33
- * Only allows alphanumeric characters, underscores, and dots (for schema.table)
34
- */
35
- sanitizeIdentifier(identifier) {
36
- // Remove any characters that aren't alphanumeric, underscore, or dot
37
- return identifier.replace(/[^a-zA-Z0-9_\.]/g, "");
38
- }
39
31
  /**
40
32
  * Validate that an identifier is safe to use
41
33
  */
@@ -44,6 +36,37 @@ class QueryOptimizer {
44
36
  // Max length 64 (MySQL limit)
45
37
  return /^[a-zA-Z_][a-zA-Z0-9_\.]{0,63}$/.test(identifier);
46
38
  }
39
+ /**
40
+ * Return the values that are safe identifiers. Hints are added after the
41
+ * query has been validated, so anything else is dropped rather than quoted.
42
+ */
43
+ safeIdentifiers(value) {
44
+ const values = Array.isArray(value) ? value : [value];
45
+ return values.filter((item) => typeof item === "string" && this.isValidIdentifier(item));
46
+ }
47
+ /**
48
+ * Return a SEMIJOIN/SUBQUERY strategy list if every strategy is allowed
49
+ */
50
+ safeStrategy(strategy, allowed) {
51
+ if (typeof strategy !== "string") {
52
+ return null;
53
+ }
54
+ const strategies = strategy
55
+ .split(",")
56
+ .map((item) => item.trim().toUpperCase());
57
+ return strategies.every((item) => allowed.includes(item))
58
+ ? strategies.join(", ")
59
+ : null;
60
+ }
61
+ /**
62
+ * Return a positive integer no larger than max, or null
63
+ */
64
+ safePositiveInteger(value, max) {
65
+ const number = Number(value);
66
+ return Number.isInteger(number) && number > 0 && number <= max
67
+ ? number
68
+ : null;
69
+ }
47
70
  /**
48
71
  * Apply optimizer hints to a SELECT query
49
72
  */
@@ -110,33 +133,22 @@ class QueryOptimizer {
110
133
  }
111
134
  // Process shorthand hints
112
135
  if (hints.maxExecutionTime !== undefined) {
113
- // Validate maxExecutionTime is a positive integer
114
- const maxTime = Math.floor(Math.abs(Number(hints.maxExecutionTime)));
115
- if (maxTime > 0 && maxTime <= 31536000000) {
116
- // Max 1 year in ms
136
+ // Max 1 year in ms
137
+ const maxTime = this.safePositiveInteger(Math.floor(Math.abs(Number(hints.maxExecutionTime))), 31536000000);
138
+ if (maxTime !== null) {
117
139
  hintParts.push(`MAX_EXECUTION_TIME(${maxTime})`);
118
140
  }
119
141
  }
120
142
  if (hints.forceIndex) {
121
- const indexes = Array.isArray(hints.forceIndex)
122
- ? hints.forceIndex
123
- : [hints.forceIndex];
124
- const sanitizedIndexes = indexes
125
- .map((idx) => this.sanitizeIdentifier(idx))
126
- .filter((idx) => this.isValidIdentifier(idx));
127
- if (sanitizedIndexes.length > 0) {
128
- hintParts.push(`INDEX(${sanitizedIndexes.join(", ")})`);
143
+ const indexes = this.safeIdentifiers(hints.forceIndex);
144
+ if (indexes.length > 0) {
145
+ hintParts.push(`INDEX(${indexes.join(", ")})`);
129
146
  }
130
147
  }
131
148
  if (hints.ignoreIndex) {
132
- const indexes = Array.isArray(hints.ignoreIndex)
133
- ? hints.ignoreIndex
134
- : [hints.ignoreIndex];
135
- const sanitizedIndexes = indexes
136
- .map((idx) => this.sanitizeIdentifier(idx))
137
- .filter((idx) => this.isValidIdentifier(idx));
138
- if (sanitizedIndexes.length > 0) {
139
- hintParts.push(`NO_INDEX(${sanitizedIndexes.join(", ")})`);
149
+ const indexes = this.safeIdentifiers(hints.ignoreIndex);
150
+ if (indexes.length > 0) {
151
+ hintParts.push(`NO_INDEX(${indexes.join(", ")})`);
140
152
  }
141
153
  }
142
154
  return hintParts.join(" ");
@@ -145,6 +157,10 @@ class QueryOptimizer {
145
157
  * Format a single optimizer hint
146
158
  */
147
159
  formatHint(hint) {
160
+ const table = this.safeIdentifiers(hint.table)[0];
161
+ if (hint.table !== undefined && !table) {
162
+ return "";
163
+ }
148
164
  switch (hint.type) {
149
165
  // Join-Order Hints
150
166
  case "JOIN_FIXED_ORDER":
@@ -153,7 +169,10 @@ class QueryOptimizer {
153
169
  case "JOIN_PREFIX":
154
170
  case "JOIN_SUFFIX":
155
171
  if (hint.tables && hint.tables.length > 0) {
156
- return `${hint.type}(${hint.tables.join(", ")})`;
172
+ const tables = this.safeIdentifiers(hint.tables);
173
+ if (tables.length === hint.tables.length) {
174
+ return `${hint.type}(${tables.join(", ")})`;
175
+ }
157
176
  }
158
177
  return "";
159
178
  // Table-Level Hints
@@ -165,8 +184,8 @@ class QueryOptimizer {
165
184
  case "NO_HASH_JOIN":
166
185
  case "MERGE":
167
186
  case "NO_MERGE":
168
- if (hint.table) {
169
- return `${hint.type}(${hint.table})`;
187
+ if (table) {
188
+ return `${hint.type}(${table})`;
170
189
  }
171
190
  return `${hint.type}()`;
172
191
  // Index-Level Hints
@@ -180,41 +199,48 @@ class QueryOptimizer {
180
199
  case "NO_RANGE_OPTIMIZATION":
181
200
  case "SKIP_SCAN":
182
201
  case "NO_SKIP_SCAN":
183
- if (hint.table && hint.index) {
184
- const indexes = Array.isArray(hint.index)
185
- ? hint.index.join(", ")
186
- : hint.index;
187
- return `${hint.type}(${hint.table} ${indexes})`;
202
+ if (table && hint.index) {
203
+ const indexes = this.safeIdentifiers(hint.index);
204
+ const indexCount = Array.isArray(hint.index) ? hint.index.length : 1;
205
+ if (indexes.length === 0 || indexes.length !== indexCount) {
206
+ return "";
207
+ }
208
+ return `${hint.type}(${table} ${indexes.join(", ")})`;
188
209
  }
189
- else if (hint.table) {
190
- return `${hint.type}(${hint.table})`;
210
+ else if (table) {
211
+ return `${hint.type}(${table})`;
191
212
  }
192
213
  return "";
193
214
  // Subquery Hints
194
215
  case "SEMIJOIN":
195
216
  case "NO_SEMIJOIN":
196
217
  if (hint.strategy) {
197
- return `${hint.type}(${hint.strategy})`;
218
+ const strategy = this.safeStrategy(hint.strategy, [
219
+ "DUPSWEEDOUT", "FIRSTMATCH", "LOOSESCAN", "MATERIALIZATION",
220
+ ]);
221
+ return strategy ? `${hint.type}(${strategy})` : "";
198
222
  }
199
223
  return `${hint.type}()`;
200
- case "SUBQUERY":
201
- if (hint.strategy) {
202
- return `SUBQUERY(${hint.strategy})`;
203
- }
204
- return "";
224
+ case "SUBQUERY": {
225
+ const strategy = this.safeStrategy(hint.strategy, [
226
+ "INTOEXISTS", "MATERIALIZATION",
227
+ ]);
228
+ return strategy ? `SUBQUERY(${strategy})` : "";
229
+ }
205
230
  // Miscellaneous
206
- case "MAX_EXECUTION_TIME":
207
- if (hint.value !== undefined) {
208
- return `MAX_EXECUTION_TIME(${hint.value})`;
209
- }
210
- return "";
211
- case "RESOURCE_GROUP":
212
- if (hint.value) {
213
- return `RESOURCE_GROUP(${hint.value})`;
214
- }
215
- return "";
231
+ case "MAX_EXECUTION_TIME": {
232
+ const maxTime = this.safePositiveInteger(hint.value, 31536000000);
233
+ return maxTime !== null ? `MAX_EXECUTION_TIME(${maxTime})` : "";
234
+ }
235
+ case "RESOURCE_GROUP": {
236
+ const group = this.safeIdentifiers(hint.value)[0];
237
+ return group ? `RESOURCE_GROUP(${group})` : "";
238
+ }
216
239
  case "SET_VAR":
217
- if (hint.value) {
240
+ // name=value, where value is a number, a word, or a quoted list such
241
+ // as optimizer_switch='mrr=on,mrr_cost_based=off'
242
+ if (typeof hint.value === "string" &&
243
+ /^[a-zA-Z_][a-zA-Z0-9_]{0,63}s*=s*(?:[a-zA-Z0-9_.]{1,64}|'[a-zA-Z0-9_=,.]{1,256}')$/.test(hint.value)) {
218
244
  return `SET_VAR(${hint.value})`;
219
245
  }
220
246
  return "";
@@ -234,9 +260,10 @@ class QueryOptimizer {
234
260
  return query;
235
261
  }
236
262
  // Find table references and add USE INDEX after them
237
- const indexes = Array.isArray(hints.useIndex)
238
- ? hints.useIndex
239
- : [hints.useIndex];
263
+ const indexes = this.safeIdentifiers(hints.useIndex);
264
+ if (indexes.length === 0) {
265
+ return query;
266
+ }
240
267
  const useIndexClause = `USE INDEX (${indexes.join(", ")})`;
241
268
  // Simple approach: add after FROM clause table
242
269
  // This is a basic implementation - complex queries may need more sophisticated parsing
@@ -0,0 +1,5 @@
1
+ export interface GrantInspection {
2
+ readOnly: boolean;
3
+ writePrivileges: string[];
4
+ }
5
+ export declare const inspectGrants: (grantLines: string[]) => GrantInspection;