@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.
@@ -0,0 +1,320 @@
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.startHttpServer = void 0;
7
+ const http_1 = __importDefault(require("http"));
8
+ const crypto_1 = require("crypto");
9
+ const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
10
+ const types_js_1 = require("@modelcontextprotocol/sdk/types.js");
11
+ const runtimeConfig_1 = require("../config/runtimeConfig");
12
+ const auth_1 = require("./auth");
13
+ class RequestBodyError extends Error {
14
+ constructor(message, status) {
15
+ super(message);
16
+ this.status = status;
17
+ }
18
+ }
19
+ const sendJson = (res, status, body, headers = {}) => {
20
+ if (res.headersSent) {
21
+ res.end();
22
+ return;
23
+ }
24
+ res.writeHead(status, { "Content-Type": "application/json", ...headers });
25
+ res.end(JSON.stringify(body));
26
+ };
27
+ const jsonRpcError = (code, message) => ({
28
+ jsonrpc: "2.0",
29
+ error: { code, message },
30
+ id: null,
31
+ });
32
+ const readJsonBody = (req, maxBytes) => new Promise((resolve, reject) => {
33
+ const chunks = [];
34
+ let size = 0;
35
+ let failed = false;
36
+ req.on("data", (chunk) => {
37
+ if (failed)
38
+ return;
39
+ size += chunk.length;
40
+ if (maxBytes > 0 && size > maxBytes) {
41
+ failed = true;
42
+ reject(new RequestBodyError(`Request body exceeds ${maxBytes} bytes`, 413));
43
+ return;
44
+ }
45
+ chunks.push(chunk);
46
+ });
47
+ req.on("end", () => {
48
+ if (failed)
49
+ return;
50
+ try {
51
+ resolve(JSON.parse(Buffer.concat(chunks).toString("utf8")));
52
+ }
53
+ catch {
54
+ reject(new RequestBodyError("Parse error: request body is not valid JSON", 400));
55
+ }
56
+ });
57
+ req.on("error", (error) => {
58
+ if (!failed)
59
+ reject(error);
60
+ });
61
+ });
62
+ /** Hostname from a Host header value, without the port ("[::1]:3000" -> "[::1]"). */
63
+ const hostnameOf = (hostHeader) => {
64
+ const value = hostHeader.trim().toLowerCase();
65
+ if (value.startsWith("[")) {
66
+ const end = value.indexOf("]");
67
+ return end === -1 ? value : value.slice(0, end + 1);
68
+ }
69
+ return value.split(":")[0];
70
+ };
71
+ const startHttpServer = async (options) => {
72
+ const { config, createServer, auditLogger } = options;
73
+ const authenticator = options.authenticator || (0, auth_1.createAuthenticator)(config);
74
+ const sessions = new Map();
75
+ const metadataPaths = new Set(["/.well-known/oauth-protected-resource", `/.well-known/oauth-protected-resource${config.path}`]);
76
+ const resourceMetadataUrl = (0, auth_1.protectedResourceMetadataUrl)(config);
77
+ const allowedOrigins = new Set(config.allowedOrigins.map((origin) => origin.replace(/\/+$/, "").toLowerCase()));
78
+ const clientIpOf = (req) => {
79
+ if (config.trustProxy) {
80
+ const forwarded = req.headers["x-forwarded-for"];
81
+ const first = (Array.isArray(forwarded) ? forwarded[0] : forwarded || "").split(",")[0].trim();
82
+ if (first)
83
+ return first;
84
+ }
85
+ return req.socket.remoteAddress || "unknown";
86
+ };
87
+ const isHostAllowed = (hostHeader) => {
88
+ if (config.allowedHosts.length === 0)
89
+ return true;
90
+ if (!hostHeader)
91
+ return false;
92
+ return config.allowedHosts.includes(hostnameOf(hostHeader));
93
+ };
94
+ const isOriginAllowed = (origin) => {
95
+ const normalized = origin.replace(/\/+$/, "").toLowerCase();
96
+ if (allowedOrigins.size > 0)
97
+ return allowedOrigins.has(normalized);
98
+ // Default: only local browser tools may call a loopback-bound server
99
+ if (!(0, runtimeConfig_1.isLoopbackHost)(config.host))
100
+ return false;
101
+ try {
102
+ return (0, runtimeConfig_1.isLoopbackHost)(new URL(normalized).hostname);
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ };
108
+ const setCorsHeaders = (res, origin) => {
109
+ res.setHeader("Access-Control-Allow-Origin", origin);
110
+ res.setHeader("Vary", "Origin");
111
+ res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS");
112
+ res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID");
113
+ res.setHeader("Access-Control-Expose-Headers", "Mcp-Session-Id, WWW-Authenticate");
114
+ };
115
+ const authenticateHeader = (error) => {
116
+ const parts = ['Bearer realm="mysql-mcp"'];
117
+ if (resourceMetadataUrl && config.auth === "oauth") {
118
+ parts.push(`resource_metadata="${resourceMetadataUrl}"`);
119
+ }
120
+ // RFC 6750: no error code when the request carried no credentials
121
+ if (error && error.oauthError !== "invalid_request") {
122
+ parts.push(`error="${error.oauthError}"`, `error_description="${error.message.replace(/"/g, "'")}"`);
123
+ }
124
+ if (error?.oauthError === "insufficient_scope" && config.oauth?.requiredScopes.length) {
125
+ parts.push(`scope="${config.oauth.requiredScopes.join(" ")}"`);
126
+ }
127
+ return parts.join(", ");
128
+ };
129
+ const closeSession = (sessionId, reason) => {
130
+ const session = sessions.get(sessionId);
131
+ if (!session)
132
+ return;
133
+ sessions.delete(sessionId);
134
+ try {
135
+ options.onSessionClosed?.(sessionId);
136
+ }
137
+ catch (error) {
138
+ console.error(`Session ${sessionId} cleanup failed: ${error.message}`);
139
+ }
140
+ auditLogger.log({ event: "session_closed", session: sessionId, client: session.clientId, reason });
141
+ // server.close() closes the transport, whose onclose re-enters here as a no-op
142
+ session.server.close().catch(() => undefined);
143
+ };
144
+ const findSession = (req, res, authInfo) => {
145
+ const header = req.headers["mcp-session-id"];
146
+ const sessionId = Array.isArray(header) ? header[0] : header;
147
+ if (!sessionId) {
148
+ sendJson(res, 400, jsonRpcError(-32000, "Bad Request: Mcp-Session-Id header is required"));
149
+ return undefined;
150
+ }
151
+ const session = sessions.get(sessionId);
152
+ if (!session) {
153
+ sendJson(res, 404, jsonRpcError(-32001, "Session not found"));
154
+ return undefined;
155
+ }
156
+ if (session.clientId !== authInfo.clientId) {
157
+ sendJson(res, 403, jsonRpcError(-32000, "Forbidden: session belongs to another client"));
158
+ return undefined;
159
+ }
160
+ session.lastSeen = Date.now();
161
+ return session;
162
+ };
163
+ const startSession = async (req, res, authInfo, body) => {
164
+ if (config.maxSessions > 0 && sessions.size >= config.maxSessions) {
165
+ sendJson(res, 503, jsonRpcError(-32000, "Too many active sessions, try again later"), { "Retry-After": "60" });
166
+ return;
167
+ }
168
+ const server = createServer();
169
+ const transport = new streamableHttp_js_1.StreamableHTTPServerTransport({
170
+ sessionIdGenerator: () => (0, crypto_1.randomUUID)(),
171
+ onsessioninitialized: (sessionId) => {
172
+ sessions.set(sessionId, { transport, server, clientId: authInfo.clientId, lastSeen: Date.now() });
173
+ auditLogger.log({
174
+ event: "session_opened",
175
+ session: sessionId,
176
+ client: authInfo.clientId,
177
+ ip: authInfo.extra?.clientIp,
178
+ });
179
+ },
180
+ onsessionclosed: (sessionId) => closeSession(sessionId, "deleted by client"),
181
+ });
182
+ transport.onclose = () => {
183
+ if (transport.sessionId)
184
+ closeSession(transport.sessionId, "transport closed");
185
+ };
186
+ await server.connect(transport);
187
+ req.auth = authInfo;
188
+ await transport.handleRequest(req, res, body);
189
+ // A rejected initialize never creates a session; release its server
190
+ if (!transport.sessionId || !sessions.has(transport.sessionId)) {
191
+ await server.close().catch(() => undefined);
192
+ }
193
+ };
194
+ const handleMcpRequest = async (req, res, clientIp) => {
195
+ let authInfo;
196
+ try {
197
+ authInfo = await authenticator.authenticate(req.headers.authorization);
198
+ }
199
+ catch (error) {
200
+ if (!(error instanceof auth_1.AuthError))
201
+ throw error;
202
+ auditLogger.log({ event: "auth_failed", ip: clientIp, reason: error.message });
203
+ sendJson(res, error.status, { error: error.oauthError, error_description: error.message }, { "WWW-Authenticate": authenticateHeader(error) });
204
+ return;
205
+ }
206
+ authInfo = { ...authInfo, extra: { ...(authInfo.extra || {}), clientIp } };
207
+ if (req.method === "POST") {
208
+ let body;
209
+ try {
210
+ body = await readJsonBody(req, config.maxBodyBytes);
211
+ }
212
+ catch (error) {
213
+ const status = error instanceof RequestBodyError ? error.status : 400;
214
+ sendJson(res, status, jsonRpcError(status === 413 ? -32000 : -32700, error.message), { Connection: "close" });
215
+ if (status === 413)
216
+ res.on("finish", () => req.destroy());
217
+ return;
218
+ }
219
+ if (req.headers["mcp-session-id"]) {
220
+ const session = findSession(req, res, authInfo);
221
+ if (!session)
222
+ return;
223
+ req.auth = authInfo;
224
+ await session.transport.handleRequest(req, res, body);
225
+ return;
226
+ }
227
+ const initializing = Array.isArray(body) ? body.some(types_js_1.isInitializeRequest) : (0, types_js_1.isInitializeRequest)(body);
228
+ if (!initializing) {
229
+ sendJson(res, 400, jsonRpcError(-32000, "Bad Request: No valid session ID provided"));
230
+ return;
231
+ }
232
+ await startSession(req, res, authInfo, body);
233
+ return;
234
+ }
235
+ if (req.method === "GET" || req.method === "DELETE") {
236
+ const session = findSession(req, res, authInfo);
237
+ if (!session)
238
+ return;
239
+ req.auth = authInfo;
240
+ await session.transport.handleRequest(req, res);
241
+ return;
242
+ }
243
+ sendJson(res, 405, jsonRpcError(-32000, "Method not allowed"), { Allow: "GET, POST, DELETE, OPTIONS" });
244
+ };
245
+ const handleRequest = async (req, res) => {
246
+ const pathname = (new URL(req.url || "/", "http://localhost").pathname.replace(/\/+$/, "") || "/");
247
+ if (pathname === "/health" && req.method === "GET") {
248
+ sendJson(res, 200, { status: "ok" });
249
+ return;
250
+ }
251
+ // DNS-rebinding protection: reject unexpected Host and Origin headers
252
+ if (!isHostAllowed(req.headers.host)) {
253
+ sendJson(res, 403, jsonRpcError(-32000, "Forbidden: Host header is not allowed"));
254
+ return;
255
+ }
256
+ const origin = req.headers.origin;
257
+ if (origin) {
258
+ if (!isOriginAllowed(origin)) {
259
+ sendJson(res, 403, jsonRpcError(-32000, "Forbidden: Origin is not allowed"));
260
+ return;
261
+ }
262
+ setCorsHeaders(res, origin);
263
+ }
264
+ if (req.method === "OPTIONS") {
265
+ res.writeHead(204);
266
+ res.end();
267
+ return;
268
+ }
269
+ if (config.auth === "oauth" && req.method === "GET" && metadataPaths.has(pathname)) {
270
+ sendJson(res, 200, (0, auth_1.protectedResourceMetadata)(config));
271
+ return;
272
+ }
273
+ if (pathname !== config.path) {
274
+ sendJson(res, 404, { error: "Not found" });
275
+ return;
276
+ }
277
+ await handleMcpRequest(req, res, clientIpOf(req));
278
+ };
279
+ const server = http_1.default.createServer((req, res) => {
280
+ handleRequest(req, res).catch((error) => {
281
+ console.error(`HTTP request failed: ${error?.message || error}`);
282
+ sendJson(res, 500, jsonRpcError(-32603, "Internal server error"));
283
+ });
284
+ });
285
+ const sweepInterval = Math.max(1000, Math.min(60 * 1000, config.sessionIdleTimeoutMs || 60 * 1000));
286
+ const sweeper = setInterval(() => {
287
+ if (config.sessionIdleTimeoutMs <= 0)
288
+ return;
289
+ const now = Date.now();
290
+ for (const [sessionId, session] of sessions) {
291
+ if (now - session.lastSeen > config.sessionIdleTimeoutMs)
292
+ closeSession(sessionId, "idle timeout");
293
+ }
294
+ }, sweepInterval);
295
+ sweeper.unref();
296
+ await new Promise((resolve, reject) => {
297
+ server.once("error", reject);
298
+ server.listen(config.port, config.host, () => {
299
+ server.off("error", reject);
300
+ resolve();
301
+ });
302
+ });
303
+ const address = server.address();
304
+ const port = typeof address === "object" && address ? address.port : config.port;
305
+ const displayHost = config.host.includes(":") ? `[${config.host}]` : config.host;
306
+ return {
307
+ server,
308
+ url: `http://${displayHost}:${port}${config.path}`,
309
+ sessionCount: () => sessions.size,
310
+ close: async () => {
311
+ clearInterval(sweeper);
312
+ for (const sessionId of [...sessions.keys()])
313
+ closeSession(sessionId, "server shutdown");
314
+ const closed = new Promise((resolve) => server.close(() => resolve()));
315
+ server.closeAllConnections();
316
+ await closed;
317
+ },
318
+ };
319
+ };
320
+ exports.startHttpServer = startHttpServer;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Sliding-window limiter: at most `limit` events per key in any 60 s window.
3
+ * A limit of 0 disables it.
4
+ */
5
+ export declare class RateLimiter {
6
+ private readonly limit;
7
+ private readonly now;
8
+ private readonly hits;
9
+ constructor(limit: number, now?: () => number);
10
+ get enabled(): boolean;
11
+ /** Records a hit; returns 0 when allowed, otherwise the milliseconds until the next slot frees up. */
12
+ consume(key: string): number;
13
+ /** Drops keys with no hits in the current window. */
14
+ prune(): void;
15
+ }
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RateLimiter = void 0;
4
+ const WINDOW_MS = 60 * 1000;
5
+ /**
6
+ * Sliding-window limiter: at most `limit` events per key in any 60 s window.
7
+ * A limit of 0 disables it.
8
+ */
9
+ class RateLimiter {
10
+ constructor(limit, now = Date.now) {
11
+ this.limit = limit;
12
+ this.now = now;
13
+ this.hits = new Map();
14
+ }
15
+ get enabled() {
16
+ return this.limit > 0;
17
+ }
18
+ /** Records a hit; returns 0 when allowed, otherwise the milliseconds until the next slot frees up. */
19
+ consume(key) {
20
+ if (!this.enabled)
21
+ return 0;
22
+ const now = this.now();
23
+ const recent = (this.hits.get(key) || []).filter((time) => now - time < WINDOW_MS);
24
+ if (recent.length >= this.limit) {
25
+ this.hits.set(key, recent);
26
+ return WINDOW_MS - (now - recent[0]);
27
+ }
28
+ recent.push(now);
29
+ this.hits.set(key, recent);
30
+ return 0;
31
+ }
32
+ /** Drops keys with no hits in the current window. */
33
+ prune() {
34
+ const now = this.now();
35
+ for (const [key, times] of this.hits) {
36
+ if (times.every((time) => now - time >= WINDOW_MS))
37
+ this.hits.delete(key);
38
+ }
39
+ }
40
+ }
41
+ exports.RateLimiter = RateLimiter;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Identity of the caller for the tool call currently executing. Over stdio
3
+ * there is a single local caller and no session id.
4
+ */
5
+ export interface RequestContext {
6
+ transport: "stdio" | "http";
7
+ sessionId?: string;
8
+ clientId?: string;
9
+ clientIp?: string;
10
+ }
11
+ export declare const runWithRequestContext: <T>(context: RequestContext, fn: () => Promise<T>) => Promise<T>;
12
+ export declare const getRequestContext: () => RequestContext | undefined;
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getRequestContext = exports.runWithRequestContext = void 0;
4
+ const async_hooks_1 = require("async_hooks");
5
+ const storage = new async_hooks_1.AsyncLocalStorage();
6
+ const runWithRequestContext = (context, fn) => storage.run(context, fn);
7
+ exports.runWithRequestContext = runWithRequestContext;
8
+ const getRequestContext = () => storage.getStore();
9
+ exports.getRequestContext = getRequestContext;
@@ -78,7 +78,9 @@ export declare class MaintenanceTools {
78
78
  error?: string;
79
79
  }>;
80
80
  /**
81
- * Flush table (close and reopen)
81
+ * Flush table(s) of the connected database (close and reopen).
82
+ * WITH READ LOCK is not supported: the lock would stay on a pooled
83
+ * connection and, without a table name, block writes server-wide.
82
84
  */
83
85
  flushTable(params: {
84
86
  table_name?: string;
@@ -252,7 +252,9 @@ class MaintenanceTools {
252
252
  }
253
253
  }
254
254
  /**
255
- * Flush table (close and reopen)
255
+ * Flush table(s) of the connected database (close and reopen).
256
+ * WITH READ LOCK is not supported: the lock would stay on a pooled
257
+ * connection and, without a table name, block writes server-wide.
256
258
  */
257
259
  async flushTable(params) {
258
260
  try {
@@ -262,25 +264,35 @@ class MaintenanceTools {
262
264
  }
263
265
  const { table_name, with_read_lock = false } = params;
264
266
  const database = dbValidation.database;
265
- let query;
267
+ if (with_read_lock) {
268
+ return {
269
+ status: "error",
270
+ error: "with_read_lock is not supported: the read lock would outlive this call on a pooled connection.",
271
+ };
272
+ }
273
+ let tableNames;
266
274
  if (table_name) {
267
275
  if (!this.security.validateIdentifier(table_name).valid) {
268
276
  return { status: "error", error: "Invalid table name" };
269
277
  }
270
- query = `FLUSH TABLES \`${database}\`.\`${table_name}\``;
271
- if (with_read_lock) {
272
- query += " WITH READ LOCK";
273
- }
278
+ tableNames = [table_name];
274
279
  }
275
280
  else {
276
- query = with_read_lock ? "FLUSH TABLES WITH READ LOCK" : "FLUSH TABLES";
281
+ // Flush only the connected database, never every table on the server
282
+ const rows = await this.db.query("SELECT TABLE_NAME AS table_name FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_TYPE = 'BASE TABLE'", [database]);
283
+ tableNames = rows.map((row) => row.table_name);
284
+ }
285
+ if (tableNames.length > 0) {
286
+ const tableList = tableNames
287
+ .map((name) => `\`${database}\`.\`${name.replace(/`/g, "``")}\``)
288
+ .join(", ");
289
+ await this.db.query(`FLUSH TABLES ${tableList}`);
277
290
  }
278
- await this.db.query(query);
279
291
  return {
280
292
  status: "success",
281
293
  message: table_name
282
- ? `Table '${table_name}' flushed successfully${with_read_lock ? " with read lock" : ""}`
283
- : `All tables flushed successfully${with_read_lock ? " with read lock" : ""}`,
294
+ ? `Table '${table_name}' flushed successfully`
295
+ : `${tableNames.length} table(s) in '${database}' flushed successfully`,
284
296
  };
285
297
  }
286
298
  catch (error) {
@@ -61,6 +61,15 @@ class QueryTools {
61
61
  if (finalQuery !== query) {
62
62
  optimizedQuery = finalQuery;
63
63
  }
64
+ // Hints change the SQL after validation, so validate the result too.
65
+ // The optimizer hint comment is the only comment allowed through.
66
+ const hintedValidation = this.security.validateQuery(finalQuery.replace(/\/\*\+[^*]*\*\//, " "), hasExecutePermission);
67
+ if (!hintedValidation.valid || hintedValidation.queryType !== "SELECT") {
68
+ return {
69
+ status: "error",
70
+ error: `Query validation failed after applying hints: ${hintedValidation.error || "Only SELECT queries are allowed"}`,
71
+ };
72
+ }
64
73
  }
65
74
  // Handle dry_run: return query plan and cost estimate without executing
66
75
  if (queryParams.dry_run) {
@@ -0,0 +1,4 @@
1
+ import { Tool, ToolAnnotations } from "@modelcontextprotocol/sdk/types.js";
2
+ export declare const getToolAnnotations: (name: string) => ToolAnnotations;
3
+ export declare const hasExplicitAnnotations: (name: string) => boolean;
4
+ export declare const withToolAnnotations: (tools: Tool[]) => Tool[];
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withToolAnnotations = exports.hasExplicitAnnotations = exports.getToolAnnotations = void 0;
4
+ // Reads only: no data, schema, or server state changes
5
+ const READ_TOOLS = [
6
+ "list_databases", "list_tables", "get_database_summary", "get_schema_erd",
7
+ "get_schema_rag_context", "find_tables_by_keyword", "search_schema",
8
+ "search_data_across_tables", "get_column_statistics", "read_table_schema",
9
+ "read_records", "plan_seed_data", "generate_seed_preview",
10
+ "validate_seed_integrity", "infer_seed_rules", "seed_from_template",
11
+ "run_select_query", "repair_query", "describe_connection", "read_changelog",
12
+ "test_connection", "list_all_tools", "get_all_tables_relationships",
13
+ "get_transaction_status", "list_stored_procedures", "get_stored_procedure_info",
14
+ "show_create_procedure", "export_table_to_csv", "export_query_to_csv",
15
+ "analyze_query", "get_optimization_hints", "list_views", "get_view_info",
16
+ "show_create_view", "list_triggers", "get_trigger_info", "show_create_trigger",
17
+ "list_indexes", "get_index_info", "list_foreign_keys", "list_constraints",
18
+ "check_table", "get_table_status", "get_table_size", "fulltext_search",
19
+ "get_fulltext_info", "get_fulltext_stats",
20
+ ];
21
+ // Change state but only add to it or maintain it; existing data is kept
22
+ const WRITE_TOOLS = [
23
+ "create_record", "bulk_insert", "execute_seed_plan", "begin_transaction",
24
+ "rollback_transaction", "create_table", "create_trigger", "create_index",
25
+ "add_foreign_key", "add_unique_constraint", "add_check_constraint",
26
+ "create_stored_procedure", "create_fulltext_index",
27
+ ];
28
+ // Maintenance statements that leave the same state when repeated
29
+ const IDEMPOTENT_WRITE_TOOLS = [
30
+ "analyze_table", "analyze_index", "optimize_table", "flush_table", "optimize_fulltext",
31
+ ];
32
+ // May overwrite or remove data or schema objects, or run arbitrary statements
33
+ const DESTRUCTIVE_TOOLS = [
34
+ "update_record", "delete_record", "bulk_update", "bulk_delete",
35
+ "execute_write_query", "alter_table", "drop_table", "execute_ddl",
36
+ "cursor_execute_request", "commit_transaction", "execute_in_transaction",
37
+ "execute_stored_procedure", "drop_stored_procedure", "create_view",
38
+ "alter_view", "drop_view", "drop_trigger", "drop_index", "drop_foreign_key",
39
+ "drop_constraint", "repair_table", "truncate_table", "drop_fulltext_index",
40
+ ];
41
+ const behaviors = new Map();
42
+ for (const name of READ_TOOLS)
43
+ behaviors.set(name, { behavior: "read", idempotent: true });
44
+ for (const name of WRITE_TOOLS)
45
+ behaviors.set(name, { behavior: "write", idempotent: false });
46
+ for (const name of IDEMPOTENT_WRITE_TOOLS)
47
+ behaviors.set(name, { behavior: "write", idempotent: true });
48
+ for (const name of DESTRUCTIVE_TOOLS)
49
+ behaviors.set(name, { behavior: "destructive", idempotent: false });
50
+ const ACRONYMS = { csv: "CSV", erd: "ERD", rag: "RAG", ddl: "DDL" };
51
+ const toTitle = (name) => name
52
+ .split("_")
53
+ .map((word) => ACRONYMS[word] || word.charAt(0).toUpperCase() + word.slice(1))
54
+ .join(" ");
55
+ const getToolAnnotations = (name) => {
56
+ // Unknown tools are treated as destructive, the safest hint
57
+ const entry = behaviors.get(name) || { behavior: "destructive", idempotent: false };
58
+ return {
59
+ title: toTitle(name),
60
+ readOnlyHint: entry.behavior === "read",
61
+ destructiveHint: entry.behavior === "destructive",
62
+ idempotentHint: entry.idempotent,
63
+ openWorldHint: false,
64
+ };
65
+ };
66
+ exports.getToolAnnotations = getToolAnnotations;
67
+ const hasExplicitAnnotations = (name) => behaviors.has(name);
68
+ exports.hasExplicitAnnotations = hasExplicitAnnotations;
69
+ const withToolAnnotations = (tools) => tools.map((tool) => ({
70
+ ...tool,
71
+ annotations: { ...(0, exports.getToolAnnotations)(tool.name), ...(tool.annotations || {}) },
72
+ }));
73
+ exports.withToolAnnotations = withToolAnnotations;
package/manifest.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "mysql-mcp",
3
3
  "description": "A Model Context Protocol for MySQL database interaction",
4
- "version": "1.44.0",
4
+ "version": "1.46.0",
5
5
  "tools": [
6
6
  {
7
7
  "name": "list_databases",
@@ -2660,7 +2660,7 @@
2660
2660
  },
2661
2661
  {
2662
2662
  "name": "optimize_table",
2663
- "description": "Optimizes a table to reclaim unused space and defragment data.",
2663
+ "description": "Optimizes a table to reclaim unused space and defragment data. Rebuilds the table, so it requires 'ddl' permission.",
2664
2664
  "input_schema": {
2665
2665
  "type": "object",
2666
2666
  "properties": {
@@ -2717,7 +2717,7 @@
2717
2717
  },
2718
2718
  {
2719
2719
  "name": "repair_table",
2720
- "description": "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only).",
2720
+ "description": "Repairs a corrupted table (MyISAM, ARCHIVE, CSV only). Requires 'ddl' permission.",
2721
2721
  "input_schema": {
2722
2722
  "type": "object",
2723
2723
  "properties": {
@@ -2795,17 +2795,13 @@
2795
2795
  },
2796
2796
  {
2797
2797
  "name": "flush_table",
2798
- "description": "Flushes table(s) - closes and reopens them.",
2798
+ "description": "Flushes table(s) in the connected database - closes and reopens them. Requires 'ddl' permission.",
2799
2799
  "input_schema": {
2800
2800
  "type": "object",
2801
2801
  "properties": {
2802
2802
  "table_name": {
2803
2803
  "type": "string",
2804
- "description": "Optional: specific table (omit for all tables)"
2805
- },
2806
- "with_read_lock": {
2807
- "type": "boolean",
2808
- "description": "Acquire read lock after flushing"
2804
+ "description": "Optional: specific table (omit for all tables in the connected database)"
2809
2805
  },
2810
2806
  "database": {
2811
2807
  "type": "string",
@@ -3028,7 +3024,7 @@
3028
3024
  },
3029
3025
  {
3030
3026
  "name": "optimize_fulltext",
3031
- "description": "Optimizes a table to update FULLTEXT index statistics and reclaim space. Use this after bulk inserts or updates to improve search performance.",
3027
+ "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.",
3032
3028
  "input_schema": {
3033
3029
  "type": "object",
3034
3030
  "properties": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@berthojoris/mcp-mysql-server",
3
- "version": "1.44.0",
3
+ "version": "1.46.0",
4
4
  "description": "Model Context Protocol server for MySQL database integration with dynamic per-project permissions",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",