@ginkgolab/datasources 0.1.0 → 0.1.1
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/dist/certified.js +3 -109
- package/dist/chunk-IJOM466W.js +324 -0
- package/dist/chunk-K2QVVHDO.js +482 -0
- package/dist/chunk-NTJXQDHH.js +21 -0
- package/dist/chunk-XX5MM5RN.js +51 -0
- package/dist/chunk-YDPLKNPL.js +113 -0
- package/dist/chunk-YU3RO2LC.js +63 -0
- package/dist/gateway.js +6 -523
- package/dist/index.js +40 -991
- package/dist/parseToolResult.js +4 -16
- package/dist/schema/card.js +17 -306
- package/dist/schema/store.js +6 -46
- package/dist/sqlGuard.js +5 -57
- package/package.json +1 -1
- package/dist/manager-BLTs1PDe.d.ts +0 -362
package/dist/index.js
CHANGED
|
@@ -1,3 +1,37 @@
|
|
|
1
|
+
import {
|
|
2
|
+
deleteSchemaCard,
|
|
3
|
+
readSchemaCard,
|
|
4
|
+
writeSchemaCard
|
|
5
|
+
} from "./chunk-XX5MM5RN.js";
|
|
6
|
+
import {
|
|
7
|
+
CARD_RENDER_BUDGET_BYTES,
|
|
8
|
+
CARD_STORE_MAX_BYTES,
|
|
9
|
+
LOW_CARDINALITY_THRESHOLD,
|
|
10
|
+
collectSchemaCard,
|
|
11
|
+
renderCardForPrompt,
|
|
12
|
+
scoreTableRelevance
|
|
13
|
+
} from "./chunk-IJOM466W.js";
|
|
14
|
+
import {
|
|
15
|
+
McpGateway,
|
|
16
|
+
QueryCacheManager,
|
|
17
|
+
QueryGateway,
|
|
18
|
+
computeQueryHashKey,
|
|
19
|
+
dryRunExplain,
|
|
20
|
+
executeSqlWithGuards,
|
|
21
|
+
formatCacheKey,
|
|
22
|
+
formatCacheKeyDisplay,
|
|
23
|
+
normalizeSqlForCache
|
|
24
|
+
} from "./chunk-K2QVVHDO.js";
|
|
25
|
+
import {
|
|
26
|
+
guardReadOnlySql
|
|
27
|
+
} from "./chunk-YU3RO2LC.js";
|
|
28
|
+
import {
|
|
29
|
+
parseToolResult
|
|
30
|
+
} from "./chunk-NTJXQDHH.js";
|
|
31
|
+
import {
|
|
32
|
+
CertifiedQueryStore
|
|
33
|
+
} from "./chunk-YDPLKNPL.js";
|
|
34
|
+
|
|
1
35
|
// src/config.ts
|
|
2
36
|
import fs from "fs";
|
|
3
37
|
import path from "path";
|
|
@@ -149,71 +183,11 @@ function maskConnectionString(conn) {
|
|
|
149
183
|
}
|
|
150
184
|
|
|
151
185
|
// src/manager.ts
|
|
152
|
-
import
|
|
153
|
-
import
|
|
186
|
+
import fs3 from "fs";
|
|
187
|
+
import path3 from "path";
|
|
154
188
|
|
|
155
189
|
// src/connectors/db/postgresDialect.ts
|
|
156
190
|
import { Pool } from "pg";
|
|
157
|
-
|
|
158
|
-
// src/connectors/db/sqlGuard.ts
|
|
159
|
-
function assertReadOnlySql(sql) {
|
|
160
|
-
const cleanSql = sql.trim().replace(/;+$/, "");
|
|
161
|
-
if (cleanSql.includes(";")) {
|
|
162
|
-
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");
|
|
163
|
-
}
|
|
164
|
-
const lower = cleanSql.toLowerCase();
|
|
165
|
-
if (!lower.startsWith("select") && !lower.startsWith("with")) {
|
|
166
|
-
throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u4EC5\u5141\u8BB8\u6267\u884C\u53EA\u8BFB SELECT / WITH \u67E5\u8BE2\uFF01");
|
|
167
|
-
}
|
|
168
|
-
const dangerousKeywords = [
|
|
169
|
-
"drop",
|
|
170
|
-
"delete",
|
|
171
|
-
"update",
|
|
172
|
-
"insert",
|
|
173
|
-
"alter",
|
|
174
|
-
"truncate",
|
|
175
|
-
"create",
|
|
176
|
-
"grant",
|
|
177
|
-
"revoke",
|
|
178
|
-
"exec",
|
|
179
|
-
"execute",
|
|
180
|
-
"call",
|
|
181
|
-
"copy",
|
|
182
|
-
"into",
|
|
183
|
-
"prepare",
|
|
184
|
-
"listen",
|
|
185
|
-
"notify",
|
|
186
|
-
"pg_sleep",
|
|
187
|
-
"pg_terminate_backend",
|
|
188
|
-
"pg_cancel_backend",
|
|
189
|
-
"set_config",
|
|
190
|
-
"dblink",
|
|
191
|
-
"lo_import",
|
|
192
|
-
"lo_export"
|
|
193
|
-
];
|
|
194
|
-
for (const kw of dangerousKeywords) {
|
|
195
|
-
const regex = new RegExp(`(^|\\s|;|\\()(${kw})(\\s|;|$|\\()`, "i");
|
|
196
|
-
if (regex.test(lower)) {
|
|
197
|
-
throw new Error(`\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [${kw.toUpperCase()}]`);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
if (/(^|\s)for\s+(update|share)(\s|$)/i.test(lower)) {
|
|
201
|
-
throw new Error("\u5B89\u5168\u9650\u5236\uFF1A\u68C0\u6D4B\u5230\u7981\u6B62\u7684 SQL \u6307\u4EE4 [FOR UPDATE/SHARE]");
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
function enforceRowLimit(sql, maxRows = 200) {
|
|
205
|
-
const stripped = sql.replace(/'(?:[^']|'')*'/g, "''").replace(/--[^\n]*/g, "").replace(/\/\*[\s\S]*?\*\//g, "");
|
|
206
|
-
if (/\blimit\b/i.test(stripped)) return sql;
|
|
207
|
-
return `${sql}
|
|
208
|
-
LIMIT ${maxRows}`;
|
|
209
|
-
}
|
|
210
|
-
function guardReadOnlySql(sql) {
|
|
211
|
-
assertReadOnlySql(sql);
|
|
212
|
-
const clean = sql.trim().replace(/;+$/, "");
|
|
213
|
-
return enforceRowLimit(clean);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// src/connectors/db/postgresDialect.ts
|
|
217
191
|
var postgresDialect = {
|
|
218
192
|
dbType: "postgres",
|
|
219
193
|
async connect(connectionString) {
|
|
@@ -713,486 +687,6 @@ function createDbToolsConnection(dialect, client, sourceName) {
|
|
|
713
687
|
};
|
|
714
688
|
}
|
|
715
689
|
|
|
716
|
-
// src/gateway/queryCache.ts
|
|
717
|
-
import { createHash } from "crypto";
|
|
718
|
-
function normalizeSqlForCache(sql) {
|
|
719
|
-
const trimmed = sql.trim().replace(/;+\s*$/, "");
|
|
720
|
-
const LITERAL_RE = /('(?:[^']|'')*'|"(?:[^"]|"")*")/g;
|
|
721
|
-
const parts = [];
|
|
722
|
-
let last = 0;
|
|
723
|
-
let m;
|
|
724
|
-
while ((m = LITERAL_RE.exec(trimmed)) !== null) {
|
|
725
|
-
parts.push(trimmed.slice(last, m.index).replace(/\s+/g, " ").toLowerCase());
|
|
726
|
-
parts.push(m[0]);
|
|
727
|
-
last = m.index + m[0].length;
|
|
728
|
-
}
|
|
729
|
-
parts.push(trimmed.slice(last).replace(/\s+/g, " ").toLowerCase());
|
|
730
|
-
return parts.join("");
|
|
731
|
-
}
|
|
732
|
-
function computeQueryHashKey(sourceId, sql, params) {
|
|
733
|
-
const normSql = normalizeSqlForCache(sql);
|
|
734
|
-
const sqlHash = createHash("sha256").update(normSql).digest("hex");
|
|
735
|
-
const paramsHash = createHash("sha256").update(JSON.stringify(params ?? [])).digest("hex");
|
|
736
|
-
return {
|
|
737
|
-
sourceId,
|
|
738
|
-
sqlHash,
|
|
739
|
-
paramsHash
|
|
740
|
-
};
|
|
741
|
-
}
|
|
742
|
-
function formatCacheKey(key) {
|
|
743
|
-
return `${key.sourceId}:${key.sqlHash}:${key.paramsHash}`;
|
|
744
|
-
}
|
|
745
|
-
function formatCacheKeyDisplay(key) {
|
|
746
|
-
return `${key.sourceId}:${key.sqlHash.slice(0, 16)}:${key.paramsHash.slice(0, 8)}`;
|
|
747
|
-
}
|
|
748
|
-
var QueryCacheManager = class {
|
|
749
|
-
cache = /* @__PURE__ */ new Map();
|
|
750
|
-
maxEntries;
|
|
751
|
-
defaultTtlMs;
|
|
752
|
-
constructor(options) {
|
|
753
|
-
this.maxEntries = options?.maxEntries ?? 500;
|
|
754
|
-
this.defaultTtlMs = options?.defaultTtlMs ?? 15 * 60 * 1e3;
|
|
755
|
-
}
|
|
756
|
-
get(key) {
|
|
757
|
-
const formatted = formatCacheKey(key);
|
|
758
|
-
const entry = this.cache.get(formatted);
|
|
759
|
-
if (!entry) return null;
|
|
760
|
-
const now = Date.now();
|
|
761
|
-
if (now - entry.cachedAt > entry.ttlMs) {
|
|
762
|
-
this.cache.delete(formatted);
|
|
763
|
-
return null;
|
|
764
|
-
}
|
|
765
|
-
this.cache.delete(formatted);
|
|
766
|
-
this.cache.set(formatted, entry);
|
|
767
|
-
return {
|
|
768
|
-
data: entry.data,
|
|
769
|
-
cachedAt: entry.cachedAt
|
|
770
|
-
};
|
|
771
|
-
}
|
|
772
|
-
set(key, data, ttlMs) {
|
|
773
|
-
const formatted = formatCacheKey(key);
|
|
774
|
-
const now = Date.now();
|
|
775
|
-
if (this.cache.size >= this.maxEntries) {
|
|
776
|
-
const firstKey = this.cache.keys().next().value;
|
|
777
|
-
if (firstKey) this.cache.delete(firstKey);
|
|
778
|
-
}
|
|
779
|
-
this.cache.set(formatted, {
|
|
780
|
-
key: formatted,
|
|
781
|
-
data,
|
|
782
|
-
cachedAt: now,
|
|
783
|
-
ttlMs: ttlMs ?? this.defaultTtlMs
|
|
784
|
-
});
|
|
785
|
-
}
|
|
786
|
-
/**
|
|
787
|
-
* 清除特定数据源或全部缓存
|
|
788
|
-
*/
|
|
789
|
-
invalidate(sourceId) {
|
|
790
|
-
if (!sourceId) {
|
|
791
|
-
this.cache.clear();
|
|
792
|
-
return;
|
|
793
|
-
}
|
|
794
|
-
const prefix = `${sourceId}:`;
|
|
795
|
-
for (const k of this.cache.keys()) {
|
|
796
|
-
if (k.startsWith(prefix)) {
|
|
797
|
-
this.cache.delete(k);
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
}
|
|
801
|
-
size() {
|
|
802
|
-
return this.cache.size;
|
|
803
|
-
}
|
|
804
|
-
};
|
|
805
|
-
|
|
806
|
-
// src/gateway/explainGuard.ts
|
|
807
|
-
var DEFAULT_BUDGET = 1e6;
|
|
808
|
-
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;
|
|
809
|
-
function parsePostgresPlan(plan) {
|
|
810
|
-
let totalRows = Number(plan["Plan Rows"] ?? 0);
|
|
811
|
-
let hasSeqScan = plan["Node Type"] === "Seq Scan";
|
|
812
|
-
const seqScanTables = [];
|
|
813
|
-
if (hasSeqScan && plan["Relation Name"]) {
|
|
814
|
-
seqScanTables.push(String(plan["Relation Name"]));
|
|
815
|
-
}
|
|
816
|
-
const plans = plan["Plans"] || [];
|
|
817
|
-
for (const subPlan of plans) {
|
|
818
|
-
const sub = parsePostgresPlan(subPlan);
|
|
819
|
-
totalRows = Math.max(totalRows, sub.totalRows);
|
|
820
|
-
if (sub.hasSeqScan) hasSeqScan = true;
|
|
821
|
-
seqScanTables.push(...sub.seqScanTables);
|
|
822
|
-
}
|
|
823
|
-
return { totalRows, hasSeqScan, seqScanTables };
|
|
824
|
-
}
|
|
825
|
-
function parseMysqlPlan(obj) {
|
|
826
|
-
let totalRows = 0;
|
|
827
|
-
let hasAllScan = false;
|
|
828
|
-
const allScanTables = [];
|
|
829
|
-
function walk(node) {
|
|
830
|
-
if (!node || typeof node !== "object") return;
|
|
831
|
-
const rec = node;
|
|
832
|
-
if (rec["table"] && typeof rec["table"] === "object") {
|
|
833
|
-
const tableObj = rec["table"];
|
|
834
|
-
const rows = Number(tableObj["rows_examined_per_scan"] ?? tableObj["rows"] ?? 0);
|
|
835
|
-
totalRows += rows;
|
|
836
|
-
if (tableObj["access_type"] === "ALL") {
|
|
837
|
-
hasAllScan = true;
|
|
838
|
-
if (tableObj["table_name"]) {
|
|
839
|
-
allScanTables.push(String(tableObj["table_name"]));
|
|
840
|
-
}
|
|
841
|
-
}
|
|
842
|
-
}
|
|
843
|
-
for (const v of Object.values(rec)) {
|
|
844
|
-
if (Array.isArray(v)) {
|
|
845
|
-
v.forEach(walk);
|
|
846
|
-
} else if (v && typeof v === "object") {
|
|
847
|
-
walk(v);
|
|
848
|
-
}
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
walk(obj);
|
|
852
|
-
return { totalRows, hasAllScan, allScanTables };
|
|
853
|
-
}
|
|
854
|
-
async function dryRunExplain(client, dbType, sql, options, params) {
|
|
855
|
-
const budget = options?.maxScanRowsBudget ?? DEFAULT_BUDGET;
|
|
856
|
-
const blockFullTableScan = options?.blockFullTableScan ?? true;
|
|
857
|
-
const cleanSql = sql.trim().replace(/;+$/, "");
|
|
858
|
-
try {
|
|
859
|
-
let explainSql = "";
|
|
860
|
-
if (dbType === "postgres") {
|
|
861
|
-
explainSql = `EXPLAIN (FORMAT JSON) ${cleanSql}`;
|
|
862
|
-
} else if (dbType === "mysql") {
|
|
863
|
-
explainSql = `EXPLAIN FORMAT=JSON ${cleanSql}`;
|
|
864
|
-
} else if (dbType === "sqlite") {
|
|
865
|
-
explainSql = `EXPLAIN QUERY PLAN ${cleanSql}`;
|
|
866
|
-
} else if (dbType === "duckdb") {
|
|
867
|
-
explainSql = `EXPLAIN ${cleanSql}`;
|
|
868
|
-
} else if (dbType === "clickhouse") {
|
|
869
|
-
explainSql = `EXPLAIN ESTIMATE ${cleanSql}`;
|
|
870
|
-
} else {
|
|
871
|
-
explainSql = `EXPLAIN ${cleanSql}`;
|
|
872
|
-
}
|
|
873
|
-
const res = await client.query(explainSql, params);
|
|
874
|
-
const rows = res.rows;
|
|
875
|
-
let estimatedRows = 0;
|
|
876
|
-
let isFullTableScan = false;
|
|
877
|
-
let scanTargetDetail = "";
|
|
878
|
-
if (dbType === "postgres" && rows.length > 0) {
|
|
879
|
-
const rawJson = Object.values(rows[0])[0];
|
|
880
|
-
const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
|
881
|
-
const planRoot = Array.isArray(parsed) ? parsed[0]?.Plan : parsed?.Plan;
|
|
882
|
-
if (planRoot) {
|
|
883
|
-
const { totalRows, hasSeqScan, seqScanTables } = parsePostgresPlan(planRoot);
|
|
884
|
-
estimatedRows = totalRows;
|
|
885
|
-
isFullTableScan = hasSeqScan && estimatedRows > 5e3;
|
|
886
|
-
if (seqScanTables.length > 0) {
|
|
887
|
-
scanTargetDetail = `\uFF08\u8868: ${seqScanTables.join(", ")}\uFF09`;
|
|
888
|
-
}
|
|
889
|
-
}
|
|
890
|
-
} else if (dbType === "mysql" && rows.length > 0) {
|
|
891
|
-
const rawJson = Object.values(rows[0])[0];
|
|
892
|
-
const parsed = typeof rawJson === "string" ? JSON.parse(rawJson) : rawJson;
|
|
893
|
-
if (parsed) {
|
|
894
|
-
const { totalRows, hasAllScan, allScanTables } = parseMysqlPlan(parsed);
|
|
895
|
-
estimatedRows = totalRows;
|
|
896
|
-
isFullTableScan = hasAllScan && estimatedRows > 5e3;
|
|
897
|
-
if (allScanTables.length > 0) {
|
|
898
|
-
scanTargetDetail = `\uFF08\u8868: ${allScanTables.join(", ")}\uFF09`;
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
} else if (dbType === "sqlite") {
|
|
902
|
-
for (const row of rows) {
|
|
903
|
-
const detail = String(row["detail"] || Object.values(row)[0] || "");
|
|
904
|
-
if (detail.includes("SCAN TABLE") && !detail.includes("USING INDEX")) {
|
|
905
|
-
isFullTableScan = true;
|
|
906
|
-
scanTargetDetail = `\uFF08${detail}\uFF09`;
|
|
907
|
-
}
|
|
908
|
-
}
|
|
909
|
-
} else if (dbType === "duckdb") {
|
|
910
|
-
for (const row of rows) {
|
|
911
|
-
const detail = String(row["explain_value"] || Object.values(row)[0] || "");
|
|
912
|
-
if (detail.includes("SEQ_SCAN")) {
|
|
913
|
-
isFullTableScan = true;
|
|
914
|
-
scanTargetDetail = `\uFF08SEQ_SCAN\uFF09`;
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
} else if (dbType === "clickhouse") {
|
|
918
|
-
for (const row of rows) {
|
|
919
|
-
const line = String(Object.values(row)[0] || "");
|
|
920
|
-
const match = line.match(/rows:\s*(\d+)/i);
|
|
921
|
-
if (match) {
|
|
922
|
-
estimatedRows = Number(match[1]);
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
}
|
|
926
|
-
const exceedsBudget = estimatedRows > budget;
|
|
927
|
-
let costWarning;
|
|
928
|
-
if (exceedsBudget) {
|
|
929
|
-
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`;
|
|
930
|
-
} else if (isFullTableScan && blockFullTableScan && estimatedRows > budget / 2) {
|
|
931
|
-
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`;
|
|
932
|
-
}
|
|
933
|
-
return {
|
|
934
|
-
isValid: true,
|
|
935
|
-
estimatedRows,
|
|
936
|
-
isFullTableScan,
|
|
937
|
-
exceedsBudget,
|
|
938
|
-
costWarning,
|
|
939
|
-
planRaw: rows.slice(0, 5)
|
|
940
|
-
};
|
|
941
|
-
} catch (err) {
|
|
942
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
943
|
-
if (SQL_FAULT_RE.test(message)) {
|
|
944
|
-
return {
|
|
945
|
-
isValid: false,
|
|
946
|
-
estimatedRows: 0,
|
|
947
|
-
isFullTableScan: false,
|
|
948
|
-
exceedsBudget: false,
|
|
949
|
-
syntaxError: message,
|
|
950
|
-
costWarning: `\u6267\u884C\u8BA1\u5212\u9884\u68C0\u5931\u8D25\uFF08\u8BED\u6CD5\u6216\u8868/\u5B57\u6BB5\u4E0D\u5B58\u5728\uFF09\uFF1A${message}`
|
|
951
|
-
};
|
|
952
|
-
}
|
|
953
|
-
return {
|
|
954
|
-
isValid: true,
|
|
955
|
-
estimatedRows: 0,
|
|
956
|
-
isFullTableScan: false,
|
|
957
|
-
exceedsBudget: false,
|
|
958
|
-
degraded: true,
|
|
959
|
-
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}`
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
// src/gateway/queryPipeline.ts
|
|
965
|
-
async function executeSqlWithGuards(opts) {
|
|
966
|
-
const sql = opts.sql.trim();
|
|
967
|
-
assertReadOnlySql(sql);
|
|
968
|
-
const cacheKey = computeQueryHashKey(opts.sourceId, sql, opts.params);
|
|
969
|
-
if (!opts.skipCache) {
|
|
970
|
-
const cached = opts.cache.get(cacheKey);
|
|
971
|
-
if (cached) {
|
|
972
|
-
if (opts.logPrefix) {
|
|
973
|
-
console.log(
|
|
974
|
-
`[${opts.logPrefix}] \u547D\u4E2D MCP \u7F51\u5173\u67E5\u8BE2\u7F13\u5B58 (SQL Hash: ${cacheKey.sqlHash.slice(0, 8)})`
|
|
975
|
-
);
|
|
976
|
-
}
|
|
977
|
-
return {
|
|
978
|
-
data: cached.data,
|
|
979
|
-
cacheHit: true,
|
|
980
|
-
cachedAt: cached.cachedAt
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
}
|
|
984
|
-
let explainReport;
|
|
985
|
-
if (opts.dialectClient && !opts.bypassExplain) {
|
|
986
|
-
explainReport = await dryRunExplain(
|
|
987
|
-
opts.dialectClient.client,
|
|
988
|
-
opts.dialectClient.dbType,
|
|
989
|
-
sql,
|
|
990
|
-
opts.explainOptions,
|
|
991
|
-
opts.params
|
|
992
|
-
);
|
|
993
|
-
if (explainReport.degraded && opts.logPrefix) {
|
|
994
|
-
console.warn(
|
|
995
|
-
`[${opts.logPrefix}] EXPLAIN \u9884\u68C0\u964D\u7EA7\u653E\u884C: ${explainReport.costWarning}`
|
|
996
|
-
);
|
|
997
|
-
}
|
|
998
|
-
if (!explainReport.isValid) {
|
|
999
|
-
throw new Error(
|
|
1000
|
-
explainReport.costWarning || `SQL \u6267\u884C\u8BA1\u5212\u8BED\u6CD5\u9884\u68C0\u5931\u8D25: ${explainReport.syntaxError}`
|
|
1001
|
-
);
|
|
1002
|
-
}
|
|
1003
|
-
if (explainReport.exceedsBudget) {
|
|
1004
|
-
throw new Error(
|
|
1005
|
-
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"
|
|
1006
|
-
);
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
const data = await opts.execute();
|
|
1010
|
-
opts.cache.set(cacheKey, data, opts.cacheTtlMs);
|
|
1011
|
-
return { data, cacheHit: false, explainReport };
|
|
1012
|
-
}
|
|
1013
|
-
|
|
1014
|
-
// src/parseToolResult.ts
|
|
1015
|
-
function parseToolResult(res, toolLabel) {
|
|
1016
|
-
const r = res ?? {};
|
|
1017
|
-
const contentList = Array.isArray(r.content) ? r.content : [];
|
|
1018
|
-
if (r.isError) {
|
|
1019
|
-
const errorText = contentList.map((c) => c.text || "").join("\n");
|
|
1020
|
-
throw new Error(errorText || `${toolLabel} execution failed`);
|
|
1021
|
-
}
|
|
1022
|
-
const textOutput = contentList.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
|
|
1023
|
-
try {
|
|
1024
|
-
return JSON.parse(textOutput);
|
|
1025
|
-
} catch {
|
|
1026
|
-
return textOutput;
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
|
|
1030
|
-
// src/gateway/queryGateway.ts
|
|
1031
|
-
var TABLE_IDENTIFIER_RE = /^[A-Za-z_][\w$]*(\.[A-Za-z_][\w$]*)*$/;
|
|
1032
|
-
var QueryGateway = class {
|
|
1033
|
-
cache;
|
|
1034
|
-
manager;
|
|
1035
|
-
config;
|
|
1036
|
-
constructor(manager, config, sharedCache) {
|
|
1037
|
-
this.manager = manager;
|
|
1038
|
-
this.config = config ?? {};
|
|
1039
|
-
this.cache = sharedCache ?? new QueryCacheManager({
|
|
1040
|
-
maxEntries: config?.maxCacheEntries,
|
|
1041
|
-
defaultTtlMs: config?.defaultCacheTtlMs
|
|
1042
|
-
});
|
|
1043
|
-
}
|
|
1044
|
-
/**
|
|
1045
|
-
* 按数据源 ID 与工具原名检索已绑定的工具调用契约
|
|
1046
|
-
*/
|
|
1047
|
-
async getTool(sourceId, toolName) {
|
|
1048
|
-
const conf = this.manager.get(sourceId);
|
|
1049
|
-
if (!conf || conf.enabled === false) return void 0;
|
|
1050
|
-
const tools = await this.manager.tools(conf);
|
|
1051
|
-
return tools.find(
|
|
1052
|
-
(t) => t.originalName === toolName || t.name === `${sourceId}_${toolName}`
|
|
1053
|
-
);
|
|
1054
|
-
}
|
|
1055
|
-
/**
|
|
1056
|
-
* 核心方法:执行 SQL 查询(流经共享守卫管线)
|
|
1057
|
-
*/
|
|
1058
|
-
async executeQuery(args) {
|
|
1059
|
-
const { sourceId, sql, params, skipCache, bypassExplain, cacheTtlMs } = args;
|
|
1060
|
-
const startTime = Date.now();
|
|
1061
|
-
const conf = this.manager.get(sourceId);
|
|
1062
|
-
if (!conf || conf.enabled === false) {
|
|
1063
|
-
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u5C31\u7EEA\u6216\u672A\u542F\u7528`);
|
|
1064
|
-
}
|
|
1065
|
-
const result = await executeSqlWithGuards({
|
|
1066
|
-
sourceId,
|
|
1067
|
-
sql,
|
|
1068
|
-
params,
|
|
1069
|
-
skipCache,
|
|
1070
|
-
bypassExplain,
|
|
1071
|
-
cacheTtlMs,
|
|
1072
|
-
dialectClient: this.manager.getDialectClient?.(sourceId),
|
|
1073
|
-
cache: this.cache,
|
|
1074
|
-
explainOptions: this.config.explainOptions,
|
|
1075
|
-
logPrefix: `Gateway ${sourceId}`,
|
|
1076
|
-
execute: async () => {
|
|
1077
|
-
const toolBinding = await this.getTool(sourceId, "execute_sql");
|
|
1078
|
-
if (!toolBinding) {
|
|
1079
|
-
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u66B4\u9732 execute_sql \u5DE5\u5177\u63A5\u53E3`);
|
|
1080
|
-
}
|
|
1081
|
-
const conn = await this.manager.connect(conf);
|
|
1082
|
-
const raw = await conn.callTool("execute_sql", {
|
|
1083
|
-
sql,
|
|
1084
|
-
...params !== void 0 ? { params } : {}
|
|
1085
|
-
});
|
|
1086
|
-
const parsed = parseToolResult(raw, "tool execute_sql");
|
|
1087
|
-
let rows = [];
|
|
1088
|
-
let rowCount = 0;
|
|
1089
|
-
if (parsed && typeof parsed === "object") {
|
|
1090
|
-
if (!Array.isArray(parsed) && Array.isArray(parsed.rows)) {
|
|
1091
|
-
rows = parsed.rows;
|
|
1092
|
-
rowCount = typeof parsed.rowCount === "number" ? parsed.rowCount : rows.length;
|
|
1093
|
-
} else if (Array.isArray(parsed)) {
|
|
1094
|
-
rows = parsed;
|
|
1095
|
-
rowCount = rows.length;
|
|
1096
|
-
}
|
|
1097
|
-
}
|
|
1098
|
-
return { rows, rowCount };
|
|
1099
|
-
}
|
|
1100
|
-
});
|
|
1101
|
-
return {
|
|
1102
|
-
rows: result.data.rows,
|
|
1103
|
-
rowCount: result.data.rowCount,
|
|
1104
|
-
cacheHit: result.cacheHit,
|
|
1105
|
-
cachedAt: result.cachedAt,
|
|
1106
|
-
durationMs: Date.now() - startTime,
|
|
1107
|
-
explainReport: result.explainReport
|
|
1108
|
-
};
|
|
1109
|
-
}
|
|
1110
|
-
/**
|
|
1111
|
-
* 两阶段发现第一阶段:获取全量数据源及其表名概览(不含详细字段,防上下文撑爆)
|
|
1112
|
-
*/
|
|
1113
|
-
async listCatalogs() {
|
|
1114
|
-
const list = this.manager.list().filter((c) => c.enabled !== false);
|
|
1115
|
-
const results = [];
|
|
1116
|
-
for (const item of list) {
|
|
1117
|
-
const listTool = await this.getTool(item.id, "list_tables");
|
|
1118
|
-
let tables = [];
|
|
1119
|
-
if (listTool) {
|
|
1120
|
-
try {
|
|
1121
|
-
const res = await listTool.call({});
|
|
1122
|
-
if (res && Array.isArray(res.tables)) {
|
|
1123
|
-
tables = res.tables.map(
|
|
1124
|
-
(t) => typeof t === "string" ? t : String(t?.table ?? "")
|
|
1125
|
-
).filter(Boolean);
|
|
1126
|
-
}
|
|
1127
|
-
} catch {
|
|
1128
|
-
tables = [];
|
|
1129
|
-
}
|
|
1130
|
-
}
|
|
1131
|
-
results.push({
|
|
1132
|
-
sourceId: item.id,
|
|
1133
|
-
name: item.name,
|
|
1134
|
-
type: item.dbType ?? item.kind,
|
|
1135
|
-
tables
|
|
1136
|
-
});
|
|
1137
|
-
}
|
|
1138
|
-
return results;
|
|
1139
|
-
}
|
|
1140
|
-
/**
|
|
1141
|
-
* 两阶段发现第二阶段:按需拉取特定表的详细 Schema 与前 3 条样本数据
|
|
1142
|
-
*/
|
|
1143
|
-
async describeTableResource(sourceId, tableName) {
|
|
1144
|
-
if (!TABLE_IDENTIFIER_RE.test(tableName)) {
|
|
1145
|
-
throw new Error(`\u975E\u6CD5\u8868\u540D\u6807\u8BC6\u7B26: ${tableName}`);
|
|
1146
|
-
}
|
|
1147
|
-
const describeTool = await this.getTool(sourceId, "describe_table");
|
|
1148
|
-
if (!describeTool) {
|
|
1149
|
-
throw new Error(`\u6570\u636E\u6E90 [${sourceId}] \u672A\u63D0\u4F9B describe_table \u5DE5\u5177`);
|
|
1150
|
-
}
|
|
1151
|
-
const descRes = await describeTool.call({
|
|
1152
|
-
table_name: tableName,
|
|
1153
|
-
table: tableName
|
|
1154
|
-
});
|
|
1155
|
-
const columns = [];
|
|
1156
|
-
if (descRes && Array.isArray(descRes.columns)) {
|
|
1157
|
-
for (const col of descRes.columns) {
|
|
1158
|
-
columns.push({
|
|
1159
|
-
name: String(col.column || col.name),
|
|
1160
|
-
type: String(col.type || "string"),
|
|
1161
|
-
comment: col.comment ? String(col.comment) : void 0
|
|
1162
|
-
});
|
|
1163
|
-
}
|
|
1164
|
-
}
|
|
1165
|
-
let sampleRows = [];
|
|
1166
|
-
try {
|
|
1167
|
-
const sampleRes = await this.executeQuery({
|
|
1168
|
-
sourceId,
|
|
1169
|
-
sql: `SELECT * FROM ${tableName} LIMIT 3`,
|
|
1170
|
-
skipCache: false,
|
|
1171
|
-
bypassExplain: true
|
|
1172
|
-
});
|
|
1173
|
-
sampleRows = sampleRes.rows;
|
|
1174
|
-
} catch {
|
|
1175
|
-
sampleRows = [];
|
|
1176
|
-
}
|
|
1177
|
-
return {
|
|
1178
|
-
sourceId,
|
|
1179
|
-
tableName,
|
|
1180
|
-
columns,
|
|
1181
|
-
sampleRows
|
|
1182
|
-
};
|
|
1183
|
-
}
|
|
1184
|
-
/**
|
|
1185
|
-
* 清除网关缓存(共享实例时等同清除该源的全部缓存)
|
|
1186
|
-
*/
|
|
1187
|
-
invalidateCache(sourceId) {
|
|
1188
|
-
this.cache.invalidate(sourceId);
|
|
1189
|
-
}
|
|
1190
|
-
getCacheManager() {
|
|
1191
|
-
return this.cache;
|
|
1192
|
-
}
|
|
1193
|
-
};
|
|
1194
|
-
var McpGateway = QueryGateway;
|
|
1195
|
-
|
|
1196
690
|
// src/connectors/file/fileStore.ts
|
|
1197
691
|
import fs2 from "fs/promises";
|
|
1198
692
|
import path2 from "path";
|
|
@@ -1464,341 +958,6 @@ function duckDbPath(filesDir, sourceId) {
|
|
|
1464
958
|
return path2.join(sourceDir(filesDir, sourceId), FILE_SOURCE_DB_FILENAME);
|
|
1465
959
|
}
|
|
1466
960
|
|
|
1467
|
-
// src/schema/card.ts
|
|
1468
|
-
var LOW_CARDINALITY_THRESHOLD = 50;
|
|
1469
|
-
var TOP_VALUES_MAX = 10;
|
|
1470
|
-
var CARD_MAX_TABLES = 50;
|
|
1471
|
-
var PROFILE_MAX_COLUMNS = 20;
|
|
1472
|
-
var TOP_VALUE_QUERIES_PER_TABLE = 10;
|
|
1473
|
-
var CARD_RENDER_BUDGET_BYTES = 2048;
|
|
1474
|
-
var CARD_STORE_MAX_BYTES = 64 * 1024;
|
|
1475
|
-
var NUMERIC_OR_DATE_RE = /int|numeric|decimal|double|float|real|number|date|time|hugeint|bigint|smallint|tinyint/i;
|
|
1476
|
-
function isNumericOrDate(type) {
|
|
1477
|
-
return NUMERIC_OR_DATE_RE.test(type);
|
|
1478
|
-
}
|
|
1479
|
-
function normalizeCellValue(value) {
|
|
1480
|
-
if (value === null || value === void 0) return "";
|
|
1481
|
-
if (typeof value === "bigint") return value.toString();
|
|
1482
|
-
if (value instanceof Date) return value.toISOString();
|
|
1483
|
-
return String(value);
|
|
1484
|
-
}
|
|
1485
|
-
function buildSchemaCard(input) {
|
|
1486
|
-
let truncated = false;
|
|
1487
|
-
const tables = [];
|
|
1488
|
-
for (const profile of input.profiles.slice(0, CARD_MAX_TABLES)) {
|
|
1489
|
-
const columns = profile.columns.slice(0, PROFILE_MAX_COLUMNS).map((col) => {
|
|
1490
|
-
const out = { name: col.column, type: col.type };
|
|
1491
|
-
const card2 = profile.cardinalities?.[col.column];
|
|
1492
|
-
if (card2 !== void 0 && card2 <= LOW_CARDINALITY_THRESHOLD) {
|
|
1493
|
-
out.cardinality = card2;
|
|
1494
|
-
const tops = profile.topValues?.[col.column];
|
|
1495
|
-
if (tops && tops.length > 0) {
|
|
1496
|
-
out.topValues = tops.slice(0, TOP_VALUES_MAX);
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
const range = profile.ranges?.[col.column];
|
|
1500
|
-
if (range && isNumericOrDate(col.type)) {
|
|
1501
|
-
out.min = range.min;
|
|
1502
|
-
out.max = range.max;
|
|
1503
|
-
}
|
|
1504
|
-
return out;
|
|
1505
|
-
});
|
|
1506
|
-
if (profile.columns.length > PROFILE_MAX_COLUMNS) truncated = true;
|
|
1507
|
-
tables.push({
|
|
1508
|
-
name: profile.name,
|
|
1509
|
-
...profile.rowCount !== void 0 ? { rowCount: profile.rowCount } : {},
|
|
1510
|
-
columns
|
|
1511
|
-
});
|
|
1512
|
-
}
|
|
1513
|
-
if (input.profiles.length > CARD_MAX_TABLES) truncated = true;
|
|
1514
|
-
let card = {
|
|
1515
|
-
sourceId: input.sourceId,
|
|
1516
|
-
generatedAt: input.generatedAt ?? Date.now(),
|
|
1517
|
-
kind: "db-like",
|
|
1518
|
-
tables,
|
|
1519
|
-
...input.allTables && input.allTables.length > 0 ? { allTables: input.allTables } : {},
|
|
1520
|
-
truncated
|
|
1521
|
-
};
|
|
1522
|
-
while (JSON.stringify(card).length > CARD_STORE_MAX_BYTES && card.tables.length > 0) {
|
|
1523
|
-
truncated = true;
|
|
1524
|
-
const withTops = card.tables.some((t) => t.columns.some((c) => c.topValues));
|
|
1525
|
-
if (withTops) {
|
|
1526
|
-
card = {
|
|
1527
|
-
...card,
|
|
1528
|
-
truncated,
|
|
1529
|
-
tables: card.tables.map((t) => ({
|
|
1530
|
-
...t,
|
|
1531
|
-
columns: t.columns.map((c) => {
|
|
1532
|
-
const { topValues, ...rest } = c;
|
|
1533
|
-
void topValues;
|
|
1534
|
-
return rest;
|
|
1535
|
-
})
|
|
1536
|
-
}))
|
|
1537
|
-
};
|
|
1538
|
-
} else if (card.tables.length > 1) {
|
|
1539
|
-
card = {
|
|
1540
|
-
...card,
|
|
1541
|
-
truncated,
|
|
1542
|
-
tables: card.tables.slice(0, Math.max(1, Math.floor(card.tables.length / 2)))
|
|
1543
|
-
};
|
|
1544
|
-
} else {
|
|
1545
|
-
const only = card.tables[0];
|
|
1546
|
-
if (only.columns.length <= 1) break;
|
|
1547
|
-
card = {
|
|
1548
|
-
...card,
|
|
1549
|
-
truncated,
|
|
1550
|
-
tables: [
|
|
1551
|
-
{ ...only, columns: only.columns.slice(0, Math.max(1, Math.floor(only.columns.length / 2))) }
|
|
1552
|
-
]
|
|
1553
|
-
};
|
|
1554
|
-
}
|
|
1555
|
-
}
|
|
1556
|
-
return { ...card, truncated };
|
|
1557
|
-
}
|
|
1558
|
-
var BUSINESS_SYNONYM_MAP = {
|
|
1559
|
-
order: ["\u8BA2\u5355", "\u4EA4\u6613", "\u5DE5\u5355", "\u6210\u5355"],
|
|
1560
|
-
user: ["\u7528\u6237", "\u5BA2\u6237", "\u8D26\u53F7", "\u4E70\u5BB6", "\u4F1A\u5458", "\u4EBA\u7FA4"],
|
|
1561
|
-
customer: ["\u5BA2\u6237", "\u7528\u6237", "\u4E70\u5BB6", "\u5BA2\u7FA4"],
|
|
1562
|
-
member: ["\u4F1A\u5458", "vip", "\u7528\u6237"],
|
|
1563
|
-
payment: ["\u652F\u4ED8", "\u4ED8\u6B3E", "\u7ED3\u7B97", "\u6536\u6B3E"],
|
|
1564
|
-
pay: ["\u652F\u4ED8", "\u4ED8\u6B3E", "\u7ED3\u7B97"],
|
|
1565
|
-
product: ["\u5546\u54C1", "\u4EA7\u54C1", "\u7269\u6599", "\u54C1\u7C7B", "\u8D27\u54C1", "sku", "spu"],
|
|
1566
|
-
item: ["\u5546\u54C1", "\u6761\u76EE", "\u660E\u7EC6", "\u9879"],
|
|
1567
|
-
refund: ["\u9000\u6B3E", "\u552E\u540E", "\u9000\u8D27"],
|
|
1568
|
-
lead: ["\u7EBF\u7D22", "\u83B7\u5BA2", "\u6F5C\u5BA2", "\u5546\u673A"],
|
|
1569
|
-
channel: ["\u6E20\u9053", "\u6765\u6E90", "\u63A8\u5E7F", "\u6295\u653E"],
|
|
1570
|
-
amount: ["\u91D1\u989D", "\u603B\u989D", "\u4EA4\u6613\u989D", "\u94B1", "\u6570\u989D"],
|
|
1571
|
-
price: ["\u4EF7\u683C", "\u5355\u4EF7", "\u5BA2\u5355\u4EF7", "\u552E\u4EF7"],
|
|
1572
|
-
cost: ["\u6210\u672C", "\u8D39\u7528", "\u652F\u51FA", "\u5F00\u9500", "cac"],
|
|
1573
|
-
revenue: ["\u8425\u6536", "\u6536\u5165", "\u8425\u4E1A\u989D", "gmv"],
|
|
1574
|
-
log: ["\u65E5\u5FD7", "\u8BB0\u5F55", "\u8F68\u8FF9", "\u57CB\u70B9"],
|
|
1575
|
-
event: ["\u4E8B\u4EF6", "\u884C\u4E3A", "\u52A8\u4F5C"],
|
|
1576
|
-
issue: ["\u7F3A\u9677", "\u95EE\u9898", "bug", "\u4EFB\u52A1", "\u6545\u969C"],
|
|
1577
|
-
commit: ["\u63D0\u4EA4", "\u4EE3\u7801", "\u53D8\u66F4"]
|
|
1578
|
-
};
|
|
1579
|
-
function scoreTableRelevance(table, queryHint) {
|
|
1580
|
-
if (!queryHint || typeof queryHint !== "string") return 0;
|
|
1581
|
-
const q = queryHint.toLowerCase().trim();
|
|
1582
|
-
if (!q) return 0;
|
|
1583
|
-
let score = 0;
|
|
1584
|
-
const tblName = table.name.toLowerCase();
|
|
1585
|
-
if (q.includes(tblName)) score += 30;
|
|
1586
|
-
else if (tblName.includes(q)) score += 15;
|
|
1587
|
-
const tokens = q.split(/[\s,._/\\:;!?'"()#@%^&*+-]+/).map((w) => w.trim()).filter((w) => w.length >= 2);
|
|
1588
|
-
for (const token of tokens) {
|
|
1589
|
-
if (tblName.includes(token)) score += 10;
|
|
1590
|
-
}
|
|
1591
|
-
for (const [enKey, cnList] of Object.entries(BUSINESS_SYNONYM_MAP)) {
|
|
1592
|
-
const tableMatchesEn = tblName.includes(enKey);
|
|
1593
|
-
const queryMatchesCn = cnList.some((cn) => q.includes(cn));
|
|
1594
|
-
if (tableMatchesEn && queryMatchesCn) {
|
|
1595
|
-
score += 25;
|
|
1596
|
-
}
|
|
1597
|
-
const tableMatchesCn = cnList.some((cn) => tblName.includes(cn));
|
|
1598
|
-
const queryMatchesEn = q.includes(enKey);
|
|
1599
|
-
if (tableMatchesCn && queryMatchesEn) {
|
|
1600
|
-
score += 25;
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
for (const col of table.columns) {
|
|
1604
|
-
const colName = col.name.toLowerCase();
|
|
1605
|
-
if (q.includes(colName)) score += 5;
|
|
1606
|
-
for (const token of tokens) {
|
|
1607
|
-
if (colName === token) score += 3;
|
|
1608
|
-
else if (colName.includes(token)) score += 1;
|
|
1609
|
-
}
|
|
1610
|
-
for (const [enKey, cnList] of Object.entries(BUSINESS_SYNONYM_MAP)) {
|
|
1611
|
-
if (colName.includes(enKey) && cnList.some((cn) => q.includes(cn))) {
|
|
1612
|
-
score += 8;
|
|
1613
|
-
}
|
|
1614
|
-
}
|
|
1615
|
-
}
|
|
1616
|
-
return score;
|
|
1617
|
-
}
|
|
1618
|
-
function renderCardForPrompt(card, budgetOrOptions = CARD_RENDER_BUDGET_BYTES) {
|
|
1619
|
-
const opts = typeof budgetOrOptions === "number" ? { budgetBytes: budgetOrOptions } : budgetOrOptions ?? {};
|
|
1620
|
-
const budgetBytes = opts.budgetBytes ?? CARD_RENDER_BUDGET_BYTES;
|
|
1621
|
-
const queryHint = opts.queryHint;
|
|
1622
|
-
const generatedAt = new Date(card.generatedAt).toISOString().slice(0, 16).replace("T", " ");
|
|
1623
|
-
const lines = [];
|
|
1624
|
-
const isToolsCard = card.kind === "tools-only" || card.kind === "mcp";
|
|
1625
|
-
const header = isToolsCard ? `### \u6570\u636E\u6E90 ${card.sourceId} \u5DE5\u5177\u5361\uFF08\u751F\u6210\u4E8E ${generatedAt}\uFF09` : `### \u6570\u636E\u6E90 ${card.sourceId} \u7ED3\u6784\u5361\uFF08\u751F\u6210\u4E8E ${generatedAt}\uFF09`;
|
|
1626
|
-
lines.push(header);
|
|
1627
|
-
if (isToolsCard) {
|
|
1628
|
-
for (const t of card.toolSummaries ?? []) {
|
|
1629
|
-
lines.push(`- ${t.name}${t.description ? `\uFF1A${t.description}` : ""}`);
|
|
1630
|
-
}
|
|
1631
|
-
} else {
|
|
1632
|
-
const sorted = [...card.tables].sort((a, b) => {
|
|
1633
|
-
const scoreA = scoreTableRelevance(a, queryHint);
|
|
1634
|
-
const scoreB = scoreTableRelevance(b, queryHint);
|
|
1635
|
-
if (scoreA !== scoreB) return scoreB - scoreA;
|
|
1636
|
-
return (b.rowCount ?? 0) - (a.rowCount ?? 0);
|
|
1637
|
-
});
|
|
1638
|
-
const renderedTableNames = /* @__PURE__ */ new Set();
|
|
1639
|
-
for (const table of sorted) {
|
|
1640
|
-
renderedTableNames.add(table.name);
|
|
1641
|
-
const cols = table.columns.map((c) => {
|
|
1642
|
-
let s = `${c.name} ${c.type}`;
|
|
1643
|
-
if (c.cardinality !== void 0) {
|
|
1644
|
-
s += `(${c.cardinality} \u503C`;
|
|
1645
|
-
if (c.topValues && c.topValues.length > 0) {
|
|
1646
|
-
s += `: ${c.topValues.slice(0, 5).join("/")}${c.topValues.length > 5 ? "/\u2026" : ""}`;
|
|
1647
|
-
}
|
|
1648
|
-
s += ")";
|
|
1649
|
-
}
|
|
1650
|
-
if (c.min !== void 0 && c.max !== void 0) {
|
|
1651
|
-
s += `[${c.min} ~ ${c.max}]`;
|
|
1652
|
-
}
|
|
1653
|
-
return s;
|
|
1654
|
-
}).join("\uFF0C");
|
|
1655
|
-
const rows = table.rowCount !== void 0 ? `\u7EA6 ${table.rowCount.toLocaleString()} \u884C` : "";
|
|
1656
|
-
lines.push(`- ${table.name}${rows ? `\uFF08${rows}\uFF09` : ""}\uFF1A${cols}`);
|
|
1657
|
-
}
|
|
1658
|
-
if (card.allTables && card.allTables.length > 0) {
|
|
1659
|
-
const remaining = card.allTables.filter((t) => !renderedTableNames.has(t));
|
|
1660
|
-
if (remaining.length > 0) {
|
|
1661
|
-
lines.push(`- \u5176\u4F59\u53EF\u7528\u6570\u636E\u8868\u6E05\u5355\uFF08\u5171 ${remaining.length} \u5F20\uFF09\uFF1A${remaining.join("\u3001")}`);
|
|
1662
|
-
}
|
|
1663
|
-
}
|
|
1664
|
-
}
|
|
1665
|
-
if (card.truncated) lines.push("\uFF08\u5185\u5BB9\u5DF2\u6309\u9884\u7B97\u622A\u65AD\uFF09");
|
|
1666
|
-
const TRUNCATION_NOTE = "\uFF08\u5185\u5BB9\u5DF2\u6309\u9884\u7B97\u622A\u65AD\uFF09";
|
|
1667
|
-
const fits = (ls) => Buffer.byteLength(ls.join("\n"), "utf-8") <= budgetBytes;
|
|
1668
|
-
if (fits(lines)) return lines.join("\n");
|
|
1669
|
-
const headLine = lines[0];
|
|
1670
|
-
const body = lines.slice(1).filter((l) => !l.includes("\u5DF2\u6309\u9884\u7B97\u622A\u65AD"));
|
|
1671
|
-
while (body.length > 0) {
|
|
1672
|
-
body.pop();
|
|
1673
|
-
const candidate = [headLine, ...body, TRUNCATION_NOTE];
|
|
1674
|
-
if (fits(candidate)) return candidate.join("\n");
|
|
1675
|
-
}
|
|
1676
|
-
return headLine;
|
|
1677
|
-
}
|
|
1678
|
-
async function collectTableProfile(probe, table, opts) {
|
|
1679
|
-
const q = opts.quoteIdent;
|
|
1680
|
-
const maxColumns = opts.maxColumns ?? PROFILE_MAX_COLUMNS;
|
|
1681
|
-
const columns = (await probe.describeTable(table)).slice(0, maxColumns);
|
|
1682
|
-
if (columns.length === 0) {
|
|
1683
|
-
return { name: table, columns: [] };
|
|
1684
|
-
}
|
|
1685
|
-
const selects = [`COUNT(*) AS "rowCount"`];
|
|
1686
|
-
columns.forEach((col, i) => {
|
|
1687
|
-
selects.push(`COUNT(DISTINCT ${q(col.column)}) AS "card_${i}"`);
|
|
1688
|
-
if (isNumericOrDate(col.type)) {
|
|
1689
|
-
selects.push(`MIN(${q(col.column)}) AS "min_${i}"`);
|
|
1690
|
-
selects.push(`MAX(${q(col.column)}) AS "max_${i}"`);
|
|
1691
|
-
}
|
|
1692
|
-
});
|
|
1693
|
-
const aggregateRows = await probe.query(
|
|
1694
|
-
`SELECT ${selects.join(", ")} FROM ${q(table)}`
|
|
1695
|
-
);
|
|
1696
|
-
const agg = aggregateRows[0] ?? {};
|
|
1697
|
-
const cardinalities = {};
|
|
1698
|
-
const ranges = {};
|
|
1699
|
-
columns.forEach((col, i) => {
|
|
1700
|
-
const cardRaw = agg[`card_${i}`];
|
|
1701
|
-
if (cardRaw !== void 0 && cardRaw !== null) {
|
|
1702
|
-
cardinalities[col.column] = Number(normalizeCellValue(cardRaw));
|
|
1703
|
-
}
|
|
1704
|
-
const minRaw = agg[`min_${i}`];
|
|
1705
|
-
const maxRaw = agg[`max_${i}`];
|
|
1706
|
-
if (minRaw !== void 0 && minRaw !== null) {
|
|
1707
|
-
ranges[col.column] = {
|
|
1708
|
-
min: normalizeCellValue(minRaw),
|
|
1709
|
-
max: normalizeCellValue(maxRaw)
|
|
1710
|
-
};
|
|
1711
|
-
}
|
|
1712
|
-
});
|
|
1713
|
-
const topValues = {};
|
|
1714
|
-
const lowCardCols = columns.filter(
|
|
1715
|
-
(col) => cardinalities[col.column] !== void 0 && cardinalities[col.column] > 0 && cardinalities[col.column] <= LOW_CARDINALITY_THRESHOLD
|
|
1716
|
-
);
|
|
1717
|
-
for (const col of lowCardCols.slice(0, TOP_VALUE_QUERIES_PER_TABLE)) {
|
|
1718
|
-
try {
|
|
1719
|
-
const rows = await probe.query(
|
|
1720
|
-
`SELECT ${q(col.column)} AS "v", COUNT(*) AS "c" FROM ${q(table)} GROUP BY ${q(col.column)} ORDER BY "c" DESC LIMIT ${TOP_VALUES_MAX}`
|
|
1721
|
-
);
|
|
1722
|
-
topValues[col.column] = rows.map((r) => normalizeCellValue(r.v));
|
|
1723
|
-
} catch {
|
|
1724
|
-
}
|
|
1725
|
-
}
|
|
1726
|
-
return {
|
|
1727
|
-
name: table,
|
|
1728
|
-
rowCount: agg.rowCount !== void 0 && agg.rowCount !== null ? Number(normalizeCellValue(agg.rowCount)) : void 0,
|
|
1729
|
-
columns,
|
|
1730
|
-
cardinalities,
|
|
1731
|
-
ranges,
|
|
1732
|
-
topValues
|
|
1733
|
-
};
|
|
1734
|
-
}
|
|
1735
|
-
async function collectSchemaCard(input) {
|
|
1736
|
-
const tables = await input.probe.listTables();
|
|
1737
|
-
const allTables = tables.map((t) => t.table);
|
|
1738
|
-
const profiles = [];
|
|
1739
|
-
for (const t of tables.slice(0, CARD_MAX_TABLES)) {
|
|
1740
|
-
try {
|
|
1741
|
-
profiles.push(
|
|
1742
|
-
await collectTableProfile(input.probe, t.table, {
|
|
1743
|
-
quoteIdent: input.quoteIdent
|
|
1744
|
-
})
|
|
1745
|
-
);
|
|
1746
|
-
} catch (err) {
|
|
1747
|
-
console.warn(
|
|
1748
|
-
`[schema-card] \u5256\u6790\u8868 ${t.table} \u5931\u8D25\uFF08\u8DF3\u8FC7\uFF09:`,
|
|
1749
|
-
err instanceof Error ? err.message : err
|
|
1750
|
-
);
|
|
1751
|
-
}
|
|
1752
|
-
}
|
|
1753
|
-
return buildSchemaCard({
|
|
1754
|
-
sourceId: input.sourceId,
|
|
1755
|
-
profiles,
|
|
1756
|
-
allTables: allTables.length > profiles.length ? allTables : void 0
|
|
1757
|
-
});
|
|
1758
|
-
}
|
|
1759
|
-
|
|
1760
|
-
// src/schema/store.ts
|
|
1761
|
-
import fs3 from "fs/promises";
|
|
1762
|
-
import path3 from "path";
|
|
1763
|
-
var ID_RE = /^[\w-]+$/;
|
|
1764
|
-
function isValidSourceId(id) {
|
|
1765
|
-
return ID_RE.test(id) && id.length <= 100;
|
|
1766
|
-
}
|
|
1767
|
-
function isSchemaCard(value) {
|
|
1768
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
1769
|
-
return false;
|
|
1770
|
-
}
|
|
1771
|
-
const v = value;
|
|
1772
|
-
return typeof v.sourceId === "string" && typeof v.generatedAt === "number" && (v.kind === "db-like" || v.kind === "tools-only" || v.kind === "mcp") && Array.isArray(v.tables) && typeof v.truncated === "boolean";
|
|
1773
|
-
}
|
|
1774
|
-
async function readSchemaCard(dir, sourceId) {
|
|
1775
|
-
if (!isValidSourceId(sourceId)) return null;
|
|
1776
|
-
try {
|
|
1777
|
-
const raw = await fs3.readFile(path3.join(dir, `${sourceId}.json`), "utf-8");
|
|
1778
|
-
const parsed = JSON.parse(raw);
|
|
1779
|
-
return isSchemaCard(parsed) ? parsed : null;
|
|
1780
|
-
} catch {
|
|
1781
|
-
return null;
|
|
1782
|
-
}
|
|
1783
|
-
}
|
|
1784
|
-
async function writeSchemaCard(dir, card) {
|
|
1785
|
-
if (!isValidSourceId(card.sourceId)) {
|
|
1786
|
-
throw new Error(`\u975E\u6CD5 sourceId: ${card.sourceId}`);
|
|
1787
|
-
}
|
|
1788
|
-
const text = JSON.stringify(card, null, 2);
|
|
1789
|
-
if (Buffer.byteLength(text, "utf-8") > CARD_STORE_MAX_BYTES) {
|
|
1790
|
-
throw new Error(
|
|
1791
|
-
`\u7ED3\u6784\u5361\u8D85\u8FC7 ${CARD_STORE_MAX_BYTES} \u5B57\u8282\u4E0A\u9650\uFF08\u6784\u5EFA\u9884\u7B97\u5931\u5B88\uFF09: ${card.sourceId}`
|
|
1792
|
-
);
|
|
1793
|
-
}
|
|
1794
|
-
await fs3.mkdir(dir, { recursive: true });
|
|
1795
|
-
await fs3.writeFile(path3.join(dir, `${card.sourceId}.json`), text, "utf-8");
|
|
1796
|
-
}
|
|
1797
|
-
async function deleteSchemaCard(dir, sourceId) {
|
|
1798
|
-
if (!isValidSourceId(sourceId)) return;
|
|
1799
|
-
await fs3.rm(path3.join(dir, `${sourceId}.json`), { force: true });
|
|
1800
|
-
}
|
|
1801
|
-
|
|
1802
961
|
// src/schema/cardLifecycle.ts
|
|
1803
962
|
function createSchemaCardLifecycle(opts) {
|
|
1804
963
|
const { cardsDir, buildCard } = opts;
|
|
@@ -1910,8 +1069,8 @@ function describeDynamicSource(s) {
|
|
|
1910
1069
|
}
|
|
1911
1070
|
function createDatasourceManager(opts) {
|
|
1912
1071
|
const { configPath } = opts;
|
|
1913
|
-
const filesDir = opts.filesDir ??
|
|
1914
|
-
const schemaCardsDir = opts.schemaCardsDir ??
|
|
1072
|
+
const filesDir = opts.filesDir ?? path3.join(path3.dirname(configPath), "..", "data", "files");
|
|
1073
|
+
const schemaCardsDir = opts.schemaCardsDir ?? path3.join(path3.dirname(configPath), "..", "data", "schema-cards");
|
|
1915
1074
|
let configCache = null;
|
|
1916
1075
|
let lastMtimeMs = 0;
|
|
1917
1076
|
const connCache = /* @__PURE__ */ new Map();
|
|
@@ -1970,7 +1129,7 @@ function createDatasourceManager(opts) {
|
|
|
1970
1129
|
});
|
|
1971
1130
|
const readConfig = () => {
|
|
1972
1131
|
try {
|
|
1973
|
-
const stat =
|
|
1132
|
+
const stat = fs3.statSync(configPath);
|
|
1974
1133
|
if (configCache === null || stat.mtimeMs !== lastMtimeMs) {
|
|
1975
1134
|
configCache = loadConfigFile(configPath);
|
|
1976
1135
|
lastMtimeMs = stat.mtimeMs;
|
|
@@ -1986,7 +1145,7 @@ function createDatasourceManager(opts) {
|
|
|
1986
1145
|
writeConfigFile(c, configPath);
|
|
1987
1146
|
configCache = c;
|
|
1988
1147
|
try {
|
|
1989
|
-
lastMtimeMs =
|
|
1148
|
+
lastMtimeMs = fs3.statSync(configPath).mtimeMs;
|
|
1990
1149
|
} catch {
|
|
1991
1150
|
lastMtimeMs = Date.now();
|
|
1992
1151
|
}
|
|
@@ -2250,116 +1409,6 @@ function mergeToolSets(target, incoming, sourceId) {
|
|
|
2250
1409
|
}
|
|
2251
1410
|
}
|
|
2252
1411
|
|
|
2253
|
-
// src/certified/certifiedStore.ts
|
|
2254
|
-
import fs5 from "fs";
|
|
2255
|
-
import path5 from "path";
|
|
2256
|
-
var CertifiedQueryStore = class {
|
|
2257
|
-
queries = /* @__PURE__ */ new Map();
|
|
2258
|
-
configPath;
|
|
2259
|
-
initialQueries = [];
|
|
2260
|
-
lastMtimeMs = 0;
|
|
2261
|
-
constructor(options) {
|
|
2262
|
-
this.configPath = options?.configPath;
|
|
2263
|
-
if (options?.initialQueries) {
|
|
2264
|
-
this.initialQueries = options.initialQueries;
|
|
2265
|
-
for (const q of options.initialQueries) {
|
|
2266
|
-
this.queries.set(q.id, q);
|
|
2267
|
-
}
|
|
2268
|
-
}
|
|
2269
|
-
if (this.configPath) {
|
|
2270
|
-
this.loadFromFile(this.configPath);
|
|
2271
|
-
this.touchMtime();
|
|
2272
|
-
}
|
|
2273
|
-
}
|
|
2274
|
-
touchMtime() {
|
|
2275
|
-
try {
|
|
2276
|
-
this.lastMtimeMs = this.configPath ? fs5.statSync(this.configPath).mtimeMs : 0;
|
|
2277
|
-
} catch {
|
|
2278
|
-
this.lastMtimeMs = 0;
|
|
2279
|
-
}
|
|
2280
|
-
}
|
|
2281
|
-
/**
|
|
2282
|
-
* 配置文件 mtime 热加载:文件变更后重建内存索引(含 initialQueries 垫底)。
|
|
2283
|
-
* 每次语义路由前调用一次(一次 stat 的成本),免去改配置必须重启进程。
|
|
2284
|
-
*/
|
|
2285
|
-
reloadIfChanged() {
|
|
2286
|
-
if (!this.configPath) return;
|
|
2287
|
-
let mtime = 0;
|
|
2288
|
-
try {
|
|
2289
|
-
mtime = fs5.statSync(this.configPath).mtimeMs;
|
|
2290
|
-
} catch {
|
|
2291
|
-
return;
|
|
2292
|
-
}
|
|
2293
|
-
if (mtime === this.lastMtimeMs) return;
|
|
2294
|
-
this.lastMtimeMs = mtime;
|
|
2295
|
-
this.queries.clear();
|
|
2296
|
-
for (const q of this.initialQueries) {
|
|
2297
|
-
this.queries.set(q.id, q);
|
|
2298
|
-
}
|
|
2299
|
-
this.loadFromFile(this.configPath);
|
|
2300
|
-
}
|
|
2301
|
-
loadFromFile(filePath) {
|
|
2302
|
-
try {
|
|
2303
|
-
if (!fs5.existsSync(filePath)) return;
|
|
2304
|
-
const content = fs5.readFileSync(filePath, "utf-8");
|
|
2305
|
-
const parsed = JSON.parse(content);
|
|
2306
|
-
if (Array.isArray(parsed)) {
|
|
2307
|
-
for (const item of parsed) {
|
|
2308
|
-
if (item && item.id && item.sqlTemplate) {
|
|
2309
|
-
this.queries.set(item.id, item);
|
|
2310
|
-
}
|
|
2311
|
-
}
|
|
2312
|
-
}
|
|
2313
|
-
} catch (err) {
|
|
2314
|
-
console.warn(`[CertifiedQueryStore] \u52A0\u8F7D\u8BA4\u8BC1\u67E5\u8BE2\u914D\u7F6E\u5931\u8D25 (${filePath}):`, err);
|
|
2315
|
-
}
|
|
2316
|
-
}
|
|
2317
|
-
saveToFile(filePath) {
|
|
2318
|
-
const target = filePath || this.configPath;
|
|
2319
|
-
if (!target) return;
|
|
2320
|
-
try {
|
|
2321
|
-
const dir = path5.dirname(target);
|
|
2322
|
-
if (!fs5.existsSync(dir)) {
|
|
2323
|
-
fs5.mkdirSync(dir, { recursive: true });
|
|
2324
|
-
}
|
|
2325
|
-
const data = Array.from(this.queries.values());
|
|
2326
|
-
fs5.writeFileSync(target, JSON.stringify(data, null, 2), "utf-8");
|
|
2327
|
-
} catch (err) {
|
|
2328
|
-
console.warn(`[CertifiedQueryStore] \u4FDD\u5B58\u8BA4\u8BC1\u67E5\u8BE2\u914D\u7F6E\u5931\u8D25 (${target}):`, err);
|
|
2329
|
-
}
|
|
2330
|
-
}
|
|
2331
|
-
list(sourceId) {
|
|
2332
|
-
const all = Array.from(this.queries.values());
|
|
2333
|
-
if (!sourceId) return all;
|
|
2334
|
-
return all.filter((q) => q.sourceId === "*" || q.sourceId === sourceId);
|
|
2335
|
-
}
|
|
2336
|
-
get(id) {
|
|
2337
|
-
return this.queries.get(id);
|
|
2338
|
-
}
|
|
2339
|
-
upsert(query) {
|
|
2340
|
-
this.queries.set(query.id, {
|
|
2341
|
-
...query,
|
|
2342
|
-
certifiedAt: query.certifiedAt ?? Date.now()
|
|
2343
|
-
});
|
|
2344
|
-
if (this.configPath) {
|
|
2345
|
-
this.saveToFile();
|
|
2346
|
-
}
|
|
2347
|
-
}
|
|
2348
|
-
delete(id) {
|
|
2349
|
-
const res = this.queries.delete(id);
|
|
2350
|
-
if (res && this.configPath) {
|
|
2351
|
-
this.saveToFile();
|
|
2352
|
-
}
|
|
2353
|
-
return res;
|
|
2354
|
-
}
|
|
2355
|
-
clear() {
|
|
2356
|
-
this.queries.clear();
|
|
2357
|
-
}
|
|
2358
|
-
size() {
|
|
2359
|
-
return this.queries.size;
|
|
2360
|
-
}
|
|
2361
|
-
};
|
|
2362
|
-
|
|
2363
1412
|
// src/certified/semanticRouter.ts
|
|
2364
1413
|
function tokenizeText(text) {
|
|
2365
1414
|
if (!text) return [];
|