@berthojoris/mcp-mysql-server 1.43.5 → 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.
Files changed (66) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/DOCUMENTATIONS.md +674 -508
  3. package/README.md +468 -376
  4. package/bin/mcp-mysql.js +214 -168
  5. package/dist/cache/queryCache.js +1 -1
  6. package/dist/config/config.js +2 -1
  7. package/dist/config/featureConfig.d.ts +5 -0
  8. package/dist/config/featureConfig.js +11 -13
  9. package/dist/config/runtimeConfig.d.ts +50 -0
  10. package/dist/config/runtimeConfig.js +173 -0
  11. package/dist/db/connection.d.ts +40 -1
  12. package/dist/db/connection.js +188 -22
  13. package/dist/mcp-server.js +248 -375
  14. package/dist/security/grantInspector.d.ts +5 -0
  15. package/dist/security/grantInspector.js +32 -0
  16. package/dist/security/securityLayer.d.ts +21 -2
  17. package/dist/security/securityLayer.js +151 -21
  18. package/dist/server/auditLogger.d.ts +24 -0
  19. package/dist/server/auditLogger.js +60 -0
  20. package/dist/server/auth.d.ts +56 -0
  21. package/dist/server/auth.js +274 -0
  22. package/dist/server/httpServer.d.ts +22 -0
  23. package/dist/server/httpServer.js +320 -0
  24. package/dist/server/rateLimiter.d.ts +15 -0
  25. package/dist/server/rateLimiter.js +41 -0
  26. package/dist/server/requestContext.d.ts +12 -0
  27. package/dist/server/requestContext.js +9 -0
  28. package/dist/tools/toolAnnotations.d.ts +4 -0
  29. package/dist/tools/toolAnnotations.js +73 -0
  30. package/dist/tools/toolArgumentValidation.js +22 -22
  31. package/dist/tools/toolRegistry.d.ts +1 -1
  32. package/dist/tools/toolRegistry.js +7 -1
  33. package/manifest.json +1 -1
  34. package/package.json +86 -78
  35. package/dist/auth/authService.d.ts +0 -29
  36. package/dist/auth/authService.js +0 -114
  37. package/dist/tools/backupRestoreTools.d.ts +0 -18
  38. package/dist/tools/backupRestoreTools.js +0 -70
  39. package/dist/tools/documentationGeneratorTools.d.ts +0 -145
  40. package/dist/tools/documentationGeneratorTools.js +0 -820
  41. package/dist/tools/forecastingTools.d.ts +0 -36
  42. package/dist/tools/forecastingTools.js +0 -256
  43. package/dist/tools/functionTools.d.ts +0 -87
  44. package/dist/tools/functionTools.js +0 -358
  45. package/dist/tools/indexRecommendationTools.d.ts +0 -50
  46. package/dist/tools/indexRecommendationTools.js +0 -451
  47. package/dist/tools/intelligentQueryTools.d.ts +0 -94
  48. package/dist/tools/intelligentQueryTools.js +0 -713
  49. package/dist/tools/performanceTools.d.ts +0 -76
  50. package/dist/tools/performanceTools.js +0 -505
  51. package/dist/tools/processTools.d.ts +0 -61
  52. package/dist/tools/processTools.js +0 -181
  53. package/dist/tools/queryVisualizationTools.d.ts +0 -22
  54. package/dist/tools/queryVisualizationTools.js +0 -155
  55. package/dist/tools/schemaDesignTools.d.ts +0 -67
  56. package/dist/tools/schemaDesignTools.js +0 -359
  57. package/dist/tools/schemaPatternTools.d.ts +0 -19
  58. package/dist/tools/schemaPatternTools.js +0 -253
  59. package/dist/tools/schemaVersioningTools.d.ts +0 -138
  60. package/dist/tools/schemaVersioningTools.js +0 -1008
  61. package/dist/tools/securityAuditTools.d.ts +0 -39
  62. package/dist/tools/securityAuditTools.js +0 -319
  63. package/dist/tools/smartDiscoveryTools.d.ts +0 -163
  64. package/dist/tools/smartDiscoveryTools.js +0 -750
  65. package/dist/tools/testDataTools.d.ts +0 -26
  66. package/dist/tools/testDataTools.js +0 -325
