@ecubelabs/mysql-mcp 1.0.0-next.7 → 1.0.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.
- package/README.md +296 -448
- package/dist/index.js +377 -239
- package/dist/src/catalog/collect.js +3 -2
- package/dist/src/catalog/docs.js +14 -12
- package/dist/src/catalog/index.js +59 -99
- package/dist/src/catalog/render.js +4 -10
- package/dist/src/catalog/store.js +193 -76
- package/dist/src/catalog/types.js +0 -12
- package/dist/src/config/index.js +175 -0
- package/dist/src/db/index.js +379 -379
- package/dist/src/db/permissions.js +32 -16
- package/dist/src/db/utils.js +3 -1
- package/dist/src/ssh/config.js +34 -27
- package/dist/src/ssh/tunnel.js +238 -155
- package/dist/src/utils/index.js +4 -35
- package/package.json +4 -4
- package/dist/src/catalog/context.js +0 -187
- package/dist/src/catalog/lock.js +0 -113
- package/dist/src/config/args.js +0 -30
- package/dist/src/config/load.js +0 -169
- package/dist/src/config/schema.js +0 -351
- package/dist/src/config/secrets.js +0 -128
- package/dist/src/config/ssl.js +0 -25
- package/dist/src/db/registry.js +0 -178
- package/dist/src/init/check.js +0 -31
- package/dist/src/init/cli.js +0 -26
- package/dist/src/init/config-edit.js +0 -95
- package/dist/src/init/prompt.js +0 -82
- package/dist/src/init/wizard.js +0 -223
- package/dist/src/server/catalog-tool.js +0 -91
- package/dist/src/server/connections.js +0 -117
package/dist/index.js
CHANGED
|
@@ -1,23 +1,54 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { fileURLToPath } from 'url';
|
|
3
3
|
import { realpathSync } from 'fs';
|
|
4
|
-
import * as path from 'path';
|
|
5
4
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
6
5
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
7
6
|
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
8
|
-
import { log,
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import { codeBranchToolInstruction } from './src/catalog/branch.js';
|
|
13
|
-
import { ContextStore } from './src/catalog/context.js';
|
|
7
|
+
import { log, sharedOnce, tableResourceUri } from './src/utils/index.js';
|
|
8
|
+
import { writeCapabilities } from './src/db/permissions.js';
|
|
9
|
+
import { SCHEMA_DELETE_PERMISSIONS, SCHEMA_DDL_PERMISSIONS, SCHEMA_INSERT_PERMISSIONS, SCHEMA_UPDATE_PERMISSIONS, isMultiDbMode, mcpConfig as config, MYSQL_PROFILE, PROFILE_LABEL, IS_WRITE_FORBIDDEN_PROFILE, MYSQL_CATALOG_ENABLED, MYSQL_CATALOG_PATH, MYSQL_CATALOG_TTL_HOURS, MYSQL_DEFAULT_TIMEOUT_SECONDS, MYSQL_MAX_TIMEOUT_SECONDS, MAX_RESPONSE_ROWS, MYSQL_SSL_ENABLED, MYSQL_SSL_CA_PATH, MYSQL_SSL_CERT_PATH, MYSQL_SSL_KEY_PATH, PACKAGE_VERSION, SSH_ENABLED, } from './src/config/index.js';
|
|
10
|
+
import { codeBranchToolInstruction, codeRevisionDescription } from './src/catalog/branch.js';
|
|
14
11
|
import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
|
|
15
12
|
import { renderSchemasResource } from './src/catalog/render.js';
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
const
|
|
13
|
+
import { describeConnection, getPool, executeQuery, executeReadOnlyQuery, setQueryDiagnosticsSource, setCodeBranchSource, clampTimeoutSeconds, describeQueryError, poolPromise, profileBanner, } from './src/db/index.js';
|
|
14
|
+
import { describeTunnel, ensureTunnel, resolveTunnelConfig, stopTunnel } from './src/ssh/tunnel.js';
|
|
15
|
+
log('info', `Starting MySQL MCP server v${PACKAGE_VERSION}...`);
|
|
16
|
+
const toolVersion = `MySQL MCP Server [v${PACKAGE_VERSION}]`;
|
|
17
|
+
const TOOL_DESCRIPTION_LIMIT = 2048;
|
|
18
|
+
let baseToolDescription = `[${toolVersion}] Run SQL queries against the ${PROFILE_LABEL} MySQL database`;
|
|
19
|
+
if (MYSQL_PROFILE) {
|
|
20
|
+
baseToolDescription += IS_WRITE_FORBIDDEN_PROFILE
|
|
21
|
+
? ` — ENVIRONMENT: ${PROFILE_LABEL}, STRICTLY READ-ONLY (writes are refused by policy)`
|
|
22
|
+
: ` — ENVIRONMENT: ${PROFILE_LABEL}`;
|
|
23
|
+
}
|
|
24
|
+
if (isMultiDbMode) {
|
|
25
|
+
baseToolDescription += ' (Multi-DB mode enabled)';
|
|
26
|
+
}
|
|
27
|
+
const writes = writeCapabilities();
|
|
28
|
+
if (writes.length > 0) {
|
|
29
|
+
const supported = writes.map(({ label, schemas }) => (schemas ? `${label} (${schemas.join(', ')} only)` : label));
|
|
30
|
+
baseToolDescription += ` with support for: ${supported.join(', ')} and READ operations`;
|
|
31
|
+
if (Object.keys(SCHEMA_INSERT_PERMISSIONS).length > 0 ||
|
|
32
|
+
Object.keys(SCHEMA_UPDATE_PERMISSIONS).length > 0 ||
|
|
33
|
+
Object.keys(SCHEMA_DELETE_PERMISSIONS).length > 0 ||
|
|
34
|
+
Object.keys(SCHEMA_DDL_PERMISSIONS).length > 0) {
|
|
35
|
+
baseToolDescription += ' (Schema-specific permissions enabled)';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
baseToolDescription += ' (READ-ONLY)';
|
|
40
|
+
}
|
|
41
|
+
baseToolDescription +=
|
|
42
|
+
`\n\nLIMITS: every read is cancelled after ${MYSQL_DEFAULT_TIMEOUT_SECONDS}s ` +
|
|
43
|
+
`(raise per call with timeout_seconds, up to ${MYSQL_MAX_TIMEOUT_SECONDS}) and returns at most ` +
|
|
44
|
+
`${MAX_RESPONSE_ROWS.toLocaleString('en-US')} rows. Aggregate in SQL rather than pulling rows to count them. ` +
|
|
45
|
+
`USE and SET are rejected; write schema.table instead of USE. ` +
|
|
46
|
+
`Executable comments (/*! ... */) and MAX_EXECUTION_TIME or SET_VAR hints are rejected; use timeout_seconds instead.`;
|
|
47
|
+
baseToolDescription +=
|
|
48
|
+
'\n\nQualify every table with its schema (schema.table). ' +
|
|
49
|
+
'A schema name that is not a bare identifier must be backtick-quoted, e.g. SELECT ... FROM `my-schema`.some_table.';
|
|
50
|
+
const isReadOnly = writes.length === 0;
|
|
51
|
+
const mysqlCatalogTool = {
|
|
21
52
|
name: 'mysql_catalog',
|
|
22
53
|
description: 'Read the local schema catalog without rediscovering database metadata. ' +
|
|
23
54
|
'Use map for the app/schema overview, search to find tables or known columns, ' +
|
|
@@ -28,17 +59,13 @@ const MYSQL_CATALOG_TOOL = {
|
|
|
28
59
|
'Use branch to record which branch of a GitHub repository matches this database, once ' +
|
|
29
60
|
'the user confirmed it. ' +
|
|
30
61
|
'Use owner to record which repository and app own a schema, once the user confirmed it. ' +
|
|
31
|
-
'Use note to save a table memo or alias,
|
|
62
|
+
'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
|
|
32
63
|
'Use refresh when cached metadata contradicts what a query actually returned, ' +
|
|
33
64
|
'or right after a migration: added columns and indexes raise no error, so ' +
|
|
34
65
|
'nothing else invalidates them.',
|
|
35
66
|
inputSchema: {
|
|
36
67
|
type: 'object',
|
|
37
68
|
properties: {
|
|
38
|
-
connection: {
|
|
39
|
-
type: 'string',
|
|
40
|
-
description: 'Connection whose catalog to read or update. Listed in the mysql_query description.',
|
|
41
|
-
},
|
|
42
69
|
action: {
|
|
43
70
|
type: 'string',
|
|
44
71
|
enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'owner', 'note', 'forget', 'refresh'],
|
|
@@ -79,14 +106,14 @@ const MYSQL_CATALOG_TOOL = {
|
|
|
79
106
|
},
|
|
80
107
|
target: {
|
|
81
108
|
type: 'string',
|
|
82
|
-
description: 'Qualified schema.table for note or forget
|
|
109
|
+
description: 'Qualified schema.table for note or forget. Schema name for owner. For refresh: ' +
|
|
83
110
|
'"schema.table" for one table\'s columns, indexes and foreign keys; a schema name for the ' +
|
|
84
111
|
'table inventory. Omit it to refresh the inventory.',
|
|
85
112
|
},
|
|
86
113
|
text: {
|
|
87
114
|
type: 'string',
|
|
88
115
|
maxLength: 1000,
|
|
89
|
-
description: '
|
|
116
|
+
description: 'Table memo to add with note; use either text or alias',
|
|
90
117
|
},
|
|
91
118
|
alias: {
|
|
92
119
|
type: 'string',
|
|
@@ -125,7 +152,7 @@ const MYSQL_CATALOG_TOOL = {
|
|
|
125
152
|
},
|
|
126
153
|
},
|
|
127
154
|
},
|
|
128
|
-
required: ['
|
|
155
|
+
required: ['action'],
|
|
129
156
|
},
|
|
130
157
|
annotations: {
|
|
131
158
|
readOnlyHint: false,
|
|
@@ -135,107 +162,91 @@ const MYSQL_CATALOG_TOOL = {
|
|
|
135
162
|
title: 'MySQL Schema Catalog',
|
|
136
163
|
},
|
|
137
164
|
};
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
165
|
+
const mysqlQueryInputSchema = {
|
|
166
|
+
type: 'object',
|
|
167
|
+
properties: {
|
|
168
|
+
sql: {
|
|
169
|
+
type: 'string',
|
|
170
|
+
description: 'The SQL query to execute',
|
|
171
|
+
},
|
|
172
|
+
timeout_seconds: {
|
|
173
|
+
type: 'integer',
|
|
174
|
+
minimum: 1,
|
|
175
|
+
maximum: MYSQL_MAX_TIMEOUT_SECONDS,
|
|
176
|
+
description: `Server-side execution limit in seconds (default ${MYSQL_DEFAULT_TIMEOUT_SECONDS}, ` +
|
|
177
|
+
`maximum ${MYSQL_MAX_TIMEOUT_SECONDS}; out-of-range values are clamped). ` +
|
|
178
|
+
`Raise it only when a cancelled query's plan looked sound and the query was merely slow. ` +
|
|
179
|
+
`A query the plan shows scanning a whole table does not finish sooner with more time.`,
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
required: ['sql'],
|
|
183
|
+
};
|
|
184
|
+
log('info', 'MySQL Configuration:', JSON.stringify({
|
|
185
|
+
connection: describeConnection(),
|
|
186
|
+
user: config.mysql.user,
|
|
187
|
+
password: config.mysql.password ? '******' : 'not set',
|
|
188
|
+
database: config.mysql.database || 'MULTI_DB_MODE',
|
|
189
|
+
ssl: MYSQL_SSL_ENABLED ? 'enabled' : 'disabled',
|
|
190
|
+
sslCA: MYSQL_SSL_CA_PATH ?? 'not set',
|
|
191
|
+
sslCert: MYSQL_SSL_CERT_PATH ?? 'not set',
|
|
192
|
+
sslKey: MYSQL_SSL_KEY_PATH ?? 'not set',
|
|
193
|
+
multiDbMode: isMultiDbMode ? 'enabled' : 'disabled',
|
|
194
|
+
profile: PROFILE_LABEL,
|
|
195
|
+
writePolicy: IS_WRITE_FORBIDDEN_PROFILE
|
|
196
|
+
? 'read-only (enforced by profile)'
|
|
197
|
+
: isReadOnly
|
|
198
|
+
? 'read-only'
|
|
199
|
+
: 'writes enabled',
|
|
200
|
+
sshTunnel: SSH_ENABLED ? describeTunnel() : 'disabled',
|
|
201
|
+
}, null, 2));
|
|
202
|
+
export default function createMcpServer() {
|
|
203
|
+
const mysqlSettings = config.mysql;
|
|
204
|
+
const catalogTarget = SSH_ENABLED
|
|
205
|
+
? (() => {
|
|
206
|
+
const tunnel = resolveTunnelConfig();
|
|
207
|
+
return JSON.stringify(['tcp', tunnel.remoteHost, tunnel.remotePort]);
|
|
208
|
+
})()
|
|
209
|
+
: typeof mysqlSettings.socketPath === 'string'
|
|
210
|
+
? JSON.stringify(['unix', mysqlSettings.socketPath])
|
|
211
|
+
: JSON.stringify(['tcp', String(mysqlSettings.host ?? '127.0.0.1'), Number(mysqlSettings.port ?? 3306)]);
|
|
212
|
+
const identity = catalogIdentity({
|
|
213
|
+
profile: MYSQL_PROFILE,
|
|
214
|
+
target: catalogTarget,
|
|
215
|
+
user: String(mysqlSettings.user ?? ''),
|
|
216
|
+
customPath: MYSQL_CATALOG_PATH,
|
|
217
|
+
});
|
|
218
|
+
const catalog = new SchemaCatalog({
|
|
219
|
+
enabled: MYSQL_CATALOG_ENABLED,
|
|
220
|
+
profile: MYSQL_PROFILE || 'default',
|
|
221
|
+
fingerprint: identity.fingerprint,
|
|
222
|
+
filePath: identity.filePath,
|
|
223
|
+
ttlHours: MYSQL_CATALOG_TTL_HOURS,
|
|
224
|
+
defaultSchema: typeof mysqlSettings.database === 'string' ? mysqlSettings.database : null,
|
|
225
|
+
});
|
|
226
|
+
setQueryDiagnosticsSource({
|
|
227
|
+
indexFacts: (reference) => catalog.indexFacts(reference),
|
|
172
228
|
});
|
|
173
|
-
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
connections: runtimes.map((rt) => ({
|
|
180
|
-
name: rt.name,
|
|
181
|
-
target: rt.db.describeConnection(),
|
|
182
|
-
user: rt.spec.user,
|
|
183
|
-
database: rt.spec.database ?? null,
|
|
184
|
-
})),
|
|
185
|
-
writePolicy: env.writeForbidden
|
|
186
|
-
? 'read-only (enforced by environment)'
|
|
187
|
-
: readOnly
|
|
188
|
-
? 'read-only'
|
|
189
|
-
: 'per connection',
|
|
190
|
-
}, null, 2));
|
|
191
|
-
const initialDescription = queryToolDescription(env, runtimes, PACKAGE_VERSION);
|
|
192
|
-
if (initialDescription.overflow > 0) {
|
|
193
|
-
console.error(`[warn] tool description is ${initialDescription.overflow} characters over the ${TOOL_DESCRIPTION_LIMIT}-character ` +
|
|
194
|
-
`limit clients keep; they silently drop the rest. Use fewer connections or record fewer code branches.`);
|
|
229
|
+
setCodeBranchSource(() => catalog.codeBranchSummary());
|
|
230
|
+
const queryBaseDescription = baseToolDescription + codeRevisionDescription(catalog.codeBranches());
|
|
231
|
+
if (queryBaseDescription.length > TOOL_DESCRIPTION_LIMIT) {
|
|
232
|
+
console.error(`[warn] tool description is ${queryBaseDescription.length} characters before the ` +
|
|
233
|
+
`catalog tail; clients keep ${TOOL_DESCRIPTION_LIMIT} and silently drop the rest. ` +
|
|
234
|
+
`Record fewer code branches, or shorten the text in index.ts.`);
|
|
195
235
|
}
|
|
196
|
-
const
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
description: 'Connection to run against. Each one is a database account; see CONNECTIONS above.',
|
|
200
|
-
};
|
|
201
|
-
const queryInputSchema = {
|
|
202
|
-
type: 'object',
|
|
203
|
-
properties: {
|
|
204
|
-
connection: connectionProperty,
|
|
205
|
-
sql: {
|
|
206
|
-
type: 'string',
|
|
207
|
-
description: 'The SQL query to execute',
|
|
208
|
-
},
|
|
209
|
-
timeout_seconds: {
|
|
210
|
-
type: 'integer',
|
|
211
|
-
minimum: 1,
|
|
212
|
-
maximum: env.defaults.maxTimeoutSeconds,
|
|
213
|
-
description: `Server-side execution limit in seconds (default ${env.defaults.defaultTimeoutSeconds}, ` +
|
|
214
|
-
`maximum ${env.defaults.maxTimeoutSeconds}; out-of-range values are clamped). ` +
|
|
215
|
-
`Raise it only when a cancelled query's plan looked sound and the query was merely slow. ` +
|
|
216
|
-
`A query the plan shows scanning a whole table does not finish sooner with more time.`,
|
|
217
|
-
},
|
|
218
|
-
},
|
|
219
|
-
required: ['connection', 'sql'],
|
|
220
|
-
};
|
|
221
|
-
const catalogInputSchema = {
|
|
222
|
-
...MYSQL_CATALOG_TOOL.inputSchema,
|
|
223
|
-
properties: { ...MYSQL_CATALOG_TOOL.inputSchema.properties, connection: connectionProperty },
|
|
224
|
-
};
|
|
225
|
-
const envBanner = `[env: ${env.label}]`;
|
|
226
|
-
const loadResourceTables = async (rt) => {
|
|
227
|
-
if (rt.catalog.isEnabled()) {
|
|
236
|
+
const mysqlQueryDescription = () => queryBaseDescription + catalog.toolDescriptionSuffix(TOOL_DESCRIPTION_LIMIT - queryBaseDescription.length);
|
|
237
|
+
const loadResourceTables = async () => {
|
|
238
|
+
if (catalog.isEnabled()) {
|
|
228
239
|
try {
|
|
229
|
-
const cached = await
|
|
240
|
+
const cached = await catalog.listTables();
|
|
230
241
|
if (cached.length > 0) {
|
|
231
242
|
return cached;
|
|
232
243
|
}
|
|
233
244
|
}
|
|
234
245
|
catch (error) {
|
|
235
|
-
console.error(`[catalog] table resource fallback
|
|
246
|
+
console.error(`[catalog] table resource fallback: ${error instanceof Error ? error.message : String(error)}`);
|
|
236
247
|
}
|
|
237
248
|
}
|
|
238
|
-
return
|
|
249
|
+
return executeQuery(`
|
|
239
250
|
SELECT
|
|
240
251
|
table_name as name,
|
|
241
252
|
table_schema as \`database\`,
|
|
@@ -253,131 +264,256 @@ export default function createMcpServer(env, registry) {
|
|
|
253
264
|
table_schema, table_name
|
|
254
265
|
`);
|
|
255
266
|
};
|
|
256
|
-
const runtimeFor = (name) => {
|
|
257
|
-
const found = runtimes.find((rt) => rt.name === name);
|
|
258
|
-
if (!found) {
|
|
259
|
-
throw new Error(`Unknown connection "${name}" in resource URI. Connections: ${connectionNames.join(', ')}.`);
|
|
260
|
-
}
|
|
261
|
-
return found;
|
|
262
|
-
};
|
|
263
267
|
const server = new Server({
|
|
264
268
|
name: 'MySQL MCP Server',
|
|
265
269
|
version: PACKAGE_VERSION,
|
|
266
270
|
}, {
|
|
267
271
|
capabilities: {
|
|
268
272
|
resources: {},
|
|
269
|
-
tools:
|
|
273
|
+
tools: catalog.isEnabled() ? { listChanged: true } : {},
|
|
270
274
|
},
|
|
271
275
|
});
|
|
272
276
|
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
catch (error) {
|
|
288
|
-
console.error(`[resources] could not list tables for connection ${rt.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
289
|
-
}
|
|
277
|
+
try {
|
|
278
|
+
log('info', 'Handling ListResourcesRequest');
|
|
279
|
+
log('info', `Connection info: ${describeConnection()}`);
|
|
280
|
+
const tables = await loadResourceTables();
|
|
281
|
+
log('info', `Found ${tables.length} tables`);
|
|
282
|
+
const resources = tables.map((table) => ({
|
|
283
|
+
uri: tableResourceUri(table.database, table.name),
|
|
284
|
+
name: table.name,
|
|
285
|
+
title: `${table.database}.${table.name}`,
|
|
286
|
+
description: table.description || `Table ${table.name} in database ${table.database}`,
|
|
287
|
+
mimeType: 'application/json',
|
|
288
|
+
}));
|
|
290
289
|
resources.push({
|
|
291
|
-
uri:
|
|
292
|
-
name:
|
|
293
|
-
title:
|
|
294
|
-
description:
|
|
290
|
+
uri: 'mysql://tables',
|
|
291
|
+
name: 'Tables',
|
|
292
|
+
title: 'MySQL Tables',
|
|
293
|
+
description: 'List of all MySQL tables',
|
|
295
294
|
mimeType: 'application/json',
|
|
296
295
|
});
|
|
297
|
-
if (
|
|
296
|
+
if (catalog.isEnabled()) {
|
|
298
297
|
resources.push({
|
|
299
|
-
uri:
|
|
300
|
-
name:
|
|
298
|
+
uri: 'mysql://schemas',
|
|
299
|
+
name: 'Schema owners',
|
|
301
300
|
title: 'Schema to repository and app map',
|
|
302
|
-
description: `Which repository and app own each schema
|
|
301
|
+
description: `Which repository and app own each schema in ${PROFILE_LABEL}, as confirmed by users`,
|
|
303
302
|
mimeType: 'application/json',
|
|
304
303
|
});
|
|
305
304
|
}
|
|
305
|
+
return { resources };
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
log('error', 'Error in ListResourcesRequest handler:', error);
|
|
309
|
+
throw error;
|
|
306
310
|
}
|
|
307
|
-
return { resources };
|
|
308
311
|
});
|
|
309
312
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
if (parsed.kind === 'tables') {
|
|
323
|
-
return reply(JSON.stringify(await loadResourceTables(rt), null, 2));
|
|
324
|
-
}
|
|
325
|
-
if (rt.catalog.isEnabled()) {
|
|
326
|
-
try {
|
|
327
|
-
return reply(await rt.catalog.describe(`${parsed.schema}.${parsed.table}`));
|
|
313
|
+
try {
|
|
314
|
+
log('info', 'Handling ReadResourceRequest:', request.params.uri);
|
|
315
|
+
if (request.params.uri === 'mysql://schemas') {
|
|
316
|
+
return {
|
|
317
|
+
contents: [
|
|
318
|
+
{
|
|
319
|
+
uri: request.params.uri,
|
|
320
|
+
mimeType: 'application/json',
|
|
321
|
+
text: renderSchemasResource(PROFILE_LABEL, catalog.codeBranches(), catalog.schemaOwners()),
|
|
322
|
+
},
|
|
323
|
+
],
|
|
324
|
+
};
|
|
328
325
|
}
|
|
329
|
-
|
|
330
|
-
|
|
326
|
+
if (request.params.uri === 'mysql://tables') {
|
|
327
|
+
return {
|
|
328
|
+
contents: [
|
|
329
|
+
{
|
|
330
|
+
uri: request.params.uri,
|
|
331
|
+
mimeType: 'application/json',
|
|
332
|
+
text: JSON.stringify(await loadResourceTables(), null, 2),
|
|
333
|
+
},
|
|
334
|
+
],
|
|
335
|
+
};
|
|
331
336
|
}
|
|
337
|
+
let dbName = null;
|
|
338
|
+
let tableName;
|
|
339
|
+
if (request.params.uri.startsWith('mysql://tables/')) {
|
|
340
|
+
const parts = request.params.uri.slice('mysql://tables/'.length).split('/').map(decodeURIComponent);
|
|
341
|
+
dbName = parts.length >= 2 ? parts[0] : null;
|
|
342
|
+
tableName = parts.length >= 2 ? parts[1] : parts[0];
|
|
343
|
+
if (catalog.isEnabled()) {
|
|
344
|
+
try {
|
|
345
|
+
return {
|
|
346
|
+
contents: [
|
|
347
|
+
{
|
|
348
|
+
uri: request.params.uri,
|
|
349
|
+
mimeType: 'application/json',
|
|
350
|
+
text: await catalog.describe(dbName ? `${dbName}.${tableName}` : tableName),
|
|
351
|
+
},
|
|
352
|
+
],
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
catch (error) {
|
|
356
|
+
log('info', `[catalog] describe fallback for ${request.params.uri}: ${error instanceof Error ? error.message : String(error)}`);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
else {
|
|
361
|
+
const uriParts = request.params.uri.split('/');
|
|
362
|
+
tableName = uriParts.pop();
|
|
363
|
+
dbName = uriParts.length > 0 ? (uriParts.pop() ?? null) : null;
|
|
364
|
+
}
|
|
365
|
+
if (!tableName) {
|
|
366
|
+
throw new Error(`Invalid resource URI: ${request.params.uri}`);
|
|
367
|
+
}
|
|
368
|
+
let columnsQuery = 'SELECT column_name, data_type FROM information_schema.columns WHERE table_name = ?';
|
|
369
|
+
let queryParams = [tableName];
|
|
370
|
+
if (dbName) {
|
|
371
|
+
columnsQuery += ' AND table_schema = ?';
|
|
372
|
+
queryParams.push(dbName);
|
|
373
|
+
}
|
|
374
|
+
const results = (await executeQuery(columnsQuery, queryParams));
|
|
375
|
+
return {
|
|
376
|
+
contents: [
|
|
377
|
+
{
|
|
378
|
+
uri: request.params.uri,
|
|
379
|
+
mimeType: 'application/json',
|
|
380
|
+
text: JSON.stringify(results, null, 2),
|
|
381
|
+
},
|
|
382
|
+
],
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
catch (error) {
|
|
386
|
+
log('error', 'Error in ReadResourceRequest handler:', error);
|
|
387
|
+
throw error;
|
|
332
388
|
}
|
|
333
|
-
const columns = await rt.db.executeQuery('SELECT column_name, data_type FROM information_schema.columns WHERE table_schema = ? AND table_name = ?', [parsed.schema, parsed.table]);
|
|
334
|
-
return reply(JSON.stringify(columns, null, 2));
|
|
335
389
|
});
|
|
336
390
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
337
|
-
const args = (request.params.arguments ?? {});
|
|
338
|
-
let rt = null;
|
|
339
391
|
try {
|
|
340
392
|
log('info', 'Handling CallToolRequest:', request.params.name);
|
|
341
|
-
if (request.params.name !== 'mysql_query' && request.params.name !== 'mysql_catalog') {
|
|
342
|
-
throw new Error(`Unknown tool: ${request.params.name}`);
|
|
343
|
-
}
|
|
344
|
-
rt = resolveConnection(env, runtimes, args.connection);
|
|
345
393
|
if (request.params.name === 'mysql_catalog') {
|
|
346
|
-
|
|
394
|
+
if (!catalog.isEnabled()) {
|
|
395
|
+
throw new Error('The schema catalog is disabled.');
|
|
396
|
+
}
|
|
397
|
+
const args = request.params.arguments ?? {};
|
|
398
|
+
const action = args.action;
|
|
399
|
+
let text;
|
|
400
|
+
if (action === 'map') {
|
|
401
|
+
text = await catalog.map();
|
|
402
|
+
}
|
|
403
|
+
else if (action === 'search') {
|
|
404
|
+
if (typeof args.q !== 'string' || !args.q.trim()) {
|
|
405
|
+
throw new Error('mysql_catalog search requires a non-empty "q".');
|
|
406
|
+
}
|
|
407
|
+
text = await catalog.search(args.q, typeof args.limit === 'number' ? args.limit : undefined);
|
|
408
|
+
}
|
|
409
|
+
else if (action === 'describe') {
|
|
410
|
+
if (typeof args.table !== 'string' || !args.table.trim()) {
|
|
411
|
+
throw new Error('mysql_catalog describe requires "table" as schema.table.');
|
|
412
|
+
}
|
|
413
|
+
text = await catalog.describe(args.table);
|
|
414
|
+
}
|
|
415
|
+
else if (action === 'link') {
|
|
416
|
+
if (!Array.isArray(args.links) ||
|
|
417
|
+
!args.links.every((link) => link &&
|
|
418
|
+
typeof link === 'object' &&
|
|
419
|
+
typeof link.table === 'string' &&
|
|
420
|
+
typeof link.doc === 'string' &&
|
|
421
|
+
typeof link.repo === 'string')) {
|
|
422
|
+
throw new Error('mysql_catalog link requires "links" as [{table, doc, repo}, ...].');
|
|
423
|
+
}
|
|
424
|
+
text = await catalog.link(args.links);
|
|
425
|
+
}
|
|
426
|
+
else if (action === 'unlink') {
|
|
427
|
+
if (typeof args.table !== 'string' || !args.table.trim()) {
|
|
428
|
+
throw new Error('mysql_catalog unlink requires "table" as schema.table.');
|
|
429
|
+
}
|
|
430
|
+
text = await catalog.unlink(args.table);
|
|
431
|
+
}
|
|
432
|
+
else if (action === 'note') {
|
|
433
|
+
if (typeof args.target !== 'string' || !args.target.trim()) {
|
|
434
|
+
throw new Error('mysql_catalog note requires "target" as schema.table.');
|
|
435
|
+
}
|
|
436
|
+
const hasText = typeof args.text === 'string' && args.text.trim().length > 0;
|
|
437
|
+
const hasAlias = typeof args.alias === 'string' && args.alias.trim().length > 0;
|
|
438
|
+
if (hasText === hasAlias) {
|
|
439
|
+
throw new Error('mysql_catalog note requires exactly one non-empty "text" or "alias".');
|
|
440
|
+
}
|
|
441
|
+
text = await catalog.note(args.target, {
|
|
442
|
+
...(hasText ? { text: args.text } : {}),
|
|
443
|
+
...(hasAlias ? { alias: args.alias } : {}),
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
else if (action === 'forget') {
|
|
447
|
+
if (typeof args.target !== 'string' || !args.target.trim()) {
|
|
448
|
+
throw new Error('mysql_catalog forget requires "target" as schema.table.');
|
|
449
|
+
}
|
|
450
|
+
const scopes = new Set(['notes', 'aliases', 'usage', 'joins', 'metadata']);
|
|
451
|
+
if (typeof args.scope !== 'string' || !scopes.has(args.scope)) {
|
|
452
|
+
throw new Error('mysql_catalog forget requires "scope" as notes, aliases, usage, joins, or metadata.');
|
|
453
|
+
}
|
|
454
|
+
text = await catalog.forget(args.target, args.scope);
|
|
455
|
+
}
|
|
456
|
+
else if (action === 'branch') {
|
|
457
|
+
if (typeof args.repo !== 'string' ||
|
|
458
|
+
!args.repo.trim() ||
|
|
459
|
+
typeof args.branch !== 'string' ||
|
|
460
|
+
!args.branch.trim()) {
|
|
461
|
+
throw new Error('mysql_catalog branch requires "repo" and "branch", e.g. {repo: "owner/name", branch: "develop"}.');
|
|
462
|
+
}
|
|
463
|
+
text = catalog.setCodeBranch(args.repo, args.branch);
|
|
464
|
+
}
|
|
465
|
+
else if (action === 'owner') {
|
|
466
|
+
if (typeof args.target !== 'string' ||
|
|
467
|
+
!args.target.trim() ||
|
|
468
|
+
typeof args.repo !== 'string' ||
|
|
469
|
+
!args.repo.trim() ||
|
|
470
|
+
typeof args.app !== 'string' ||
|
|
471
|
+
!args.app.trim()) {
|
|
472
|
+
throw new Error('mysql_catalog owner requires "target", "repo" and "app", e.g. {target: "haulla", repo: "owner/name", app: "core-api"}.');
|
|
473
|
+
}
|
|
474
|
+
text = await catalog.setSchemaOwner(args.target, args.repo, args.app);
|
|
475
|
+
}
|
|
476
|
+
else if (action === 'refresh') {
|
|
477
|
+
if (args.target !== undefined && typeof args.target !== 'string') {
|
|
478
|
+
throw new Error('mysql_catalog refresh takes "target" as a string.');
|
|
479
|
+
}
|
|
480
|
+
text = await catalog.refresh(args.target);
|
|
481
|
+
}
|
|
482
|
+
else {
|
|
483
|
+
throw new Error(`Unknown mysql_catalog action: ${String(action)}`);
|
|
484
|
+
}
|
|
347
485
|
return {
|
|
348
486
|
content: [
|
|
349
|
-
{ type: 'text', text:
|
|
487
|
+
{ type: 'text', text: profileBanner() },
|
|
350
488
|
{ type: 'text', text },
|
|
351
489
|
],
|
|
352
490
|
isError: false,
|
|
353
491
|
};
|
|
354
492
|
}
|
|
355
|
-
|
|
493
|
+
if (request.params.name !== 'mysql_query') {
|
|
494
|
+
throw new Error(`Unknown tool: ${request.params.name}`);
|
|
495
|
+
}
|
|
496
|
+
const sql = request.params.arguments?.sql;
|
|
356
497
|
if (typeof sql !== 'string' || sql.trim() === '') {
|
|
357
498
|
throw new Error('The "sql" argument is required and must be a non-empty string.');
|
|
358
499
|
}
|
|
359
|
-
const
|
|
500
|
+
const timeoutSeconds = clampTimeoutSeconds(request.params.arguments?.timeout_seconds);
|
|
501
|
+
const references = catalog.prepareQuery(sql);
|
|
360
502
|
let result;
|
|
361
503
|
try {
|
|
362
|
-
result = await
|
|
504
|
+
result = await executeReadOnlyQuery(sql, { timeoutSeconds });
|
|
363
505
|
}
|
|
364
506
|
catch (error) {
|
|
365
|
-
|
|
366
|
-
const hint = schemaVisibilityHint(runtimes, rt, sql);
|
|
367
|
-
if (hint && error instanceof Error) {
|
|
368
|
-
error.message = `${error.message}\n${hint}`;
|
|
369
|
-
}
|
|
507
|
+
catalog.afterQuery(references, { content: [], isError: true }, error);
|
|
370
508
|
throw error;
|
|
371
509
|
}
|
|
372
|
-
const documentGuidance = result.isError ? null :
|
|
373
|
-
|
|
374
|
-
const hint = result.isError ? schemaVisibilityHint(runtimes, rt, sql) : null;
|
|
510
|
+
const documentGuidance = result.isError ? null : catalog.queryDocumentGuidance(references);
|
|
511
|
+
catalog.afterQuery(references, result);
|
|
375
512
|
return {
|
|
376
513
|
...result,
|
|
377
514
|
content: [
|
|
378
|
-
{ type: 'text', text:
|
|
515
|
+
{ type: 'text', text: profileBanner() },
|
|
379
516
|
...(result.content ?? []),
|
|
380
|
-
...(hint ? [{ type: 'text', text: hint }] : []),
|
|
381
517
|
...(documentGuidance ? [{ type: 'text', text: documentGuidance }] : []),
|
|
382
518
|
],
|
|
383
519
|
};
|
|
@@ -386,62 +522,85 @@ export default function createMcpServer(env, registry) {
|
|
|
386
522
|
const error = err;
|
|
387
523
|
log('error', 'Error in CallToolRequest handler:', describeQueryError(error));
|
|
388
524
|
return {
|
|
389
|
-
content: [
|
|
525
|
+
content: [
|
|
526
|
+
{
|
|
527
|
+
type: 'text',
|
|
528
|
+
text: `${profileBanner()} Error: ${error.message}`,
|
|
529
|
+
},
|
|
530
|
+
],
|
|
390
531
|
isError: true,
|
|
391
532
|
};
|
|
392
533
|
}
|
|
393
534
|
});
|
|
394
535
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
395
536
|
log('info', 'Handling ListToolsRequest');
|
|
396
|
-
const
|
|
397
|
-
for (const rt of runtimes) {
|
|
398
|
-
Object.assign(branches, rt.catalog.codeBranches());
|
|
399
|
-
}
|
|
400
|
-
return {
|
|
537
|
+
const toolsResponse = {
|
|
401
538
|
tools: [
|
|
402
539
|
{
|
|
403
540
|
name: 'mysql_query',
|
|
404
|
-
description:
|
|
405
|
-
inputSchema:
|
|
541
|
+
description: mysqlQueryDescription(),
|
|
542
|
+
inputSchema: mysqlQueryInputSchema,
|
|
406
543
|
annotations: {
|
|
407
|
-
readOnlyHint:
|
|
408
|
-
idempotentHint:
|
|
409
|
-
destructiveHint: !
|
|
544
|
+
readOnlyHint: isReadOnly,
|
|
545
|
+
idempotentHint: isReadOnly,
|
|
546
|
+
destructiveHint: !isReadOnly,
|
|
410
547
|
openWorldHint: false,
|
|
411
548
|
title: 'MySQL Query',
|
|
412
549
|
},
|
|
413
550
|
},
|
|
414
|
-
...(
|
|
551
|
+
...(catalog.isEnabled()
|
|
415
552
|
? [
|
|
416
553
|
{
|
|
417
|
-
...
|
|
418
|
-
|
|
419
|
-
description: MYSQL_CATALOG_TOOL.description + codeBranchToolInstruction(branches),
|
|
554
|
+
...mysqlCatalogTool,
|
|
555
|
+
description: mysqlCatalogTool.description + codeBranchToolInstruction(catalog.codeBranches()),
|
|
420
556
|
},
|
|
421
557
|
]
|
|
422
558
|
: []),
|
|
423
559
|
],
|
|
424
560
|
};
|
|
561
|
+
log('info', 'ListToolsRequest response:', JSON.stringify(toolsResponse, null, 2));
|
|
562
|
+
return toolsResponse;
|
|
563
|
+
});
|
|
564
|
+
catalog.onToolDescriptionFilled(async () => {
|
|
565
|
+
await server.sendToolListChanged().catch(() => undefined);
|
|
425
566
|
});
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
567
|
+
(async () => {
|
|
568
|
+
try {
|
|
569
|
+
if (SSH_ENABLED) {
|
|
570
|
+
log('info', 'Opening SSH tunnel before connecting to MySQL...');
|
|
571
|
+
const endpoint = await ensureTunnel();
|
|
572
|
+
log('info', `SSH tunnel ready on ${endpoint?.host}:${endpoint?.port}` +
|
|
573
|
+
(endpoint?.reused ? ' (reused an existing forward)' : ''));
|
|
574
|
+
}
|
|
575
|
+
log('info', 'Attempting to test database connection...');
|
|
576
|
+
const pool = await getPool();
|
|
577
|
+
const connection = await pool.getConnection();
|
|
578
|
+
log('info', 'Database connection test successful');
|
|
579
|
+
connection.release();
|
|
580
|
+
catalog.startInventory();
|
|
429
581
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
582
|
+
catch (error) {
|
|
583
|
+
console.error(`[startup] fatal error for profile ${PROFILE_LABEL}: ` +
|
|
584
|
+
(error instanceof Error ? error.message : String(error)));
|
|
585
|
+
log('error', 'Fatal error during server startup:', error);
|
|
586
|
+
await stopTunnel();
|
|
587
|
+
process.exit(1);
|
|
588
|
+
}
|
|
589
|
+
})();
|
|
435
590
|
const shutdown = sharedOnce(async (signal) => {
|
|
436
591
|
log('info', `Received ${signal}. Shutting down...`);
|
|
437
592
|
try {
|
|
438
|
-
await
|
|
593
|
+
await catalog.close();
|
|
594
|
+
if (poolPromise) {
|
|
595
|
+
const pool = await poolPromise;
|
|
596
|
+
await pool.end();
|
|
597
|
+
}
|
|
439
598
|
}
|
|
440
599
|
catch (err) {
|
|
441
|
-
log('error', 'Error closing
|
|
600
|
+
log('error', 'Error closing pool:', err);
|
|
442
601
|
}
|
|
443
602
|
finally {
|
|
444
|
-
await
|
|
603
|
+
await stopTunnel();
|
|
445
604
|
}
|
|
446
605
|
});
|
|
447
606
|
const shutdownAndExit = async (reason) => {
|
|
@@ -496,38 +655,17 @@ const isMainModule = () => {
|
|
|
496
655
|
}
|
|
497
656
|
return false;
|
|
498
657
|
};
|
|
499
|
-
if (isMainModule()
|
|
500
|
-
|
|
501
|
-
.then(({ runInitCli }) => runInitCli(process.argv.slice(3)))
|
|
502
|
-
.then((code) => process.exit(code), (error) => {
|
|
503
|
-
console.error(error instanceof Error ? error.message : String(error));
|
|
504
|
-
process.exit(error instanceof UsageError ? 2 : 1);
|
|
505
|
-
});
|
|
506
|
-
}
|
|
507
|
-
else if (isMainModule()) {
|
|
658
|
+
if (isMainModule()) {
|
|
659
|
+
log('info', 'Running in standalone mode');
|
|
508
660
|
(async () => {
|
|
509
|
-
let env;
|
|
510
|
-
try {
|
|
511
|
-
env = loadEnvironment(parseServerArgs(process.argv.slice(2)));
|
|
512
|
-
}
|
|
513
|
-
catch (error) {
|
|
514
|
-
if (error instanceof UsageError || error instanceof ConfigLoadError) {
|
|
515
|
-
console.error(`[startup] ${error.message}`);
|
|
516
|
-
process.exit(error instanceof UsageError ? 2 : 1);
|
|
517
|
-
}
|
|
518
|
-
throw error;
|
|
519
|
-
}
|
|
520
|
-
for (const warning of env.warnings) {
|
|
521
|
-
console.error(`[config] ${warning}`);
|
|
522
|
-
}
|
|
523
661
|
try {
|
|
524
|
-
const mcpServer = createMcpServer(
|
|
662
|
+
const mcpServer = createMcpServer();
|
|
525
663
|
const transport = new StdioServerTransport();
|
|
526
664
|
await mcpServer.connect(transport);
|
|
527
665
|
log('info', 'Server started and listening on stdio');
|
|
528
666
|
}
|
|
529
667
|
catch (error) {
|
|
530
|
-
console.error(`[startup] fatal error for
|
|
668
|
+
console.error(`[startup] fatal error for profile ${PROFILE_LABEL}: ` +
|
|
531
669
|
(error instanceof Error ? error.message : String(error)));
|
|
532
670
|
log('error', 'Server error:', error);
|
|
533
671
|
process.exit(1);
|