@ginkgolab/datasources 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,63 @@
1
+ // src/connectors/db/sqlGuard.ts
2
+ function assertReadOnlySql(sql) {
3
+ const cleanSql = sql.trim().replace(/;+$/, "");
4
+ if (cleanSql.includes(";")) {
5
+ throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u7981\u6B62\u6267\u884C\u5305\u542B\u591A\u4E2A\u5206\u53F7\u8BED\u53E5\u7684\u590D\u5408 SQL\uFF01");
6
+ }
7
+ const lower = cleanSql.toLowerCase();
8
+ if (!lower.startsWith("select") && !lower.startsWith("with")) {
9
+ throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u4EC5\u5141\u8BB8\u6267\u884C\u53EA\u8BFB SELECT / WITH \u67E5\u8BE2\uFF01");
10
+ }
11
+ const dangerousKeywords = [
12
+ "drop",
13
+ "delete",
14
+ "update",
15
+ "insert",
16
+ "alter",
17
+ "truncate",
18
+ "create",
19
+ "grant",
20
+ "revoke",
21
+ "exec",
22
+ "execute",
23
+ "call",
24
+ "copy",
25
+ "into",
26
+ "prepare",
27
+ "listen",
28
+ "notify",
29
+ "pg_sleep",
30
+ "pg_terminate_backend",
31
+ "pg_cancel_backend",
32
+ "set_config",
33
+ "dblink",
34
+ "lo_import",
35
+ "lo_export"
36
+ ];
37
+ for (const kw of dangerousKeywords) {
38
+ const regex = new RegExp(`(^|\\s|;|\\()(${kw})(\\s|;|$|\\()`, "i");
39
+ if (regex.test(lower)) {
40
+ throw new Error(`\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [${kw.toUpperCase()}]`);
41
+ }
42
+ }
43
+ if (/(^|\s)for\s+(update|share)(\s|$)/i.test(lower)) {
44
+ throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [FOR UPDATE/SHARE]");
45
+ }
46
+ }
47
+ function enforceRowLimit(sql, maxRows = 200) {
48
+ const stripped = sql.replace(/'(?:[^']|'')*'/g, "''").replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
49
+ if (/\blimit\b/i.test(stripped)) return sql;
50
+ return `${sql}
51
+ LIMIT ${maxRows}`;
52
+ }
53
+ function guardReadOnlySql(sql) {
54
+ assertReadOnlySql(sql);
55
+ const clean = sql.trim().replace(/;+$/, "");
56
+ return enforceRowLimit(clean);
57
+ }
58
+
59
+ export {
60
+ assertReadOnlySql,
61
+ enforceRowLimit,
62
+ guardReadOnlySql
63
+ };
package/dist/gateway.js CHANGED
@@ -1,526 +1,9 @@
1
- // src/parseToolResult.ts
2
- function parseToolResult(res, toolLabel) {
3
- const r = res ?? {};
4
- const contentList = Array.isArray(r.content) ? r.content : [];
5
- if (r.isError) {
6
- const errorText = contentList.map((c) => c.text || "").join("\n");
7
- throw new Error(errorText || `${toolLabel} execution failed`);
8
- }
9
- const textOutput = contentList.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
10
- try {
11
- return JSON.parse(textOutput);
12
- } catch {
13
- return textOutput;
14
- }
15
- }
16
-
17
- // src/gateway/queryCache.ts
18
- import { createHash } from "crypto";
19
- function normalizeSqlForCache(sql) {
20
- const trimmed = sql.trim().replace(/;+\s*$/, "");
21
- const LITERAL_RE = /('(?:[^']|'')*'|"(?:[^"]|"")*")/g;
22
- const parts = [];
23
- let last = 0;
24
- let m;
25
- while ((m = LITERAL_RE.exec(trimmed)) !== null) {
26
- parts.push(trimmed.slice(last, m.index).replace(/\s+/g, " ").toLowerCase());
27
- parts.push(m[0]);
28
- last = m.index + m[0].length;
29
- }
30
- parts.push(trimmed.slice(last).replace(/\s+/g, " ").toLowerCase());
31
- return parts.join("");
32
- }
33
- function computeQueryHashKey(sourceId, sql, params) {
34
- const normSql = normalizeSqlForCache(sql);
35
- const sqlHash = createHash("sha256").update(normSql).digest("hex");
36
- const paramsHash = createHash("sha256").update(JSON.stringify(params ?? [])).digest("hex");
37
- return {
38
- sourceId,
39
- sqlHash,
40
- paramsHash
41
- };
42
- }
43
- function formatCacheKey(key) {
44
- return `${key.sourceId}:${key.sqlHash}:${key.paramsHash}`;
45
- }
46
- var QueryCacheManager = class {
47
- cache = /* @__PURE__ */ new Map();
48
- maxEntries;
49
- defaultTtlMs;
50
- constructor(options) {
51
- this.maxEntries = options?.maxEntries ?? 500;
52
- this.defaultTtlMs = options?.defaultTtlMs ?? 15 * 60 * 1e3;
53
- }
54
- get(key) {
55
- const formatted = formatCacheKey(key);
56
- const entry = this.cache.get(formatted);
57
- if (!entry) return null;
58
- const now = Date.now();
59
- if (now - entry.cachedAt > entry.ttlMs) {
60
- this.cache.delete(formatted);
61
- return null;
62
- }
63
- this.cache.delete(formatted);
64
- this.cache.set(formatted, entry);
65
- return {
66
- data: entry.data,
67
- cachedAt: entry.cachedAt
68
- };
69
- }
70
- set(key, data, ttlMs) {
71
- const formatted = formatCacheKey(key);
72
- const now = Date.now();
73
- if (this.cache.size >= this.maxEntries) {
74
- const firstKey = this.cache.keys().next().value;
75
- if (firstKey) this.cache.delete(firstKey);
76
- }
77
- this.cache.set(formatted, {
78
- key: formatted,
79
- data,
80
- cachedAt: now,
81
- ttlMs: ttlMs ?? this.defaultTtlMs
82
- });
83
- }
84
- /**
85
- * 清除特定数据源或全部缓存
86
- */
87
- invalidate(sourceId) {
88
- if (!sourceId) {
89
- this.cache.clear();
90
- return;
91
- }
92
- const prefix = `${sourceId}:`;
93
- for (const k of this.cache.keys()) {
94
- if (k.startsWith(prefix)) {
95
- this.cache.delete(k);
96
- }
97
- }
98
- }
99
- size() {
100
- return this.cache.size;
101
- }
102
- };
103
-
104
- // src/connectors/db/sqlGuard.ts
105
- function assertReadOnlySql(sql) {
106
- const cleanSql = sql.trim().replace(/;+$/, "");
107
- if (cleanSql.includes(";")) {
108
- throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u7981\u6B62\u6267\u884C\u5305\u542B\u591A\u4E2A\u5206\u53F7\u8BED\u53E5\u7684\u590D\u5408 SQL\uFF01");
109
- }
110
- const lower = cleanSql.toLowerCase();
111
- if (!lower.startsWith("select") && !lower.startsWith("with")) {
112
- throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u4EC5\u5141\u8BB8\u6267\u884C\u53EA\u8BFB SELECT / WITH \u67E5\u8BE2\uFF01");
113
- }
114
- const dangerousKeywords = [
115
- "drop",
116
- "delete",
117
- "update",
118
- "insert",
119
- "alter",
120
- "truncate",
121
- "create",
122
- "grant",
123
- "revoke",
124
- "exec",
125
- "execute",
126
- "call",
127
- "copy",
128
- "into",
129
- "prepare",
130
- "listen",
131
- "notify",
132
- "pg_sleep",
133
- "pg_terminate_backend",
134
- "pg_cancel_backend",
135
- "set_config",
136
- "dblink",
137
- "lo_import",
138
- "lo_export"
139
- ];
140
- for (const kw of dangerousKeywords) {
141
- const regex = new RegExp(`(^|\\s|;|\\()(${kw})(\\s|;|$|\\()`, "i");
142
- if (regex.test(lower)) {
143
- throw new Error(`\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [${kw.toUpperCase()}]`);
144
- }
145
- }
146
- if (/(^|\s)for\s+(update|share)(\s|$)/i.test(lower)) {
147
- throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [FOR UPDATE/SHARE]");
148
- }
149
- }
150
-
151
- // src/gateway/explainGuard.ts
152
- var DEFAULT_BUDGET = 1e6;
153
- var SQL_FAULT_RE = /syntax error|parse error|does not exist|unknown (column|table|identifier)|no such (table|column)|undefined (table|column|parameter)|ambiguous|42P01|42P02|42703|ER_(NO_SUCH_TABLE|BAD_FIELD_ERROR|PARSE_ERROR)|1146|1054|1064/i;
154
- function parsePostgresPlan(plan) {
155
- let totalRows = Number(plan["Plan Rows"] ?? 0);
156
- let hasSeqScan = plan["Node Type"] === "Seq Scan";
157
- const seqScanTables = [];
158
- if (hasSeqScan && plan["Relation Name"]) {
159
- seqScanTables.push(String(plan["Relation Name"]));
160
- }
161
- const plans = plan["Plans"] || [];
162
- for (const subPlan of plans) {
163
- const sub = parsePostgresPlan(subPlan);
164
- totalRows = Math.max(totalRows, sub.totalRows);
165
- if (sub.hasSeqScan) hasSeqScan = true;
166
- seqScanTables.push(...sub.seqScanTables);
167
- }
168
- return { totalRows, hasSeqScan, seqScanTables };
169
- }
170
- function parseMysqlPlan(obj) {
171
- let totalRows = 0;
172
- let hasAllScan = false;
173
- const allScanTables = [];
174
- function walk(node) {
175
- if (!node || typeof node !== "object") return;
176
- const rec = node;
177
- if (rec["table"] && typeof rec["table"] === "object") {
178
- const tableObj = rec["table"];
179
- const rows = Number(tableObj["rows_examined_per_scan"] ?? tableObj["rows"] ?? 0);
180
- totalRows += rows;
181
- if (tableObj["access_type"] === "ALL") {
182
- hasAllScan = true;
183
- if (tableObj["table_name"]) {
184
- allScanTables.push(String(tableObj["table_name"]));
185
- }
186
- }
187
- }
188
- for (const v of Object.values(rec)) {
189
- if (Array.isArray(v)) {
190
- v.forEach(walk);
191
- } else if (v && typeof v === "object") {
192
- walk(v);
193
- }
194
- }
195
- }
196
- walk(obj);
197
- return { totalRows, hasAllScan, allScanTables };
198
- }
199
- async function dryRunExplain(client, dbType, sql, options, params) {
200
- const budget = options?.maxScanRowsBudget ?? DEFAULT_BUDGET;
201
- const blockFullTableScan = options?.blockFullTableScan ?? true;
202
- const cleanSql = sql.trim().replace(/;+$/, "");
203
- try {
204
- let explainSql = "";
205
- if (dbType === "postgres") {
206
- explainSql = `EXPLAIN (FORMAT JSON) ${cleanSql}`;
207
- } else if (dbType === "mysql") {
208
- explainSql = `EXPLAIN FORMAT=JSON ${cleanSql}`;
209
- } else if (dbType === "sqlite") {
210
- explainSql = `EXPLAIN QUERY PLAN ${cleanSql}`;
211
- } else if (dbType === "duckdb") {
212
- explainSql = `EXPLAIN ${cleanSql}`;
213
- } else if (dbType === "clickhouse") {
214
- explainSql = `EXPLAIN ESTIMATE ${cleanSql}`;
215
- } else {
216
- explainSql = `EXPLAIN ${cleanSql}`;
217
- }
218
- const res = await client.query(explainSql, params);
219
- const rows = res.rows;
220
- let estimatedRows = 0;
221
- let isFullTableScan = false;
222
- let scanTargetDetail = "";
223
- if (dbType === "postgres" && rows.length > 0) {
224
- const rawJson = Object.values(rows[0])[0];
225
- const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
226
- const planRoot = Array.isArray(parsed) ? parsed[0]?.Plan : parsed?.Plan;
227
- if (planRoot) {
228
- const { totalRows, hasSeqScan, seqScanTables } = parsePostgresPlan(planRoot);
229
- estimatedRows = totalRows;
230
- isFullTableScan = hasSeqScan && estimatedRows > 5e3;
231
- if (seqScanTables.length > 0) {
232
- scanTargetDetail = `\uFF08\u8868: ${seqScanTables.join(", ")}\uFF09`;
233
- }
234
- }
235
- } else if (dbType === "mysql" && rows.length > 0) {
236
- const rawJson = Object.values(rows[0])[0];
237
- const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
238
- if (parsed) {
239
- const { totalRows, hasAllScan, allScanTables } = parseMysqlPlan(parsed);
240
- estimatedRows = totalRows;
241
- isFullTableScan = hasAllScan && estimatedRows > 5e3;
242
- if (allScanTables.length > 0) {
243
- scanTargetDetail = `\uFF08\u8868: ${allScanTables.join(", ")}\uFF09`;
244
- }
245
- }
246
- } else if (dbType === "sqlite") {
247
- for (const row of rows) {
248
- const detail = String(row["detail"] || Object.values(row)[0] || "");
249
- if (detail.includes("SCAN TABLE") && !detail.includes("USING INDEX")) {
250
- isFullTableScan = true;
251
- scanTargetDetail = `\uFF08${detail}\uFF09`;
252
- }
253
- }
254
- } else if (dbType === "duckdb") {
255
- for (const row of rows) {
256
- const detail = String(row["explain_value"] || Object.values(row)[0] || "");
257
- if (detail.includes("SEQ_SCAN")) {
258
- isFullTableScan = true;
259
- scanTargetDetail = `\uFF08SEQ_SCAN\uFF09`;
260
- }
261
- }
262
- } else if (dbType === "clickhouse") {
263
- for (const row of rows) {
264
- const line = String(Object.values(row)[0] || "");
265
- const match = line.match(/rows:\s*(\d+)/i);
266
- if (match) {
267
- estimatedRows = Number(match[1]);
268
- }
269
- }
270
- }
271
- const exceedsBudget = estimatedRows > budget;
272
- let costWarning;
273
- if (exceedsBudget) {
274
- costWarning = `\u6210\u672C\u95E8\u7981\u62E6\u622A\uFF1A\u9884\u4F30\u626B\u63CF\u884C\u6570 (${estimatedRows.toLocaleString()}) \u8D85\u8FC7\u5B89\u5168\u9884\u7B97\u4E0A\u9650 (${budget.toLocaleString()})\u3002\u8BF7\u5728 SQL \u4E2D\u8865\u5145\u5408\u9002\u7684\u65F6\u95F4\u5206\u533A\u6761\u4EF6\uFF08\u5982 WHERE date >= ...\uFF09\u6216\u589E\u52A0 LIMIT\u3002`;
275
- } else if (isFullTableScan && blockFullTableScan && estimatedRows > budget / 2) {
276
- costWarning = `\u6210\u672C\u95E8\u7981\u8B66\u544A\uFF1A\u68C0\u6D4B\u5230\u5927\u89C4\u6A21\u5168\u8868\u626B\u63CF\u98CE\u9669 ${scanTargetDetail}\uFF0C\u9884\u4F30\u626B\u63CF\u884C\u6570\u7EA6 ${estimatedRows.toLocaleString()}\u3002\u5EFA\u8BAE\u8865\u5145\u9488\u5BF9\u7D22\u5F15\u5B57\u6BB5\u7684\u8FC7\u6EE4\u6761\u4EF6\u3002`;
277
- }
278
- return {
279
- isValid: true,
280
- estimatedRows,
281
- isFullTableScan,
282
- exceedsBudget,
283
- costWarning,
284
- planRaw: rows.slice(0, 5)
285
- };
286
- } catch (err) {
287
- const message = err instanceof Error ? err.message : String(err);
288
- if (SQL_FAULT_RE.test(message)) {
289
- return {
290
- isValid: false,
291
- estimatedRows: 0,
292
- isFullTableScan: false,
293
- exceedsBudget: false,
294
- syntaxError: message,
295
- costWarning: `\u6267\u884C\u8BA1\u5212\u9884\u68C0\u5931\u8D25\uFF08\u8BED\u6CD5\u6216\u8868/\u5B57\u6BB5\u4E0D\u5B58\u5728\uFF09\uFF1A${message}`
296
- };
297
- }
298
- return {
299
- isValid: true,
300
- estimatedRows: 0,
301
- isFullTableScan: false,
302
- exceedsBudget: false,
303
- degraded: true,
304
- costWarning: `EXPLAIN \u9884\u68C0\u4E0D\u53EF\u7528\uFF0C\u5DF2\u964D\u7EA7\u4E3A\u76F4\u63A5\u6267\u884C\uFF08\u4ECD\u53D7\u53EA\u8BFB\u4E0E\u884C\u6570\u5C01\u9876\u4FDD\u62A4\uFF09\uFF1A${message}`
305
- };
306
- }
307
- }
308
-
309
- // src/gateway/queryPipeline.ts
310
- async function executeSqlWithGuards(opts) {
311
- const sql = opts.sql.trim();
312
- assertReadOnlySql(sql);
313
- const cacheKey = computeQueryHashKey(opts.sourceId, sql, opts.params);
314
- if (!opts.skipCache) {
315
- const cached = opts.cache.get(cacheKey);
316
- if (cached) {
317
- if (opts.logPrefix) {
318
- console.log(
319
- `[${opts.logPrefix}] \u547D\u4E2D MCP \u7F51\u5173\u67E5\u8BE2\u7F13\u5B58 (SQL Hash: ${cacheKey.sqlHash.slice(0, 8)})`
320
- );
321
- }
322
- return {
323
- data: cached.data,
324
- cacheHit: true,
325
- cachedAt: cached.cachedAt
326
- };
327
- }
328
- }
329
- let explainReport;
330
- if (opts.dialectClient && !opts.bypassExplain) {
331
- explainReport = await dryRunExplain(
332
- opts.dialectClient.client,
333
- opts.dialectClient.dbType,
334
- sql,
335
- opts.explainOptions,
336
- opts.params
337
- );
338
- if (explainReport.degraded && opts.logPrefix) {
339
- console.warn(
340
- `[${opts.logPrefix}] EXPLAIN \u9884\u68C0\u964D\u7EA7\u653E\u884C: ${explainReport.costWarning}`
341
- );
342
- }
343
- if (!explainReport.isValid) {
344
- throw new Error(
345
- explainReport.costWarning || `SQL \u6267\u884C\u8BA1\u5212\u8BED\u6CD5\u9884\u68C0\u5931\u8D25: ${explainReport.syntaxError}`
346
- );
347
- }
348
- if (explainReport.exceedsBudget) {
349
- throw new Error(
350
- explainReport.costWarning || "SQL \u626B\u63CF\u6570\u636E\u884C\u6570\u8D85\u8FC7\u5355\u6B21\u67E5\u8BE2\u9884\u7B97\uFF0C\u5DF2\u89E6\u53D1\u7194\u65AD\u4FDD\u62A4\uFF01"
351
- );
352
- }
353
- }
354
- const data = await opts.execute();
355
- opts.cache.set(cacheKey, data, opts.cacheTtlMs);
356
- return { data, cacheHit: false, explainReport };
357
- }
358
-
359
- // src/gateway/queryGateway.ts
360
- var TABLE_IDENTIFIER_RE = /^[A-Za-z_][\w$]*(\.[A-Za-z_][\w$]*)*$/;
361
- var QueryGateway = class {
362
- cache;
363
- manager;
364
- config;
365
- constructor(manager, config, sharedCache) {
366
- this.manager = manager;
367
- this.config = config ?? {};
368
- this.cache = sharedCache ?? new QueryCacheManager({
369
- maxEntries: config?.maxCacheEntries,
370
- defaultTtlMs: config?.defaultCacheTtlMs
371
- });
372
- }
373
- /**
374
- * 按数据源 ID 与工具原名检索已绑定的工具调用契约
375
- */
376
- async getTool(sourceId, toolName) {
377
- const conf = this.manager.get(sourceId);
378
- if (!conf || conf.enabled === false) return void 0;
379
- const tools = await this.manager.tools(conf);
380
- return tools.find(
381
- (t) => t.originalName === toolName || t.name === `${sourceId}_${toolName}`
382
- );
383
- }
384
- /**
385
- * 核心方法:执行 SQL 查询(流经共享守卫管线)
386
- */
387
- async executeQuery(args) {
388
- const { sourceId, sql, params, skipCache, bypassExplain, cacheTtlMs } = args;
389
- const startTime = Date.now();
390
- const conf = this.manager.get(sourceId);
391
- if (!conf || conf.enabled === false) {
392
- throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u5C31\u7EEA\u6216\u672A\u542F\u7528`);
393
- }
394
- const result = await executeSqlWithGuards({
395
- sourceId,
396
- sql,
397
- params,
398
- skipCache,
399
- bypassExplain,
400
- cacheTtlMs,
401
- dialectClient: this.manager.getDialectClient?.(sourceId),
402
- cache: this.cache,
403
- explainOptions: this.config.explainOptions,
404
- logPrefix: `Gateway ${sourceId}`,
405
- execute: async () => {
406
- const toolBinding = await this.getTool(sourceId, "execute_sql");
407
- if (!toolBinding) {
408
- throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u66B4\u9732 execute_sql \u5DE5\u5177\u63A5\u53E3`);
409
- }
410
- const conn = await this.manager.connect(conf);
411
- const raw = await conn.callTool("execute_sql", {
412
- sql,
413
- ...params !== void 0 ? { params } : {}
414
- });
415
- const parsed = parseToolResult(raw, "tool execute_sql");
416
- let rows = [];
417
- let rowCount = 0;
418
- if (parsed && typeof parsed === "object") {
419
- if (!Array.isArray(parsed) && Array.isArray(parsed.rows)) {
420
- rows = parsed.rows;
421
- rowCount = typeof parsed.rowCount === "number" ? parsed.rowCount : rows.length;
422
- } else if (Array.isArray(parsed)) {
423
- rows = parsed;
424
- rowCount = rows.length;
425
- }
426
- }
427
- return { rows, rowCount };
428
- }
429
- });
430
- return {
431
- rows: result.data.rows,
432
- rowCount: result.data.rowCount,
433
- cacheHit: result.cacheHit,
434
- cachedAt: result.cachedAt,
435
- durationMs: Date.now() - startTime,
436
- explainReport: result.explainReport
437
- };
438
- }
439
- /**
440
- * 两阶段发现第一阶段:获取全量数据源及其表名概览(不含详细字段,防上下文撑爆)
441
- */
442
- async listCatalogs() {
443
- const list = this.manager.list().filter((c) => c.enabled !== false);
444
- const results = [];
445
- for (const item of list) {
446
- const listTool = await this.getTool(item.id, "list_tables");
447
- let tables = [];
448
- if (listTool) {
449
- try {
450
- const res = await listTool.call({});
451
- if (res && Array.isArray(res.tables)) {
452
- tables = res.tables.map(
453
- (t) => typeof t === "string" ? t : String(t?.table ?? "")
454
- ).filter(Boolean);
455
- }
456
- } catch {
457
- tables = [];
458
- }
459
- }
460
- results.push({
461
- sourceId: item.id,
462
- name: item.name,
463
- type: item.dbType ?? item.kind,
464
- tables
465
- });
466
- }
467
- return results;
468
- }
469
- /**
470
- * 两阶段发现第二阶段:按需拉取特定表的详细 Schema 与前 3 条样本数据
471
- */
472
- async describeTableResource(sourceId, tableName) {
473
- if (!TABLE_IDENTIFIER_RE.test(tableName)) {
474
- throw new Error(`\u975E\u6CD5\u8868\u540D\u6807\u8BC6\u7B26: ${tableName}`);
475
- }
476
- const describeTool = await this.getTool(sourceId, "describe_table");
477
- if (!describeTool) {
478
- throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u63D0\u4F9B describe_table \u5DE5\u5177`);
479
- }
480
- const descRes = await describeTool.call({
481
- table_name: tableName,
482
- table: tableName
483
- });
484
- const columns = [];
485
- if (descRes && Array.isArray(descRes.columns)) {
486
- for (const col of descRes.columns) {
487
- columns.push({
488
- name: String(col.column || col.name),
489
- type: String(col.type || "string"),
490
- comment: col.comment ? String(col.comment) : void 0
491
- });
492
- }
493
- }
494
- let sampleRows = [];
495
- try {
496
- const sampleRes = await this.executeQuery({
497
- sourceId,
498
- sql: `SELECT * FROM ${tableName} LIMIT 3`,
499
- skipCache: false,
500
- bypassExplain: true
501
- });
502
- sampleRows = sampleRes.rows;
503
- } catch {
504
- sampleRows = [];
505
- }
506
- return {
507
- sourceId,
508
- tableName,
509
- columns,
510
- sampleRows
511
- };
512
- }
513
- /**
514
- * 清除网关缓存(共享实例时等同清除该源的全部缓存)
515
- */
516
- invalidateCache(sourceId) {
517
- this.cache.invalidate(sourceId);
518
- }
519
- getCacheManager() {
520
- return this.cache;
521
- }
522
- };
523
- var McpGateway = QueryGateway;
1
+ import {
2
+ McpGateway,
3
+ QueryGateway
4
+ } from "./chunk-K2QVVHDO.js";
5
+ import "./chunk-YU3RO2LC.js";
6
+ import "./chunk-NTJXQDHH.js";
524
7
  export {
525
8
  McpGateway,
526
9
  QueryGateway