@@ -0,0 +1,173 @@
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.getRuntimeConfig = exports.loadRuntimeConfig = exports.isLoopbackHost = void 0;
7
+ const dotenv_1 = __importDefault(require("dotenv"));
8
+ dotenv_1.default.config();
9
+ const LOOPBACK_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
10
+ const MIN_TOKEN_LENGTH = 32;
11
+ const isLoopbackHost = (host) => LOOPBACK_HOSTS.includes(host.trim().toLowerCase());
12
+ exports.isLoopbackHost = isLoopbackHost;
13
+ const list = (value) => (value || "")
14
+ .split(",")
15
+ .map((item) => item.trim())
16
+ .filter(Boolean);
17
+ const parseBoolean = (name, value, fallback) => {
18
+ if (value === undefined || value.trim() === "")
19
+ return fallback;
20
+ const normalized = value.trim().toLowerCase();
21
+ if (["true", "1", "yes", "on"].includes(normalized))
22
+ return true;
23
+ if (["false", "0", "no", "off"].includes(normalized))
24
+ return false;
25
+ throw new Error(`${name} must be true or false, got "${value}"`);
26
+ };
27
+ const parseNonNegativeInt = (name, value, fallback) => {
28
+ if (value === undefined || value.trim() === "")
29
+ return fallback;
30
+ const parsed = Number(value);
31
+ if (!Number.isInteger(parsed) || parsed < 0) {
32
+ throw new Error(`${name} must be a non-negative integer, got "${value}"`);
33
+ }
34
+ return parsed;
35
+ };
36
+ const normalizePath = (value) => {
37
+ const trimmed = value.trim() || "/mcp";
38
+ const withSlash = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
39
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
40
+ };
41
+ /**
42
+ * Parse settings from the environment. Throws with a readable message on
43
+ * invalid or unsafe combinations so the server refuses to start instead of
44
+ * running with a half-applied configuration.
45
+ */
46
+ const loadRuntimeConfig = (env = process.env) => {
47
+ const transportValue = (env.MCP_TRANSPORT || "stdio").trim().toLowerCase();
48
+ if (transportValue !== "stdio" && transportValue !== "http") {
49
+ throw new Error(`MCP_TRANSPORT must be "stdio" or "http", got "${env.MCP_TRANSPORT}"`);
50
+ }
51
+ const transport = transportValue;
52
+ const isHttp = transport === "http";
53
+ // HTTP variables are ignored over stdio so they can never break a stdio setup
54
+ const http = parseHttpConfig(isHttp ? env : {});
55
+ if (isHttp)
56
+ validateHttpConfig(http);
57
+ const auditLog = (env.MCP_AUDIT_LOG || (isHttp ? "stderr" : "off")).trim();
58
+ const auditLogKeyword = auditLog.toLowerCase();
59
+ return {
60
+ transport,
61
+ http,
62
+ queryTimeoutMs: parseNonNegativeInt("MCP_QUERY_TIMEOUT_MS", env.MCP_QUERY_TIMEOUT_MS, isHttp ? 30000 : 0),
63
+ rateLimitPerMinute: parseNonNegativeInt("MCP_RATE_LIMIT_PER_MINUTE", env.MCP_RATE_LIMIT_PER_MINUTE, isHttp ? 60 : 0),
64
+ maxResultBytes: parseNonNegativeInt("MCP_MAX_RESULT_BYTES", env.MCP_MAX_RESULT_BYTES, isHttp ? 512 * 1024 : 0),
65
+ auditLog: auditLogKeyword === "off" || auditLogKeyword === "stderr" ? auditLogKeyword : auditLog,
66
+ requireReadOnlyDbUser: parseBoolean("MCP_REQUIRE_READONLY_DB_USER", env.MCP_REQUIRE_READONLY_DB_USER, false),
67
+ };
68
+ };
69
+ exports.loadRuntimeConfig = loadRuntimeConfig;
70
+ const parseHttpConfig = (env) => {
71
+ const authValue = (env.MCP_HTTP_AUTH || "none").trim().toLowerCase();
72
+ if (!["none", "token", "oauth"].includes(authValue)) {
73
+ throw new Error(`MCP_HTTP_AUTH must be "none", "token", or "oauth", got "${env.MCP_HTTP_AUTH}"`);
74
+ }
75
+ const host = (env.MCP_HTTP_HOST || "127.0.0.1").trim();
76
+ const port = parseNonNegativeInt("MCP_HTTP_PORT", env.MCP_HTTP_PORT, 3000);
77
+ if (port < 1 || port > 65535) {
78
+ throw new Error(`MCP_HTTP_PORT must be between 1 and 65535, got "${env.MCP_HTTP_PORT}"`);
79
+ }
80
+ const path = normalizePath(env.MCP_HTTP_PATH || "/mcp");
81
+ let publicUrl;
82
+ if (env.MCP_HTTP_PUBLIC_URL && env.MCP_HTTP_PUBLIC_URL.trim()) {
83
+ let parsed;
84
+ try {
85
+ parsed = new URL(env.MCP_HTTP_PUBLIC_URL.trim());
86
+ }
87
+ catch {
88
+ throw new Error(`MCP_HTTP_PUBLIC_URL is not a valid URL: "${env.MCP_HTTP_PUBLIC_URL}"`);
89
+ }
90
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
91
+ throw new Error("MCP_HTTP_PUBLIC_URL must use http or https");
92
+ }
93
+ publicUrl = parsed.origin;
94
+ }
95
+ const resourceUrl = publicUrl ? `${publicUrl}${path}` : undefined;
96
+ const allowedHosts = list(env.MCP_HTTP_ALLOWED_HOSTS).map((h) => h.toLowerCase());
97
+ if (allowedHosts.length === 0 && (0, exports.isLoopbackHost)(host)) {
98
+ allowedHosts.push(...LOOPBACK_HOSTS);
99
+ }
100
+ if (publicUrl) {
101
+ const publicHost = new URL(publicUrl).hostname.toLowerCase();
102
+ if (!allowedHosts.includes(publicHost))
103
+ allowedHosts.push(publicHost);
104
+ }
105
+ const http = {
106
+ host,
107
+ port,
108
+ path,
109
+ publicUrl,
110
+ resourceUrl,
111
+ auth: authValue,
112
+ tokens: list(env.MCP_HTTP_AUTH_TOKENS),
113
+ allowedHosts,
114
+ allowedOrigins: list(env.MCP_HTTP_ALLOWED_ORIGINS),
115
+ trustProxy: parseBoolean("MCP_HTTP_TRUST_PROXY", env.MCP_HTTP_TRUST_PROXY, false),
116
+ allowUnauthenticated: parseBoolean("MCP_HTTP_ALLOW_UNAUTHENTICATED", env.MCP_HTTP_ALLOW_UNAUTHENTICATED, false),
117
+ maxSessions: parseNonNegativeInt("MCP_HTTP_MAX_SESSIONS", env.MCP_HTTP_MAX_SESSIONS, 100),
118
+ sessionIdleTimeoutMs: parseNonNegativeInt("MCP_HTTP_SESSION_IDLE_TIMEOUT_MS", env.MCP_HTTP_SESSION_IDLE_TIMEOUT_MS, 30 * 60 * 1000),
119
+ maxBodyBytes: parseNonNegativeInt("MCP_HTTP_MAX_BODY_BYTES", env.MCP_HTTP_MAX_BODY_BYTES, 1024 * 1024),
120
+ };
121
+ if (http.auth === "oauth") {
122
+ const issuer = (env.MCP_OAUTH_ISSUER || "").trim();
123
+ const audience = (env.MCP_OAUTH_AUDIENCE || "").trim() || resourceUrl || "";
124
+ http.oauth = {
125
+ issuer,
126
+ audience,
127
+ jwksUri: (env.MCP_OAUTH_JWKS_URI || "").trim() || undefined,
128
+ requiredScopes: list(env.MCP_OAUTH_REQUIRED_SCOPES),
129
+ };
130
+ }
131
+ return http;
132
+ };
133
+ const validateHttpConfig = (http) => {
134
+ if (http.auth === "token") {
135
+ if (http.tokens.length === 0) {
136
+ throw new Error("MCP_HTTP_AUTH=token requires MCP_HTTP_AUTH_TOKENS");
137
+ }
138
+ if (http.tokens.some((token) => token.length < MIN_TOKEN_LENGTH)) {
139
+ throw new Error(`Every MCP_HTTP_AUTH_TOKENS entry must be at least ${MIN_TOKEN_LENGTH} characters (e.g. openssl rand -hex 32)`);
140
+ }
141
+ }
142
+ if (http.auth === "oauth") {
143
+ if (!http.publicUrl) {
144
+ throw new Error("MCP_HTTP_AUTH=oauth requires MCP_HTTP_PUBLIC_URL (the HTTPS URL clients connect to)");
145
+ }
146
+ if (!http.oauth?.issuer) {
147
+ throw new Error("MCP_HTTP_AUTH=oauth requires MCP_OAUTH_ISSUER");
148
+ }
149
+ try {
150
+ new URL(http.oauth.issuer);
151
+ if (http.oauth.jwksUri)
152
+ new URL(http.oauth.jwksUri);
153
+ }
154
+ catch {
155
+ throw new Error("MCP_OAUTH_ISSUER and MCP_OAUTH_JWKS_URI must be valid URLs");
156
+ }
157
+ }
158
+ if (http.auth === "none" && !http.allowUnauthenticated) {
159
+ const exposedHosts = http.allowedHosts.filter((h) => !(0, exports.isLoopbackHost)(h));
160
+ if (!(0, exports.isLoopbackHost)(http.host) || exposedHosts.length > 0) {
161
+ throw new Error("MCP_HTTP_AUTH=none is only allowed on a loopback address with loopback-only allowed hosts. " +
162
+ "Set MCP_HTTP_AUTH=token or oauth, or MCP_HTTP_ALLOW_UNAUTHENTICATED=true to override.");
163
+ }
164
+ }
165
+ };
166
+ let cachedConfig;
167
+ /** Lazily loaded process-wide configuration. */
168
+ const getRuntimeConfig = () => {
169
+ if (!cachedConfig)
170
+ cachedConfig = (0, exports.loadRuntimeConfig)();
171
+ return cachedConfig;
172
+ };
173
+ exports.getRuntimeConfig = getRuntimeConfig;
@@ -13,7 +13,33 @@ declare class DatabaseConnection {
13
13
  getConnection(): Promise<mysql.PoolConnection>;
14
14
  query<T>(sql: string, params?: any[], useCache?: boolean): Promise<T>;
15
15
  /**
16
- * Invalidate cache entries when write operations occur
16
+ * Run a statement on the pool. With MCP_QUERY_TIMEOUT_MS set, the statement
17
+ * runs on a dedicated pool connection so it can be cancelled server-side.
18
+ */
19
+ private runPooledQuery;
20
+ /**
21
+ * Run a statement and cancel it with KILL QUERY once timeoutMs elapses.
22
+ * `timedOut` is true when the cancellation fired, even if the statement won the race.
23
+ */
24
+ private queryWithTimeout;
25
+ /**
26
+ * Cancel the statement running on a connection. Uses a separate short-lived
27
+ * connection so it works even when the pool is exhausted.
28
+ */
29
+ private killQuery;
30
+ /**
31
+ * Grants of the connected MySQL account (SHOW GRANTS FOR CURRENT_USER()).
32
+ */
33
+ getCurrentUserGrants(): Promise<string[]>;
34
+ /**
35
+ * Whether a statement cannot change data seen by cached SELECTs.
36
+ * EXPLAIN/DESCRIBE ANALYZE executes the wrapped statement, so it is excluded.
37
+ */
38
+ static isReadOnlyStatement(sql: string): boolean;
39
+ /**
40
+ * Clear the whole cache when a statement may have changed data. Writes can
41
+ * touch tables that are hard to extract reliably (multi-table UPDATE/DELETE,
42
+ * db-qualified names, DDL, procedures), so no table-level guessing is done.
17
43
  */
18
44
  private invalidateCacheForWriteOperation;
19
45
  testConnection(): Promise<{
@@ -47,6 +73,19 @@ declare class DatabaseConnection {
47
73
  * Reset transaction timeout (call this when there's activity)
48
74
  */
49
75
  private resetTransactionTimeout;
76
+ /**
77
+ * Transaction visible to the current caller. Transactions begun in another
78
+ * MCP session are reported as missing so their ids are not confirmed.
79
+ */
80
+ private getOwnedTransaction;
81
+ /**
82
+ * Drop a transaction by destroying its connection; MySQL rolls it back.
83
+ */
84
+ private discardTransaction;
85
+ /**
86
+ * Roll back every transaction owned by an MCP session (session closed or expired).
87
+ */
88
+ rollbackTransactionsForSession(sessionId: string): number;
50
89
  beginTransaction(transactionId: string): Promise<void>;
51
90
  commitTransaction(transactionId: string): Promise<void>;
52
91
  rollbackTransaction(transactionId: string): Promise<void>;
@@ -7,6 +7,14 @@ const promise_1 = __importDefault(require("mysql2/promise"));
7
7
  const config_1 = require("../config/config");
8
8
  const queryLogger_1 = require("./queryLogger");
9
9
  const queryCache_1 = require("../cache/queryCache");
10
+ const runtimeConfig_1 = require("../config/runtimeConfig");
11
+ const requestContext_1 = require("../server/requestContext");
12
+ class QueryTimeoutError extends Error {
13
+ constructor(timeoutMs) {
14
+ super(`Query exceeded the ${timeoutMs} ms timeout and was cancelled`);
15
+ }
16
+ }
17
+ const currentSessionId = () => (0, requestContext_1.getRequestContext)()?.sessionId;
10
18
  class DatabaseConnection {
11
19
  constructor() {
12
20
  this.TRANSACTION_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes default timeout
@@ -17,7 +25,8 @@ class DatabaseConnection {
17
25
  port: config_1.dbConfig.port,
18
26
  user: config_1.dbConfig.user,
19
27
  password: config_1.dbConfig.password,
20
- database: config_1.dbConfig.database,
28
+ // No default schema unless one was configured
29
+ database: config_1.dbConfig.database || undefined,
21
30
  waitForConnections: true,
22
31
  connectionLimit: 10,
23
32
  queueLimit: 0,
@@ -59,7 +68,7 @@ class DatabaseConnection {
59
68
  }
60
69
  const startTime = Date.now();
61
70
  try {
62
- const [results] = await this.pool.query(sql, params);
71
+ const results = await this.runPooledQuery(sql, params);
63
72
  const duration = Date.now() - startTime;
64
73
  queryLogger_1.QueryLogger.log(sql, params, duration, "success");
65
74
  // Cache SELECT query results
@@ -67,9 +76,7 @@ class DatabaseConnection {
67
76
  this.queryCache.set(sql, params, results);
68
77
  }
69
78
  // Invalidate cache for write operations
70
- if (!isSelectQuery) {
71
- this.invalidateCacheForWriteOperation(sql);
72
- }
79
+ this.invalidateCacheForWriteOperation(sql);
73
80
  return results;
74
81
  }
75
82
  catch (error) {
@@ -79,18 +86,111 @@ class DatabaseConnection {
79
86
  }
80
87
  }
81
88
  /**
82
- * Invalidate cache entries when write operations occur
89
+ * Run a statement on the pool. With MCP_QUERY_TIMEOUT_MS set, the statement
90
+ * runs on a dedicated pool connection so it can be cancelled server-side.
91
+ */
92
+ async runPooledQuery(sql, params) {
93
+ const timeoutMs = (0, runtimeConfig_1.getRuntimeConfig)().queryTimeoutMs;
94
+ if (timeoutMs <= 0) {
95
+ const [results] = await this.pool.query(sql, params);
96
+ return results;
97
+ }
98
+ const connection = await this.getConnection();
99
+ let timedOut = false;
100
+ try {
101
+ const outcome = await this.queryWithTimeout(connection, sql, params, timeoutMs);
102
+ timedOut = outcome.timedOut;
103
+ return outcome.results;
104
+ }
105
+ catch (error) {
106
+ timedOut = error instanceof QueryTimeoutError;
107
+ throw error;
108
+ }
109
+ finally {
110
+ // A KILL QUERY that arrives after the statement finished could interrupt
111
+ // the next statement on this connection, so never reuse it.
112
+ if (timedOut) {
113
+ connection.destroy();
114
+ }
115
+ else {
116
+ connection.release();
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * Run a statement and cancel it with KILL QUERY once timeoutMs elapses.
122
+ * `timedOut` is true when the cancellation fired, even if the statement won the race.
123
+ */
124
+ async queryWithTimeout(connection, sql, params, timeoutMs) {
125
+ let timedOut = false;
126
+ let killing;
127
+ const timer = setTimeout(() => {
128
+ timedOut = true;
129
+ killing = this.killQuery(connection.threadId);
130
+ }, timeoutMs);
131
+ try {
132
+ const [results] = await connection.query(sql, params);
133
+ return { results, timedOut };
134
+ }
135
+ catch (error) {
136
+ if (timedOut)
137
+ throw new QueryTimeoutError(timeoutMs);
138
+ throw error;
139
+ }
140
+ finally {
141
+ clearTimeout(timer);
142
+ if (killing)
143
+ await killing;
144
+ }
145
+ }
146
+ /**
147
+ * Cancel the statement running on a connection. Uses a separate short-lived
148
+ * connection so it works even when the pool is exhausted.
149
+ */
150
+ async killQuery(threadId) {
151
+ if (!threadId)
152
+ return;
153
+ let killer;
154
+ try {
155
+ killer = await promise_1.default.createConnection({
156
+ host: config_1.dbConfig.host,
157
+ port: config_1.dbConfig.port,
158
+ user: config_1.dbConfig.user,
159
+ password: config_1.dbConfig.password,
160
+ });
161
+ await killer.query(`KILL QUERY ${Number(threadId)}`);
162
+ }
163
+ catch (error) {
164
+ console.error(`Failed to cancel timed-out query on thread ${threadId}: ${error.message}`);
165
+ }
166
+ finally {
167
+ if (killer) {
168
+ await killer.end().catch(() => killer?.destroy());
169
+ }
170
+ }
171
+ }
172
+ /**
173
+ * Grants of the connected MySQL account (SHOW GRANTS FOR CURRENT_USER()).
174
+ */
175
+ async getCurrentUserGrants() {
176
+ const [rows] = await this.pool.query("SHOW GRANTS FOR CURRENT_USER()");
177
+ return rows.map((row) => String(Object.values(row)[0]));
178
+ }
179
+ /**
180
+ * Whether a statement cannot change data seen by cached SELECTs.
181
+ * EXPLAIN/DESCRIBE ANALYZE executes the wrapped statement, so it is excluded.
182
+ */
183
+ static isReadOnlyStatement(sql) {
184
+ return /^(?:SELECT|SHOW)\b|^(?:EXPLAIN|DESCRIBE|DESC)\b(?!\s+ANALYZE\b)/i.test(sql.trim());
185
+ }
186
+ /**
187
+ * Clear the whole cache when a statement may have changed data. Writes can
188
+ * touch tables that are hard to extract reliably (multi-table UPDATE/DELETE,
189
+ * db-qualified names, DDL, procedures), so no table-level guessing is done.
83
190
  */
84
191
  invalidateCacheForWriteOperation(sql) {
85
- // Extract table name from INSERT, UPDATE, DELETE statements
86
- const insertMatch = sql.match(/INSERT\s+INTO\s+[\`"']?(\w+)[\`"']?/i);
87
- const updateMatch = sql.match(/UPDATE\s+[\`"']?(\w+)[\`"']?/i);
88
- const deleteMatch = sql.match(/DELETE\s+FROM\s+[\`"']?(\w+)[\`"']?/i);
89
- const truncateMatch = sql.match(/TRUNCATE\s+(?:TABLE\s+)?[\`"']?(\w+)[\`"']?/i);
90
- const dropMatch = sql.match(/DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?[\`"']?(\w+)[\`"']?/i);
91
- const match = insertMatch || updateMatch || deleteMatch || truncateMatch || dropMatch;
92
- if (match && match[1]) {
93
- this.queryCache.invalidateTable(match[1]);
192
+ if (!DatabaseConnection.isReadOnlyStatement(sql)) {
193
+ this.queryCache.clear();
94
194
  }
95
195
  }
96
196
  async testConnection() {
@@ -250,8 +350,50 @@ class DatabaseConnection {
250
350
  this.forceRollbackTransaction(transactionId, "Transaction timeout");
251
351
  }, this.TRANSACTION_TIMEOUT_MS);
252
352
  }
353
+ /**
354
+ * Transaction visible to the current caller. Transactions begun in another
355
+ * MCP session are reported as missing so their ids are not confirmed.
356
+ */
357
+ getOwnedTransaction(transactionId) {
358
+ const transaction = this.activeTransactions.get(transactionId);
359
+ if (!transaction || transaction.ownerSessionId !== currentSessionId()) {
360
+ return undefined;
361
+ }
362
+ return transaction;
363
+ }
364
+ /**
365
+ * Drop a transaction by destroying its connection; MySQL rolls it back.
366
+ */
367
+ discardTransaction(transactionId, reason) {
368
+ const transaction = this.activeTransactions.get(transactionId);
369
+ if (!transaction)
370
+ return;
371
+ if (transaction.timeout) {
372
+ clearTimeout(transaction.timeout);
373
+ }
374
+ this.activeTransactions.delete(transactionId);
375
+ transaction.connection.destroy();
376
+ console.warn(`Transaction ${transactionId} rolled back: ${reason}`);
377
+ }
378
+ /**
379
+ * Roll back every transaction owned by an MCP session (session closed or expired).
380
+ */
381
+ rollbackTransactionsForSession(sessionId) {
382
+ let count = 0;
383
+ for (const [transactionId, transaction] of this.activeTransactions) {
384
+ if (transaction.ownerSessionId === sessionId) {
385
+ this.discardTransaction(transactionId, `session ${sessionId} closed`);
386
+ count++;
387
+ }
388
+ }
389
+ return count;
390
+ }
253
391
  // Transaction Management Methods
254
392
  async beginTransaction(transactionId) {
393
+ if (this.activeTransactions.has(transactionId)) {
394
+ // Replacing the entry would leak the open transaction's connection
395
+ throw new Error(`Failed to begin transaction: transaction ID ${transactionId} is already in use`);
396
+ }
255
397
  try {
256
398
  const connection = await this.getConnection();
257
399
  await connection.beginTransaction();
@@ -267,6 +409,7 @@ class DatabaseConnection {
267
409
  timeout,
268
410
  queryCount: 0,
269
411
  rapidQueryCount: 0,
412
+ ownerSessionId: currentSessionId(),
270
413
  });
271
414
  }
272
415
  catch (error) {
@@ -274,7 +417,7 @@ class DatabaseConnection {
274
417
  }
275
418
  }
276
419
  async commitTransaction(transactionId) {
277
- const transaction = this.activeTransactions.get(transactionId);
420
+ const transaction = this.getOwnedTransaction(transactionId);
278
421
  if (!transaction) {
279
422
  throw new Error(`No active transaction found with ID: ${transactionId}`);
280
423
  }
@@ -286,6 +429,8 @@ class DatabaseConnection {
286
429
  await transaction.connection.commit();
287
430
  transaction.connection.release();
288
431
  this.activeTransactions.delete(transactionId);
432
+ // Reads cached while the transaction was open predate its committed writes
433
+ this.queryCache.clear();
289
434
  }
290
435
  catch (error) {
291
436
  // If commit fails, rollback and release connection
@@ -301,7 +446,7 @@ class DatabaseConnection {
301
446
  }
302
447
  }
303
448
  async rollbackTransaction(transactionId) {
304
- const transaction = this.activeTransactions.get(transactionId);
449
+ const transaction = this.getOwnedTransaction(transactionId);
305
450
  if (!transaction) {
306
451
  throw new Error(`No active transaction found with ID: ${transactionId}`);
307
452
  }
@@ -321,16 +466,19 @@ class DatabaseConnection {
321
466
  }
322
467
  }
323
468
  getActiveTransactionIds() {
324
- return Array.from(this.activeTransactions.keys());
469
+ const sessionId = currentSessionId();
470
+ return Array.from(this.activeTransactions.entries())
471
+ .filter(([, transaction]) => transaction.ownerSessionId === sessionId)
472
+ .map(([transactionId]) => transactionId);
325
473
  }
326
474
  hasActiveTransaction(transactionId) {
327
- return this.activeTransactions.has(transactionId);
475
+ return this.getOwnedTransaction(transactionId) !== undefined;
328
476
  }
329
477
  /**
330
478
  * Get transaction information for debugging/monitoring
331
479
  */
332
480
  getTransactionInfo(transactionId) {
333
- const transaction = this.activeTransactions.get(transactionId);
481
+ const transaction = this.getOwnedTransaction(transactionId);
334
482
  if (!transaction) {
335
483
  return { exists: false };
336
484
  }
@@ -382,7 +530,7 @@ class DatabaseConnection {
382
530
  this.queryCache.resetStats();
383
531
  }
384
532
  async executeInTransaction(transactionId, sql, params) {
385
- const transaction = this.activeTransactions.get(transactionId);
533
+ const transaction = this.getOwnedTransaction(transactionId);
386
534
  if (!transaction) {
387
535
  throw new Error(`No active transaction found with ID: ${transactionId}`);
388
536
  }
@@ -390,11 +538,25 @@ class DatabaseConnection {
390
538
  const now = new Date();
391
539
  transaction.lastQueryTime = now;
392
540
  transaction.queryCount++;
541
+ const timeoutMs = (0, runtimeConfig_1.getRuntimeConfig)().queryTimeoutMs;
393
542
  const startTime = Date.now();
394
543
  try {
395
- const [results] = await transaction.connection.query(sql, params);
544
+ let results;
545
+ if (timeoutMs > 0) {
546
+ const outcome = await this.queryWithTimeout(transaction.connection, sql, params, timeoutMs);
547
+ if (outcome.timedOut) {
548
+ // The KILL may still reach this connection, so the transaction cannot continue
549
+ throw new QueryTimeoutError(timeoutMs);
550
+ }
551
+ results = outcome.results;
552
+ }
553
+ else {
554
+ [results] = await transaction.connection.query(sql, params);
555
+ }
396
556
  const duration = Date.now() - startTime;
397
557
  queryLogger_1.QueryLogger.log(sql, params, duration, "success");
558
+ // DDL commits implicitly, so its effects are visible before COMMIT
559
+ this.invalidateCacheForWriteOperation(sql);
398
560
  // Reset timeout on successful activity and update last activity
399
561
  this.resetTransactionTimeout(transactionId);
400
562
  transaction.lastActivity = now;
@@ -403,6 +565,10 @@ class DatabaseConnection {
403
565
  catch (error) {
404
566
  const duration = Date.now() - startTime;
405
567
  queryLogger_1.QueryLogger.log(sql, params, duration, "error", error.message);
568
+ if (error instanceof QueryTimeoutError) {
569
+ this.discardTransaction(transactionId, "statement timed out");
570
+ throw new Error(`Query execution in transaction failed: ${error.message}; transaction ${transactionId} was rolled back`);
571
+ }
406
572
  throw new Error(`Query execution in transaction failed: ${error}`);
407
573
  }
408
574
  }