@ecubelabs/mysql-mcp 1.0.0-next.6 → 1.0.0-next.7
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 +448 -296
- package/dist/index.js +239 -377
- package/dist/src/catalog/collect.js +2 -3
- package/dist/src/catalog/context.js +187 -0
- package/dist/src/catalog/docs.js +12 -14
- package/dist/src/catalog/index.js +99 -59
- package/dist/src/catalog/lock.js +113 -0
- package/dist/src/catalog/render.js +10 -4
- package/dist/src/catalog/store.js +76 -193
- package/dist/src/catalog/types.js +12 -0
- package/dist/src/config/args.js +30 -0
- package/dist/src/config/index.js +0 -175
- package/dist/src/config/load.js +169 -0
- package/dist/src/config/schema.js +351 -0
- package/dist/src/config/secrets.js +128 -0
- package/dist/src/config/ssl.js +25 -0
- package/dist/src/db/index.js +379 -379
- package/dist/src/db/permissions.js +16 -32
- package/dist/src/db/registry.js +178 -0
- package/dist/src/db/utils.js +1 -3
- package/dist/src/init/check.js +31 -0
- package/dist/src/init/cli.js +26 -0
- package/dist/src/init/config-edit.js +95 -0
- package/dist/src/init/prompt.js +82 -0
- package/dist/src/init/wizard.js +223 -0
- package/dist/src/server/catalog-tool.js +91 -0
- package/dist/src/server/connections.js +117 -0
- package/dist/src/ssh/config.js +27 -34
- package/dist/src/ssh/tunnel.js +155 -238
- package/dist/src/utils/index.js +35 -4
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,54 +1,23 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { fileURLToPath } from 'url';
|
|
3
3
|
import { realpathSync } from 'fs';
|
|
4
|
+
import * as path from 'path';
|
|
4
5
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
5
6
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
6
7
|
import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
7
|
-
import { log, sharedOnce, tableResourceUri } from './src/utils/index.js';
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
8
|
+
import { log, parseResourceUri, setLogging, sharedOnce, tableResourceUri } from './src/utils/index.js';
|
|
9
|
+
import { PACKAGE_VERSION } from './src/config/index.js';
|
|
10
|
+
import { ConfigLoadError, loadEnvironment } from './src/config/load.js';
|
|
11
|
+
import { parseServerArgs, UsageError } from './src/config/args.js';
|
|
12
|
+
import { codeBranchToolInstruction } from './src/catalog/branch.js';
|
|
13
|
+
import { ContextStore } from './src/catalog/context.js';
|
|
11
14
|
import { catalogIdentity, SchemaCatalog } from './src/catalog/index.js';
|
|
12
15
|
import { renderSchemasResource } from './src/catalog/render.js';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
const
|
|
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 = {
|
|
16
|
+
import { ConnectionDatabase, describeQueryError, sessionLimitPrimer } from './src/db/index.js';
|
|
17
|
+
import { ConnectionRegistry } from './src/db/registry.js';
|
|
18
|
+
import { runCatalogAction } from './src/server/catalog-tool.js';
|
|
19
|
+
import { allReadOnly, queryToolDescription, resolveConnection, schemaVisibilityHint, TOOL_DESCRIPTION_LIMIT, } from './src/server/connections.js';
|
|
20
|
+
const MYSQL_CATALOG_TOOL = {
|
|
52
21
|
name: 'mysql_catalog',
|
|
53
22
|
description: 'Read the local schema catalog without rediscovering database metadata. ' +
|
|
54
23
|
'Use map for the app/schema overview, search to find tables or known columns, ' +
|
|
@@ -59,13 +28,17 @@ const mysqlCatalogTool = {
|
|
|
59
28
|
'Use branch to record which branch of a GitHub repository matches this database, once ' +
|
|
60
29
|
'the user confirmed it. ' +
|
|
61
30
|
'Use owner to record which repository and app own a schema, once the user confirmed it. ' +
|
|
62
|
-
'Use note to save a table memo or alias, and forget to clear one catalog scope. ' +
|
|
31
|
+
'Use note to save a table memo or alias, or a schema memo, and forget to clear one catalog scope. ' +
|
|
63
32
|
'Use refresh when cached metadata contradicts what a query actually returned, ' +
|
|
64
33
|
'or right after a migration: added columns and indexes raise no error, so ' +
|
|
65
34
|
'nothing else invalidates them.',
|
|
66
35
|
inputSchema: {
|
|
67
36
|
type: 'object',
|
|
68
37
|
properties: {
|
|
38
|
+
connection: {
|
|
39
|
+
type: 'string',
|
|
40
|
+
description: 'Connection whose catalog to read or update. Listed in the mysql_query description.',
|
|
41
|
+
},
|
|
69
42
|
action: {
|
|
70
43
|
type: 'string',
|
|
71
44
|
enum: ['map', 'search', 'describe', 'link', 'unlink', 'branch', 'owner', 'note', 'forget', 'refresh'],
|
|
@@ -106,14 +79,14 @@ const mysqlCatalogTool = {
|
|
|
106
79
|
},
|
|
107
80
|
target: {
|
|
108
81
|
type: 'string',
|
|
109
|
-
description: 'Qualified schema.table for note or forget. Schema name for owner. For refresh: ' +
|
|
82
|
+
description: 'Qualified schema.table for note or forget; a schema name for a schema memo. Schema name for owner. For refresh: ' +
|
|
110
83
|
'"schema.table" for one table\'s columns, indexes and foreign keys; a schema name for the ' +
|
|
111
84
|
'table inventory. Omit it to refresh the inventory.',
|
|
112
85
|
},
|
|
113
86
|
text: {
|
|
114
87
|
type: 'string',
|
|
115
88
|
maxLength: 1000,
|
|
116
|
-
description: '
|
|
89
|
+
description: 'Memo to add with note, for a table or a schema; use either text or alias',
|
|
117
90
|
},
|
|
118
91
|
alias: {
|
|
119
92
|
type: 'string',
|
|
@@ -152,7 +125,7 @@ const mysqlCatalogTool = {
|
|
|
152
125
|
},
|
|
153
126
|
},
|
|
154
127
|
},
|
|
155
|
-
required: ['action'],
|
|
128
|
+
required: ['connection', 'action'],
|
|
156
129
|
},
|
|
157
130
|
annotations: {
|
|
158
131
|
readOnlyHint: false,
|
|
@@ -162,91 +135,107 @@ const mysqlCatalogTool = {
|
|
|
162
135
|
title: 'MySQL Schema Catalog',
|
|
163
136
|
},
|
|
164
137
|
};
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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),
|
|
138
|
+
function catalogTarget(spec) {
|
|
139
|
+
const { instance } = spec;
|
|
140
|
+
return instance.socketPath
|
|
141
|
+
? JSON.stringify(['unix', instance.socketPath])
|
|
142
|
+
: JSON.stringify(['tcp', instance.host, instance.port]);
|
|
143
|
+
}
|
|
144
|
+
export default function createMcpServer(env, registry) {
|
|
145
|
+
setLogging(env.defaults.logging);
|
|
146
|
+
log('info', `Starting MySQL MCP server v${PACKAGE_VERSION} for environment ${env.label}...`);
|
|
147
|
+
const connections = registry ?? new ConnectionRegistry(env, { preparePool: sessionLimitPrimer(env.defaults) });
|
|
148
|
+
const context = new ContextStore(path.join(env.stateDir, 'context.json'));
|
|
149
|
+
const runtimes = connections.list().map((handle) => {
|
|
150
|
+
const { spec } = handle;
|
|
151
|
+
const db = new ConnectionDatabase(handle, env);
|
|
152
|
+
const identity = catalogIdentity({
|
|
153
|
+
profile: env.name,
|
|
154
|
+
target: catalogTarget(spec),
|
|
155
|
+
user: spec.user,
|
|
156
|
+
directory: env.defaults.catalog.dir,
|
|
157
|
+
});
|
|
158
|
+
const catalog = new SchemaCatalog({
|
|
159
|
+
enabled: env.defaults.catalog.enabled,
|
|
160
|
+
profile: env.name,
|
|
161
|
+
connection: spec.name,
|
|
162
|
+
fingerprint: identity.fingerprint,
|
|
163
|
+
filePath: identity.filePath,
|
|
164
|
+
ttlHours: env.defaults.catalog.ttlHours,
|
|
165
|
+
defaultSchema: spec.database ?? null,
|
|
166
|
+
query: (sql, params) => db.executeQuery(sql, params),
|
|
167
|
+
context: { store: context, env: env.name, instance: spec.instance.name },
|
|
168
|
+
});
|
|
169
|
+
db.setDiagnosticsSource({ indexFacts: (reference) => catalog.indexFacts(reference) });
|
|
170
|
+
db.setCodeBranchSource(() => catalog.codeBranchSummary());
|
|
171
|
+
return { name: spec.name, spec, db, catalog };
|
|
228
172
|
});
|
|
229
|
-
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
173
|
+
const catalogEnabled = runtimes.some((rt) => rt.catalog.isEnabled());
|
|
174
|
+
const readOnly = allReadOnly(env, runtimes);
|
|
175
|
+
const connectionNames = runtimes.map((rt) => rt.name);
|
|
176
|
+
log('info', 'MySQL configuration:', JSON.stringify({
|
|
177
|
+
environment: env.label,
|
|
178
|
+
config: env.configPath,
|
|
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.`);
|
|
235
195
|
}
|
|
236
|
-
const
|
|
237
|
-
|
|
238
|
-
|
|
196
|
+
const connectionProperty = {
|
|
197
|
+
type: 'string',
|
|
198
|
+
enum: connectionNames,
|
|
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()) {
|
|
239
228
|
try {
|
|
240
|
-
const cached = await catalog.listTables();
|
|
229
|
+
const cached = await rt.catalog.listTables();
|
|
241
230
|
if (cached.length > 0) {
|
|
242
231
|
return cached;
|
|
243
232
|
}
|
|
244
233
|
}
|
|
245
234
|
catch (error) {
|
|
246
|
-
console.error(`[catalog] table resource fallback: ${error instanceof Error ? error.message : String(error)}`);
|
|
235
|
+
console.error(`[catalog] table resource fallback for ${rt.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
247
236
|
}
|
|
248
237
|
}
|
|
249
|
-
return executeQuery(`
|
|
238
|
+
return rt.db.executeQuery(`
|
|
250
239
|
SELECT
|
|
251
240
|
table_name as name,
|
|
252
241
|
table_schema as \`database\`,
|
|
@@ -264,256 +253,131 @@ export default function createMcpServer() {
|
|
|
264
253
|
table_schema, table_name
|
|
265
254
|
`);
|
|
266
255
|
};
|
|
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
|
+
};
|
|
267
263
|
const server = new Server({
|
|
268
264
|
name: 'MySQL MCP Server',
|
|
269
265
|
version: PACKAGE_VERSION,
|
|
270
266
|
}, {
|
|
271
267
|
capabilities: {
|
|
272
268
|
resources: {},
|
|
273
|
-
tools:
|
|
269
|
+
tools: catalogEnabled ? { listChanged: true } : {},
|
|
274
270
|
},
|
|
275
271
|
});
|
|
276
272
|
server.setRequestHandler(ListResourcesRequestSchema, async () => {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
273
|
+
log('info', 'Handling ListResourcesRequest');
|
|
274
|
+
const resources = [];
|
|
275
|
+
for (const rt of runtimes) {
|
|
276
|
+
try {
|
|
277
|
+
for (const table of await loadResourceTables(rt)) {
|
|
278
|
+
resources.push({
|
|
279
|
+
uri: tableResourceUri(rt.name, table.database, table.name),
|
|
280
|
+
name: table.name,
|
|
281
|
+
title: `${table.database}.${table.name} (${rt.name})`,
|
|
282
|
+
description: table.description || `Table ${table.name} in database ${table.database}`,
|
|
283
|
+
mimeType: 'application/json',
|
|
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
|
+
}
|
|
289
290
|
resources.push({
|
|
290
|
-
uri:
|
|
291
|
-
name:
|
|
292
|
-
title:
|
|
293
|
-
description:
|
|
291
|
+
uri: `mysql://${rt.name}/tables`,
|
|
292
|
+
name: `Tables (${rt.name})`,
|
|
293
|
+
title: `MySQL tables visible to connection ${rt.name}`,
|
|
294
|
+
description: `List of all MySQL tables visible to connection ${rt.name}`,
|
|
294
295
|
mimeType: 'application/json',
|
|
295
296
|
});
|
|
296
|
-
if (catalog.isEnabled()) {
|
|
297
|
+
if (rt.catalog.isEnabled()) {
|
|
297
298
|
resources.push({
|
|
298
|
-
uri:
|
|
299
|
-
name:
|
|
299
|
+
uri: `mysql://${rt.name}/schemas`,
|
|
300
|
+
name: `Schema owners (${rt.name})`,
|
|
300
301
|
title: 'Schema to repository and app map',
|
|
301
|
-
description: `Which repository and app own each schema in ${
|
|
302
|
+
description: `Which repository and app own each schema visible to ${rt.name} in ${env.label}, as confirmed by users`,
|
|
302
303
|
mimeType: 'application/json',
|
|
303
304
|
});
|
|
304
305
|
}
|
|
305
|
-
return { resources };
|
|
306
|
-
}
|
|
307
|
-
catch (error) {
|
|
308
|
-
log('error', 'Error in ListResourcesRequest handler:', error);
|
|
309
|
-
throw error;
|
|
310
306
|
}
|
|
307
|
+
return { resources };
|
|
311
308
|
});
|
|
312
309
|
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
mimeType: 'application/json',
|
|
332
|
-
text: JSON.stringify(await loadResourceTables(), null, 2),
|
|
333
|
-
},
|
|
334
|
-
],
|
|
335
|
-
};
|
|
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}`);
|
|
310
|
+
const { uri } = request.params;
|
|
311
|
+
log('info', 'Handling ReadResourceRequest:', uri);
|
|
312
|
+
const parsed = parseResourceUri(uri);
|
|
313
|
+
if (!parsed) {
|
|
314
|
+
throw new Error(`Invalid resource URI: ${uri}. Expected mysql://<connection>/tables, mysql://<connection>/schemas, ` +
|
|
315
|
+
`or mysql://<connection>/tables/<schema>/<table>.`);
|
|
316
|
+
}
|
|
317
|
+
const rt = runtimeFor(parsed.connection);
|
|
318
|
+
const reply = (text) => ({ contents: [{ uri, mimeType: 'application/json', text }] });
|
|
319
|
+
if (parsed.kind === 'schemas') {
|
|
320
|
+
return reply(renderSchemasResource(env.label, rt.catalog.codeBranches(), rt.catalog.schemaOwners()));
|
|
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}`));
|
|
367
328
|
}
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
if (dbName) {
|
|
371
|
-
columnsQuery += ' AND table_schema = ?';
|
|
372
|
-
queryParams.push(dbName);
|
|
329
|
+
catch (error) {
|
|
330
|
+
log('info', `[catalog] describe fallback for ${uri}: ${error instanceof Error ? error.message : String(error)}`);
|
|
373
331
|
}
|
|
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;
|
|
388
332
|
}
|
|
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));
|
|
389
335
|
});
|
|
390
336
|
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
337
|
+
const args = (request.params.arguments ?? {});
|
|
338
|
+
let rt = null;
|
|
391
339
|
try {
|
|
392
340
|
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);
|
|
393
345
|
if (request.params.name === 'mysql_catalog') {
|
|
394
|
-
|
|
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
|
-
}
|
|
346
|
+
const text = await runCatalogAction(rt.catalog, args);
|
|
485
347
|
return {
|
|
486
348
|
content: [
|
|
487
|
-
{ type: 'text', text:
|
|
349
|
+
{ type: 'text', text: rt.db.banner() },
|
|
488
350
|
{ type: 'text', text },
|
|
489
351
|
],
|
|
490
352
|
isError: false,
|
|
491
353
|
};
|
|
492
354
|
}
|
|
493
|
-
|
|
494
|
-
throw new Error(`Unknown tool: ${request.params.name}`);
|
|
495
|
-
}
|
|
496
|
-
const sql = request.params.arguments?.sql;
|
|
355
|
+
const sql = args.sql;
|
|
497
356
|
if (typeof sql !== 'string' || sql.trim() === '') {
|
|
498
357
|
throw new Error('The "sql" argument is required and must be a non-empty string.');
|
|
499
358
|
}
|
|
500
|
-
const
|
|
501
|
-
const references = catalog.prepareQuery(sql);
|
|
359
|
+
const references = rt.catalog.prepareQuery(sql);
|
|
502
360
|
let result;
|
|
503
361
|
try {
|
|
504
|
-
result = await executeReadOnlyQuery(sql, { timeoutSeconds });
|
|
362
|
+
result = await rt.db.executeReadOnlyQuery(sql, { timeoutSeconds: args.timeout_seconds });
|
|
505
363
|
}
|
|
506
364
|
catch (error) {
|
|
507
|
-
catalog.afterQuery(references, { content: [], isError: true }, error);
|
|
365
|
+
rt.catalog.afterQuery(references, { content: [], isError: true }, error);
|
|
366
|
+
const hint = schemaVisibilityHint(runtimes, rt, sql);
|
|
367
|
+
if (hint && error instanceof Error) {
|
|
368
|
+
error.message = `${error.message}\n${hint}`;
|
|
369
|
+
}
|
|
508
370
|
throw error;
|
|
509
371
|
}
|
|
510
|
-
const documentGuidance = result.isError ? null : catalog.queryDocumentGuidance(references);
|
|
511
|
-
catalog.afterQuery(references, result);
|
|
372
|
+
const documentGuidance = result.isError ? null : rt.catalog.queryDocumentGuidance(references);
|
|
373
|
+
rt.catalog.afterQuery(references, result);
|
|
374
|
+
const hint = result.isError ? schemaVisibilityHint(runtimes, rt, sql) : null;
|
|
512
375
|
return {
|
|
513
376
|
...result,
|
|
514
377
|
content: [
|
|
515
|
-
{ type: 'text', text:
|
|
378
|
+
{ type: 'text', text: rt.db.banner() },
|
|
516
379
|
...(result.content ?? []),
|
|
380
|
+
...(hint ? [{ type: 'text', text: hint }] : []),
|
|
517
381
|
...(documentGuidance ? [{ type: 'text', text: documentGuidance }] : []),
|
|
518
382
|
],
|
|
519
383
|
};
|
|
@@ -522,85 +386,62 @@ export default function createMcpServer() {
|
|
|
522
386
|
const error = err;
|
|
523
387
|
log('error', 'Error in CallToolRequest handler:', describeQueryError(error));
|
|
524
388
|
return {
|
|
525
|
-
content: [
|
|
526
|
-
{
|
|
527
|
-
type: 'text',
|
|
528
|
-
text: `${profileBanner()} Error: ${error.message}`,
|
|
529
|
-
},
|
|
530
|
-
],
|
|
389
|
+
content: [{ type: 'text', text: `${rt ? rt.db.banner() : envBanner} Error: ${error.message}` }],
|
|
531
390
|
isError: true,
|
|
532
391
|
};
|
|
533
392
|
}
|
|
534
393
|
});
|
|
535
394
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
536
395
|
log('info', 'Handling ListToolsRequest');
|
|
537
|
-
const
|
|
396
|
+
const branches = {};
|
|
397
|
+
for (const rt of runtimes) {
|
|
398
|
+
Object.assign(branches, rt.catalog.codeBranches());
|
|
399
|
+
}
|
|
400
|
+
return {
|
|
538
401
|
tools: [
|
|
539
402
|
{
|
|
540
403
|
name: 'mysql_query',
|
|
541
|
-
description:
|
|
542
|
-
inputSchema:
|
|
404
|
+
description: queryToolDescription(env, runtimes, PACKAGE_VERSION).text,
|
|
405
|
+
inputSchema: queryInputSchema,
|
|
543
406
|
annotations: {
|
|
544
|
-
readOnlyHint:
|
|
545
|
-
idempotentHint:
|
|
546
|
-
destructiveHint: !
|
|
407
|
+
readOnlyHint: readOnly,
|
|
408
|
+
idempotentHint: readOnly,
|
|
409
|
+
destructiveHint: !readOnly,
|
|
547
410
|
openWorldHint: false,
|
|
548
411
|
title: 'MySQL Query',
|
|
549
412
|
},
|
|
550
413
|
},
|
|
551
|
-
...(
|
|
414
|
+
...(catalogEnabled
|
|
552
415
|
? [
|
|
553
416
|
{
|
|
554
|
-
...
|
|
555
|
-
|
|
417
|
+
...MYSQL_CATALOG_TOOL,
|
|
418
|
+
inputSchema: catalogInputSchema,
|
|
419
|
+
description: MYSQL_CATALOG_TOOL.description + codeBranchToolInstruction(branches),
|
|
556
420
|
},
|
|
557
421
|
]
|
|
558
422
|
: []),
|
|
559
423
|
],
|
|
560
424
|
};
|
|
561
|
-
log('info', 'ListToolsRequest response:', JSON.stringify(toolsResponse, null, 2));
|
|
562
|
-
return toolsResponse;
|
|
563
|
-
});
|
|
564
|
-
catalog.onToolDescriptionFilled(async () => {
|
|
565
|
-
await server.sendToolListChanged().catch(() => undefined);
|
|
566
425
|
});
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
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();
|
|
581
|
-
}
|
|
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);
|
|
426
|
+
const announceToolList = async () => {
|
|
427
|
+
if (catalogEnabled) {
|
|
428
|
+
await server.sendToolListChanged().catch(() => undefined);
|
|
588
429
|
}
|
|
589
|
-
}
|
|
430
|
+
};
|
|
431
|
+
for (const rt of runtimes) {
|
|
432
|
+
rt.catalog.onToolDescriptionFilled(announceToolList);
|
|
433
|
+
void rt.catalog.startInventory().then(announceToolList);
|
|
434
|
+
}
|
|
590
435
|
const shutdown = sharedOnce(async (signal) => {
|
|
591
436
|
log('info', `Received ${signal}. Shutting down...`);
|
|
592
437
|
try {
|
|
593
|
-
await catalog.close();
|
|
594
|
-
if (poolPromise) {
|
|
595
|
-
const pool = await poolPromise;
|
|
596
|
-
await pool.end();
|
|
597
|
-
}
|
|
438
|
+
await Promise.all(runtimes.map((rt) => rt.catalog.close()));
|
|
598
439
|
}
|
|
599
440
|
catch (err) {
|
|
600
|
-
log('error', 'Error closing
|
|
441
|
+
log('error', 'Error closing catalogs:', err);
|
|
601
442
|
}
|
|
602
443
|
finally {
|
|
603
|
-
await
|
|
444
|
+
await connections.close();
|
|
604
445
|
}
|
|
605
446
|
});
|
|
606
447
|
const shutdownAndExit = async (reason) => {
|
|
@@ -655,17 +496,38 @@ const isMainModule = () => {
|
|
|
655
496
|
}
|
|
656
497
|
return false;
|
|
657
498
|
};
|
|
658
|
-
if (isMainModule()) {
|
|
659
|
-
|
|
499
|
+
if (isMainModule() && process.argv[2] === 'init') {
|
|
500
|
+
void import('./src/init/cli.js')
|
|
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()) {
|
|
660
508
|
(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
|
+
}
|
|
661
523
|
try {
|
|
662
|
-
const mcpServer = createMcpServer();
|
|
524
|
+
const mcpServer = createMcpServer(env);
|
|
663
525
|
const transport = new StdioServerTransport();
|
|
664
526
|
await mcpServer.connect(transport);
|
|
665
527
|
log('info', 'Server started and listening on stdio');
|
|
666
528
|
}
|
|
667
529
|
catch (error) {
|
|
668
|
-
console.error(`[startup] fatal error for
|
|
530
|
+
console.error(`[startup] fatal error for environment ${env.label}: ` +
|
|
669
531
|
(error instanceof Error ? error.message : String(error)));
|
|
670
532
|
log('error', 'Server error:', error);
|
|
671
533
|
process.exit(1);
|