@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/bin/mcp-mysql.js CHANGED
@@ -3,15 +3,53 @@
3
3
  /**
4
4
  * MCP MySQL Server CLI
5
5
  * This script allows the MySQL MCP server to be run via NPX
6
- * It implements the Model Context Protocol using stdio transport
6
+ * It implements the Model Context Protocol using stdio transport (default)
7
+ * or, when enabled, the Streamable HTTP transport
7
8
  */
8
9
 
9
10
  const dotenv = require("dotenv");
10
11
 
11
12
  dotenv.config();
12
13
 
14
+ // Transport flags map to environment variables; a flag overrides the variable.
15
+ // They are taken out first so they are never read as permissions/categories.
16
+ const FLAG_ENV = {
17
+ transport: "MCP_TRANSPORT",
18
+ host: "MCP_HTTP_HOST",
19
+ port: "MCP_HTTP_PORT",
20
+ };
21
+
22
+ const positional = [];
23
+ const rawArgs = process.argv.slice(2);
24
+ for (let i = 0; i < rawArgs.length; i++) {
25
+ const arg = rawArgs[i];
26
+ if (!arg.startsWith("--")) {
27
+ positional.push(arg);
28
+ continue;
29
+ }
30
+
31
+ if (arg === "--http" || arg === "--stdio") {
32
+ process.env.MCP_TRANSPORT = arg.slice(2);
33
+ continue;
34
+ }
35
+
36
+ const [flag, inlineValue] = arg.slice(2).split(/=(.*)/s);
37
+ const envName = FLAG_ENV[flag];
38
+ if (!envName) {
39
+ console.error(`Error: unknown option ${arg}`);
40
+ console.error("Options: --transport=stdio|http, --http, --stdio, --host=<addr>, --port=<n>");
41
+ process.exit(1);
42
+ }
43
+ const value = inlineValue !== undefined ? inlineValue : rawArgs[++i];
44
+ if (value === undefined || value === "") {
45
+ console.error(`Error: option --${flag} requires a value`);
46
+ process.exit(1);
47
+ }
48
+ process.env[envName] = value;
49
+ }
50
+
13
51
  // Get MySQL connection string, permissions, and optional categories
14
- const args = process.argv.slice(2);
52
+ const args = positional;
15
53
  const mysqlUrl = args.shift();
16
54
 
17
55
  let permissions;
