table-reconcile-mcp 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.js +446 -0
  2. package/package.json +25 -5
  3. package/README.md +0 -3
package/index.js ADDED
@@ -0,0 +1,446 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * table-reconcile-mcp —— 旭光云·两表对账助手 MCP Server(WorkBuddy 插件)
4
+ *
5
+ * 纯本地、不联网、零认证:用户说「把这两张表对一下」,AI 调这里跑出差异,
6
+ * 而不是给他一段提示词让他自己折腾。
7
+ *
8
+ * 两个工具:
9
+ * inspect_table 看一张表的列名 / 行数 / 样本,用来判断拿哪列当主键
10
+ * reconcile 两张表按主键对账,出「只在左 / 只在右 / 两边都有但对不上」
11
+ *
12
+ * 三条被判据踩出来的规矩(照抄,别改):
13
+ * 1. 列名三跳映射:逐字 → 同义 → 近似。用户表列名和标准列不一样是常态。
14
+ * 2. 长度 ≤2 字的列名不走近似:短名会用包含关系抢走长列(「金额」抢「应赔金额」)。
15
+ * 3. 绝不替用户改表:只读文件,差异只报告不落盘。
16
+ */
17
+ import fs from "node:fs";
18
+ import path from "node:path";
19
+ import readline from "node:readline";
20
+
21
+ const NAME = "table-reconcile";
22
+ const VERSION = "1.0.0";
23
+ const PROTOCOL = "2024-11-05";
24
+ const MAX_ROWS_OUT = 20; // 每类差异最多列 20 条,避免把上下文撑爆
25
+
26
+ /* ---------------- 读表 ---------------- */
27
+
28
+ function readText(p) {
29
+ const buf = fs.readFileSync(p);
30
+ let t = buf.toString("utf8");
31
+ // UTF-8 读出来有大量替换字符 → 大概率是 GBK,改用 gbk 解
32
+ if ((t.match(/\uFFFD/g) || []).length > 3) {
33
+ try {
34
+ t = new TextDecoder("gbk").decode(buf);
35
+ } catch {
36
+ /* 解不了就按 utf8 用,下面会提示 */
37
+ }
38
+ }
39
+ return t.replace(/^\uFEFF/, "");
40
+ }
41
+
42
+ function parseCsv(text) {
43
+ const rows = [];
44
+ let row = [], cur = "", q = false;
45
+ for (let i = 0; i < text.length; i++) {
46
+ const c = text[i];
47
+ if (q) {
48
+ if (c === '"') {
49
+ if (text[i + 1] === '"') { cur += '"'; i++; } else q = false;
50
+ } else cur += c;
51
+ } else if (c === '"') q = true;
52
+ else if (c === ",") { row.push(cur); cur = ""; }
53
+ else if (c === "\n") { row.push(cur); rows.push(row); row = []; cur = ""; }
54
+ else if (c === "\r") { /* 忽略 */ }
55
+ else cur += c;
56
+ }
57
+ if (cur !== "" || row.length) { row.push(cur); rows.push(row); }
58
+ return rows.filter((r) => r.some((c) => String(c).trim() !== ""));
59
+ }
60
+
61
+ function loadTable(p) {
62
+ if (!fs.existsSync(p)) throw new Error(`找不到文件:${p}`);
63
+ const ext = path.extname(p).toLowerCase();
64
+ if (ext && ext !== ".csv" && ext !== ".txt") {
65
+ throw new Error(
66
+ `只支持 CSV(当前是 ${ext})。请先在表格软件里「另存为 CSV」再对账——` +
67
+ `插件只读文件、不改你的原表。`
68
+ );
69
+ }
70
+ const rows = parseCsv(readText(p));
71
+ if (rows.length < 2) throw new Error(`表里没有数据行(只有表头或空文件):${p}`);
72
+ const head = rows[0].map((h) => String(h).trim());
73
+ const data = rows.slice(1).map((r) => {
74
+ const o = {};
75
+ head.forEach((h, i) => (o[h] = String(r[i] ?? "").trim()));
76
+ return o;
77
+ });
78
+ return { head, data, file: path.basename(p) };
79
+ }
80
+
81
+ /* ---------------- 列名映射 ---------------- */
82
+
83
+ const ALIAS_RULES = [
84
+ ["名称", "名"], ["编号", "号"], ["等级", "级别"], ["数量", "数"],
85
+ ["单价", "价格"], ["渠道", "途径"], ["类别", "类型"], ["场景", "用途"],
86
+ ["备注", "说明"], ["状态", "情况"], ["方式", "手段"], ["安排", "行程"],
87
+ ["分钟", "时长"], ["得分", "分数"], ["描述", "说明"], ["要点", "点"],
88
+ ["单位", "方"], ["金额", "金额"], ["日期", "日期"], ["合计", "总计"],
89
+ ];
90
+
91
+ function clean(s) {
92
+ return String(s ?? "").replace(/[\s ]+/g, "").trim();
93
+ }
94
+
95
+ /** 给一个列名在候选列里找对应,返回 {hit, how}
96
+ * strict=true 只走逐字与同义;strict=false 再加近似。
97
+ * 短名(≤2 字)只在 strict=false 时允许近似:同表内防抢列的限制,跨表映射不该照搬,
98
+ * 否则「应收金额」永远认不出「金额」。 */
99
+ function mapColumn(std, candidates, strict = false) {
100
+ const c = clean(std);
101
+ // 1) 逐字
102
+ for (const x of candidates) if (clean(x) === c) return { hit: x, how: "逐字" };
103
+ // 2) 同义
104
+ for (const [a, b] of ALIAS_RULES) {
105
+ if (c.includes(a)) {
106
+ const alt = clean(c.replace(a, b));
107
+ for (const x of candidates) if (clean(x) === alt) return { hit: x, how: `同义(${a}→${b})` };
108
+ }
109
+ if (c.includes(b)) {
110
+ const alt = clean(c.replace(b, a));
111
+ for (const x of candidates) if (clean(x) === alt) return { hit: x, how: `同义(${b}→${a})` };
112
+ }
113
+ }
114
+ if (strict) return { hit: null, how: "未匹配" };
115
+ // 3) 近似:长名优先由调用方排序保证,这里只判是否包含且长度接近
116
+ for (const x of candidates) {
117
+ const cx = clean(x);
118
+ if (cx && (cx.includes(c) || c.includes(cx)) && Math.abs(cx.length - c.length) <= 2) {
119
+ return { hit: x, how: "近似" };
120
+ }
121
+ }
122
+ return { hit: null, how: "未匹配" };
123
+ }
124
+
125
+ /** 左表全部列 → 右表列的一对一分派:先精确/同义,再剩余列走近似(长名优先) */
126
+ function mapAll(leftHead, rightHead, takenKey) {
127
+ const used = new Set(takenKey ? [takenKey] : []);
128
+ const free = () => rightHead.filter((h) => !used.has(h));
129
+ const pairs = [];
130
+ const pending = [];
131
+ for (const h of leftHead) {
132
+ const m = mapColumn(h, free(), true);
133
+ if (m.hit) { pairs.push({ left: h, right: m.hit, how: m.how }); used.add(m.hit); }
134
+ else pending.push(h);
135
+ }
136
+ pending.sort((a, b) => clean(b).length - clean(a).length);
137
+ for (const h of pending) {
138
+ const m = mapColumn(h, free(), false);
139
+ if (m.hit) { pairs.push({ left: h, right: m.hit, how: m.how }); used.add(m.hit); }
140
+ }
141
+ return pairs;
142
+ }
143
+
144
+ /* ---------------- 主键与数值列 ---------------- */
145
+
146
+ function keyScore(h) {
147
+ const c = clean(h);
148
+ let sc = 0;
149
+ if (/(编号|单号|代码|ID|Id|序号|号码)$/.test(c)) sc += 5;
150
+ else if (/号$/.test(c)) sc += 3;
151
+ if (/(名称|姓名|客户|日期|时间|状态|备注|类型|地址|渠道|金额)$/.test(c)) sc -= 3;
152
+ return sc;
153
+ }
154
+
155
+ /** 猜主键:唯一率只说明「能区分行」,不说明「是这把钥匙」。
156
+ * 第一版按「列名最短」挑,6 行小表里把「日期」当成了主键,对账全错位。 */
157
+ function guessKey(table) {
158
+ let best = null;
159
+ for (const h of table.head) {
160
+ const vals = table.data.map((r) => r[h]).filter((v) => v !== "");
161
+ if (!vals.length) continue;
162
+ const uniq = new Set(vals).size / vals.length;
163
+ const fill = vals.length / table.data.length;
164
+ if (uniq < 0.95 || fill < 0.95) continue;
165
+ const score = keyScore(h);
166
+ if (!best || score > best.score || (score === best.score && uniq > best.uniq)) {
167
+ best = { col: h, uniq, fill, score };
168
+ }
169
+ }
170
+ return best;
171
+ }
172
+
173
+ function toNum(s) {
174
+ const t = clean(s).replace(/[,,¥¥$\s]/g, "").replace(/%$/, "");
175
+ if (t === "" || !/^-?\d+(\.\d+)?$/.test(t)) return null;
176
+ return Number(t);
177
+ }
178
+
179
+ function isNumericCol(table, h) {
180
+ const vals = table.data.map((r) => r[h]).filter((v) => v !== "");
181
+ if (!vals.length) return false;
182
+ const ok = vals.filter((v) => toNum(v) !== null).length;
183
+ return ok / vals.length >= 0.9;
184
+ }
185
+
186
+ /* ---------------- 对账 ---------------- */
187
+
188
+ function reconcile(basePath, targetPath, opts = {}) {
189
+ const A = loadTable(basePath);
190
+ const B = loadTable(targetPath);
191
+ const notes = [];
192
+
193
+ // 主键
194
+ // 右表主键优先「从左表主键映射过去」,而不是各自独立猜:
195
+ // 两张表是同一批记录的两份副本,主键概念必然相同,独立猜只会猜出两个不同的东西
196
+ // (第一版右表猜成了「客户」列,因为 6 行表里客户名也唯一)。
197
+ const keyA = opts.key || (guessKey(A) || {}).col;
198
+ if (!keyA) throw new Error(`左表猜不出主键,请用 key 参数指定(左表列名:${A.head.join(" / ")})`);
199
+ let keyB = opts.key ? mapColumn(opts.key, B.head).hit : null;
200
+ if (!keyB) {
201
+ const m = mapColumn(keyA, B.head, false);
202
+ if (m.hit) { keyB = m.hit; notes.push(`右表主键按「${m.how}」映射到「${keyB}」`); }
203
+ }
204
+ if (!keyB) {
205
+ const g = guessKey(B);
206
+ if (g) { keyB = g.col; notes.push(`右表主键没法从「${keyA}」映射过去,按唯一率猜为「${keyB}」`); }
207
+ }
208
+ if (!keyA || !keyB) {
209
+ throw new Error(
210
+ `右表找不到能对上「${keyA}」的列(右表列名:${B.head.join(" / ")})。` +
211
+ `请用 key 参数直接指定右表的主键列名。`
212
+ );
213
+ }
214
+
215
+ // 列映射:一对一分派,右表每一列只能被用一次
216
+ const pairs = mapAll(A.head.filter((h) => h !== keyA), B.head, keyB);
217
+
218
+ // 按主键建索引
219
+ const idxB = new Map();
220
+ for (const r of B.data) {
221
+ const k = clean(r[keyB]);
222
+ if (k === "") continue;
223
+ if (idxB.has(k)) notes.push(`右表主键「${k}」重复,只取第一行`);
224
+ else idxB.set(k, r);
225
+ }
226
+ const idxA = new Map();
227
+ for (const r of A.data) {
228
+ const k = clean(r[keyA]);
229
+ if (k === "") continue;
230
+ if (idxA.has(k)) notes.push(`左表主键「${k}」重复,只取第一行`);
231
+ else idxA.set(k, r);
232
+ }
233
+
234
+ const onlyA = [...idxA.keys()].filter((k) => !idxB.has(k));
235
+ const onlyB = [...idxB.keys()].filter((k) => !idxA.has(k));
236
+ const both = [...idxA.keys()].filter((k) => idxB.has(k));
237
+
238
+ // 逐列比对
239
+ const diffs = [];
240
+ const tolerance = opts.tolerance ?? 0.01;
241
+ for (const k of both) {
242
+ const ra = idxA.get(k), rb = idxB.get(k);
243
+ for (const p of pairs) {
244
+ const va = clean(ra[p.left]), vb = clean(rb[p.right]);
245
+ if (va === vb) continue;
246
+ const na = toNum(va), nb = toNum(vb);
247
+ if (na !== null && nb !== null) {
248
+ if (Math.abs(na - nb) <= tolerance) continue;
249
+ diffs.push({ key: k, col: p.left, a: va, b: vb, delta: (na - nb).toFixed(2), type: "数值" });
250
+ } else {
251
+ diffs.push({ key: k, col: p.left, a: va, b: vb, delta: "", type: "文本" });
252
+ }
253
+ }
254
+ }
255
+
256
+ return { A, B, keyA, keyB, pairs, onlyA, onlyB, both, diffs, notes, tolerance };
257
+ }
258
+
259
+ /* ---------------- 输出 ---------------- */
260
+
261
+ function fmtInspect(t) {
262
+ const lines = [];
263
+ lines.push(`文件:${t.file}|数据行 ${t.data.length}|列 ${t.head.length}`);
264
+ const k = guessKey(t);
265
+ if (k) lines.push(`推测主键:**${k.col}**(唯一率 ${(k.uniq * 100).toFixed(1)}%,填充率 ${(k.fill * 100).toFixed(1)}%)`);
266
+ else lines.push("推测主键:**无**(没有一列能唯一标识行,对账时请手动指定 key)");
267
+ lines.push("");
268
+ lines.push("| 列名 | 非空 | 数值列 | 样本 |");
269
+ lines.push("|---|---|---|---|");
270
+ for (const h of t.head) {
271
+ const vals = t.data.map((r) => r[h]).filter((v) => v !== "");
272
+ const sample = vals.slice(0, 2).join(" / ").slice(0, 40) || "—";
273
+ lines.push(`| ${h} | ${vals.length}/${t.data.length} | ${isNumericCol(t, h) ? "是" : ""} | ${sample} |`);
274
+ }
275
+ return lines.join("\n");
276
+ }
277
+
278
+ function fmtReconcile(r) {
279
+ const L = [];
280
+ L.push(`## 对账结果`);
281
+ L.push("");
282
+ L.push(`左表 ${r.A.file}(${r.A.data.length} 行)· 右表 ${r.B.file}(${r.B.data.length} 行)`);
283
+ L.push(`主键:左「${r.keyA}」↔ 右「${r.keyB}」`);
284
+ L.push("");
285
+ L.push("| 项 | 数量 |");
286
+ L.push("|---|---|");
287
+ L.push(`| 两边都有 | ${r.both.length} |`);
288
+ L.push(`| 只在左表 | ${r.onlyA.length} |`);
289
+ L.push(`| 只在右表 | ${r.onlyB.length} |`);
290
+ L.push(`| 匹配上但对不上 | ${r.diffs.length} 处 |`);
291
+ L.push("");
292
+
293
+ if (r.pairs.length) {
294
+ L.push("列对应关系(左 ← 右):");
295
+ for (const p of r.pairs) L.push(`- ${p.left} ← ${p.right}(${p.how})`);
296
+ const unmatched = r.A.head.filter((h) => h !== r.keyA && !r.pairs.some((p) => p.left === h));
297
+ if (unmatched.length) L.push(`- 左表这些列在右表找不到对应,未参与比对:${unmatched.join("、")}`);
298
+ L.push("");
299
+ }
300
+
301
+ const cap = (arr) => (arr.length > MAX_ROWS_OUT ? arr.slice(0, MAX_ROWS_OUT) : arr);
302
+ const more = (arr) => (arr.length > MAX_ROWS_OUT ? `\n……另有 ${arr.length - MAX_ROWS_OUT} 条未列出` : "");
303
+
304
+ if (r.onlyA.length) {
305
+ L.push(`**只在左表(右表缺)${r.onlyA.length} 条:**`);
306
+ L.push(cap(r.onlyA).map((k) => `- ${k}`).join("\n") + more(r.onlyA));
307
+ L.push("");
308
+ }
309
+ if (r.onlyB.length) {
310
+ L.push(`**只在右表(左表缺)${r.onlyB.length} 条:**`);
311
+ L.push(cap(r.onlyB).map((k) => `- ${k}`).join("\n") + more(r.onlyB));
312
+ L.push("");
313
+ }
314
+ if (r.diffs.length) {
315
+ L.push(`**两边都有但对不上 ${r.diffs.length} 处:**`);
316
+ L.push("");
317
+ L.push("| 主键 | 列 | 左表 | 右表 | 差额 |");
318
+ L.push("|---|---|---|---|---|");
319
+ for (const d of cap(r.diffs)) L.push(`| ${d.key} | ${d.col} | ${d.a} | ${d.b} | ${d.delta || "—"} |`);
320
+ if (r.diffs.length > MAX_ROWS_OUT) L.push(`\n……另有 ${r.diffs.length - MAX_ROWS_OUT} 处未列出`);
321
+ L.push("");
322
+ }
323
+
324
+ const total = r.onlyA.length + r.onlyB.length + r.diffs.length;
325
+ L.push("---");
326
+ L.push(
327
+ total === 0
328
+ ? `**结论:对得上**——${r.both.length} 条主键全部一致,容差 ${r.tolerance} 内无差额。`
329
+ : `**结论:对不上**——${total} 处需要核(缺 ${r.onlyA.length + r.onlyB.length} 条、差异 ${r.diffs.length} 处)。`
330
+ );
331
+ if (r.notes.length) {
332
+ L.push("");
333
+ L.push("说明:");
334
+ for (const n of r.notes) L.push(`- ${n}`);
335
+ }
336
+ L.push("");
337
+ L.push("> 只读你的原表,没有改动任何文件。");
338
+ return L.join("\n");
339
+ }
340
+
341
+ /* ---------------- MCP 服务 ---------------- */
342
+
343
+ const TOOLS = [
344
+ {
345
+ name: "inspect_table",
346
+ description:
347
+ "看一张 CSV 的列名、行数、每列样本,并推测可用作主键的列。对账前先用它确认两表结构。",
348
+ inputSchema: {
349
+ type: "object",
350
+ properties: { path: { type: "string", description: "CSV 文件的绝对路径" } },
351
+ required: ["path"],
352
+ },
353
+ },
354
+ {
355
+ name: "reconcile",
356
+ description:
357
+ "把两张 CSV 按主键对账:报告只在左表、只在右表、以及两边都有但对不上的行与金额差额。只读文件,不改原表。",
358
+ inputSchema: {
359
+ type: "object",
360
+ properties: {
361
+ base_path: { type: "string", description: "左表(基准表)CSV 绝对路径" },
362
+ target_path: { type: "string", description: "右表(待核对表)CSV 绝对路径" },
363
+ key: { type: "string", description: "主键列名;不填则自动推测。两表列名不同时填左表的列名即可" },
364
+ tolerance: { type: "number", description: "数值差额容差,默认 0.01" },
365
+ },
366
+ required: ["base_path", "target_path"],
367
+ },
368
+ },
369
+ ];
370
+
371
+ function callTool(name, args = {}) {
372
+ try {
373
+ if (name === "inspect_table") {
374
+ const t = loadTable(args.path);
375
+ return { content: [{ type: "text", text: fmtInspect(t) }] };
376
+ }
377
+ if (name === "reconcile") {
378
+ const r = reconcile(args.base_path, args.target_path, {
379
+ key: args.key,
380
+ tolerance: typeof args.tolerance === "number" ? args.tolerance : undefined,
381
+ });
382
+ return { content: [{ type: "text", text: fmtReconcile(r) }] };
383
+ }
384
+ return { content: [{ type: "text", text: `未知工具:${name}` }], isError: true };
385
+ } catch (e) {
386
+ return { content: [{ type: "text", text: `出错:${e.message}` }], isError: true };
387
+ }
388
+ }
389
+
390
+ /* ---------- stdio JSON-RPC 传输层(零依赖) ---------- */
391
+ function reply(id, result) {
392
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + "\n");
393
+ }
394
+ function replyError(id, code, message) {
395
+ process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }) + "\n");
396
+ }
397
+
398
+ function handle(msg) {
399
+ const { id, method, params } = msg;
400
+ const isNotification = id === undefined || id === null;
401
+
402
+ switch (method) {
403
+ case "initialize":
404
+ reply(id, {
405
+ protocolVersion: (params && params.protocolVersion) || PROTOCOL,
406
+ capabilities: { tools: {} },
407
+ serverInfo: { name: NAME, version: VERSION },
408
+ });
409
+ return;
410
+ case "notifications/initialized":
411
+ case "notifications/cancelled":
412
+ return;
413
+ case "ping":
414
+ if (!isNotification) reply(id, {});
415
+ return;
416
+ case "tools/list":
417
+ reply(id, { tools: TOOLS });
418
+ return;
419
+ case "tools/call": {
420
+ const { name, arguments: args } = params || {};
421
+ reply(id, callTool(name, args || {}));
422
+ return;
423
+ }
424
+ default:
425
+ if (!isNotification) replyError(id, -32601, `Method not found: ${method}`);
426
+ }
427
+ }
428
+
429
+ const rl = readline.createInterface({ input: process.stdin });
430
+ rl.on("line", (line) => {
431
+ const s = line.trim();
432
+ if (!s) return;
433
+ let msg;
434
+ try {
435
+ msg = JSON.parse(s);
436
+ } catch {
437
+ replyError(null, -32700, "Parse error");
438
+ return;
439
+ }
440
+ try {
441
+ handle(msg);
442
+ } catch (e) {
443
+ if (msg.id !== undefined) replyError(msg.id, -32603, `Internal error: ${e.message}`);
444
+ }
445
+ });
446
+ rl.on("close", () => process.exit(0));
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
- {
2
- "name": "table-reconcile-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
1
+ {
2
+ "name": "table-reconcile-mcp",
3
+ "version": "1.0.0",
4
+ "description": "MCP server that reconciles two CSV tables: maps column names, matches rows by key, and reports every difference.",
5
+ "type": "module",
6
+ "bin": {
7
+ "table-reconcile-mcp": "index.js"
8
+ },
9
+ "main": "index.js",
10
+ "files": [
11
+ "index.js",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18.0.0"
16
+ },
17
+ "keywords": [
18
+ "mcp",
19
+ "csv",
20
+ "reconcile",
21
+ "对账",
22
+ "table"
23
+ ],
24
+ "license": "MIT",
25
+ "dependencies": {}
6
26
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.