@@ -34,7 +72,7 @@ for (let i = 0; i < args.length; i++) {
34
72
  if (!mysqlUrl) {
35
73
  console.error("Error: MySQL connection URL is required");
36
74
  console.error(
37
- "Usage: mcp-mysql mysql://user:password@host:port/dbname [permissions] [categories]",
75
+ "Usage: mcp-mysql mysql://user:password@host:port/dbname [permissions] [categories] [--transport=stdio|http] [--host=<addr>] [--port=<n>]",
38
76
  );
39
77
  console.error("");
40
78
  console.error("Examples:");
@@ -83,6 +121,14 @@ if (!mysqlUrl) {
83
121
  " - If permissions + categories: Only tools matching BOTH layers enabled",
84
122
  );
85
123
  console.error(" - If nothing specified: Read-only default (list,read,utility)");
124
+ console.error("");
125
+ console.error("Transport (default stdio):");
126
+ console.error(
127
+ ' mcp-mysql mysql://reader:pass@localhost:3306/mydb "list,read,utility" --transport=http --port=3000',
128
+ );
129
+ console.error(
130
+ " Or set MCP_TRANSPORT=http. HTTP settings (auth, allowed hosts, limits): see DOCUMENTATIONS.md",
131
+ );
86
132
  process.exit(1);
87
133
  }
88
134
 
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Transport and protection settings. Everything here is opt-in: with no
3
+ * variables set the server runs over stdio with all protections disabled,
4
+ * exactly as before the HTTP transport existed.
5
+ */
6
+ export type TransportMode = "stdio" | "http";
7
+ export type HttpAuthMode = "none" | "token" | "oauth";
8
+ export interface OAuthConfig {
9
+ issuer: string;
10
+ audience: string;
11
+ jwksUri?: string;
12
+ requiredScopes: string[];
13
+ }
14
+ export interface HttpConfig {
15
+ host: string;
16
+ port: number;
17
+ path: string;
18
+ publicUrl?: string;
19
+ /** Public URL of the MCP endpoint (publicUrl + path), used as the OAuth resource id */
20
+ resourceUrl?: string;
21
+ auth: HttpAuthMode;
22
+ tokens: string[];
23
+ oauth?: OAuthConfig;
24
+ allowedHosts: string[];
25
+ allowedOrigins: string[];
26
+ trustProxy: boolean;
27
+ allowUnauthenticated: boolean;
28
+ maxSessions: number;
29
+ sessionIdleTimeoutMs: number;
30
+ maxBodyBytes: number;
31
+ }
32
+ export interface RuntimeConfig {
33
+ transport: TransportMode;
34
+ http: HttpConfig;
35
+ queryTimeoutMs: number;
36
+ rateLimitPerMinute: number;
37
+ maxResultBytes: number;
38
+ /** "off", "stderr", or a file path */
39
+ auditLog: string;
40
+ requireReadOnlyDbUser: boolean;
41
+ }
42
+ export declare const isLoopbackHost: (host: string) => boolean;
43
+ /**
44
+ * Parse settings from the environment. Throws with a readable message on
45
+ * invalid or unsafe combinations so the server refuses to start instead of
46
+ * running with a half-applied configuration.
47
+ */
48
+ export declare const loadRuntimeConfig: (env?: NodeJS.ProcessEnv) => RuntimeConfig;
49
+ /** Lazily loaded process-wide configuration. */
50
+ export declare const getRuntimeConfig: () => RuntimeConfig;
@@ -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;
@@ -12,6 +12,25 @@ declare class DatabaseConnection {
12
12
  static getInstance(): DatabaseConnection;
13
13
  getConnection(): Promise<mysql.PoolConnection>;
14
14
  query<T>(sql: string, params?: any[], useCache?: boolean): Promise<T>;
15
+ /**
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[]>;
15
34
  /**
16
35
  * Whether a statement cannot change data seen by cached SELECTs.
17
36
  * EXPLAIN/DESCRIBE ANALYZE executes the wrapped statement, so it is excluded.
@@ -54,6 +73,19 @@ declare class DatabaseConnection {
54
73
  * Reset transaction timeout (call this when there's activity)
55
74
  */
56
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;
57
89
  beginTransaction(transactionId: string): Promise<void>;
58
90
  commitTransaction(transactionId: string): Promise<void>;
59
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
@@ -60,7 +68,7 @@ class DatabaseConnection {
60
68
  }
61
69
  const startTime = Date.now();
62
70
  try {
63
- const [results] = await this.pool.query(sql, params);
71
+ const results = await this.runPooledQuery(sql, params);
64
72
  const duration = Date.now() - startTime;
65
73
  queryLogger_1.QueryLogger.log(sql, params, duration, "success");
66
74
  // Cache SELECT query results
@@ -77,6 +85,97 @@ class DatabaseConnection {
77
85
  throw new Error(`Query execution failed: ${error}`);
78
86
  }
79
87
  }
88
+ /**
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
+ }
80
179
  /**
81
180
  * Whether a statement cannot change data seen by cached SELECTs.
82
181
  * EXPLAIN/DESCRIBE ANALYZE executes the wrapped statement, so it is excluded.
@@ -251,8 +350,50 @@ class DatabaseConnection {
251
350
  this.forceRollbackTransaction(transactionId, "Transaction timeout");
252
351
  }, this.TRANSACTION_TIMEOUT_MS);
253
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
+ }
254
391
  // Transaction Management Methods
255
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
+ }
256
397
  try {
257
398
  const connection = await this.getConnection();
258
399
  await connection.beginTransaction();
@@ -268,6 +409,7 @@ class DatabaseConnection {
268
409
  timeout,
269
410
  queryCount: 0,
270
411
  rapidQueryCount: 0,
412
+ ownerSessionId: currentSessionId(),
271
413
  });
272
414
  }
273
415
  catch (error) {
@@ -275,7 +417,7 @@ class DatabaseConnection {
275
417
  }
276
418
  }
277
419
  async commitTransaction(transactionId) {
278
- const transaction = this.activeTransactions.get(transactionId);
420
+ const transaction = this.getOwnedTransaction(transactionId);
279
421
  if (!transaction) {
280
422
  throw new Error(`No active transaction found with ID: ${transactionId}`);
281
423
  }
@@ -304,7 +446,7 @@ class DatabaseConnection {
304
446
  }
305
447
  }
306
448
  async rollbackTransaction(transactionId) {
307
- const transaction = this.activeTransactions.get(transactionId);
449
+ const transaction = this.getOwnedTransaction(transactionId);
308
450
  if (!transaction) {
309
451
  throw new Error(`No active transaction found with ID: ${transactionId}`);
310
452
  }
@@ -324,16 +466,19 @@ class DatabaseConnection {
324
466
  }
325
467
  }
326
468
  getActiveTransactionIds() {
327
- 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);
328
473
  }
329
474
  hasActiveTransaction(transactionId) {
330
- return this.activeTransactions.has(transactionId);
475
+ return this.getOwnedTransaction(transactionId) !== undefined;
331
476
  }
332
477
  /**
333
478
  * Get transaction information for debugging/monitoring
334
479
  */
335
480
  getTransactionInfo(transactionId) {
336
- const transaction = this.activeTransactions.get(transactionId);
481
+ const transaction = this.getOwnedTransaction(transactionId);
337
482
  if (!transaction) {
338
483
  return { exists: false };
339
484
  }
@@ -385,7 +530,7 @@ class DatabaseConnection {
385
530
  this.queryCache.resetStats();
386
531
  }
387
532
  async executeInTransaction(transactionId, sql, params) {
388
- const transaction = this.activeTransactions.get(transactionId);
533
+ const transaction = this.getOwnedTransaction(transactionId);
389
534
  if (!transaction) {
390
535
  throw new Error(`No active transaction found with ID: ${transactionId}`);
391
536
  }
@@ -393,9 +538,21 @@ class DatabaseConnection {
393
538
  const now = new Date();
394
539
  transaction.lastQueryTime = now;
395
540
  transaction.queryCount++;
541
+ const timeoutMs = (0, runtimeConfig_1.getRuntimeConfig)().queryTimeoutMs;
396
542
  const startTime = Date.now();
397
543
  try {
398
- 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
+ }
399
556
  const duration = Date.now() - startTime;
400
557
  queryLogger_1.QueryLogger.log(sql, params, duration, "success");
401
558
  // DDL commits implicitly, so its effects are visible before COMMIT
@@ -408,6 +565,10 @@ class DatabaseConnection {
408
565
  catch (error) {
409
566
  const duration = Date.now() - startTime;
410
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
+ }
411
572
  throw new Error(`Query execution in transaction failed: ${error}`);
412
573
  }
413
574
  }