@chaoyue-erp/ysy-openapi-mcp 1.0.1 → 1.0.4

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,220 @@
1
+ import fs from "node:fs";
2
+ import fsp from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import readline from "node:readline";
6
+ import { createHash } from "node:crypto";
7
+ import ExcelJS from "exceljs";
8
+
9
+ const PAGE_SIZE = 500;
10
+ const MAX_SHEET_ROWS = 1048575;
11
+ const MAX_COLUMNS = 16384;
12
+ const NOT_SNAPSHOT = "导出期间数据可能发生变化;分页查询不是数据库快照,无法保证完全一致。";
13
+
14
+ function extract(raw, resultPath) {
15
+ if (raw?.meta?.success !== true) throw new Error("接口返回失败,无法导出完整数据。");
16
+ const d = raw.data;
17
+ let page;
18
+ if (/data\.pageInfo\.list/.test(resultPath)) page = d?.pageInfo;
19
+ else if (/data\.page\.list/.test(resultPath)) page = d?.page;
20
+ else if (/data\.list/.test(resultPath)) page = d;
21
+ else throw new Error("此接口不是支持验证的分页列表,暂不支持导出。");
22
+ if (!page || !Array.isArray(page.list)) throw new Error("接口未返回可用的分页列表,无法验证完整性。");
23
+ return { page, rows: page.list };
24
+ }
25
+
26
+ function integer(value, label) {
27
+ if (value === null || value === undefined || value === "" || !Number.isSafeInteger(Number(value)) || Number(value) < 0) {
28
+ throw new Error(`接口分页信息缺少有效的 ${label},无法确认导出完整性。`);
29
+ }
30
+ return Number(value);
31
+ }
32
+
33
+ function inspectPage(raw, resultPath) {
34
+ const { page, rows } = extract(raw, resultPath);
35
+ const pageNum = integer(page.pageNum, "pageNum");
36
+ const pageSize = integer(page.pageSize, "pageSize");
37
+ const total = integer(page.total, "total");
38
+ const pages = integer(page.pages, "pages");
39
+ const expectedPages = Math.ceil(total / PAGE_SIZE);
40
+ if (pageNum < 1 || pageSize !== PAGE_SIZE || (pages !== expectedPages && !(total === 0 && pages === 1))) {
41
+ throw new Error("接口分页信息不一致,无法确认导出完整性。");
42
+ }
43
+ return { rows, pageNum, pageSize, total, pages };
44
+ }
45
+
46
+ function asCell(value) {
47
+ if (value === null || value === undefined) return null;
48
+ if (typeof value === "number") {
49
+ if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {
50
+ throw new Error("数据包含无法安全表示的数字,已终止导出。");
51
+ }
52
+ if ((Number.isInteger(value) && Math.abs(value) >= 1e15) || Number(value.toPrecision(15)) !== value) return String(value);
53
+ return value;
54
+ }
55
+ if (typeof value === "boolean") return value;
56
+ if (typeof value === "object") assertSafeNumbers(value);
57
+ const text = typeof value === "string" ? value : JSON.stringify(value);
58
+ if (typeof text !== "string" || text.length > 32767 || /[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/u.test(text)) {
59
+ throw new Error("数据含 Excel 无法完整保存的文本,已终止导出。");
60
+ }
61
+ return text;
62
+ }
63
+
64
+ function assertSafeNumbers(value) {
65
+ if (typeof value === "number") {
66
+ if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {
67
+ throw new Error("数据包含无法安全表示的数字,已终止导出。");
68
+ }
69
+ } else if (value && typeof value === "object") {
70
+ for (const nested of Object.values(value)) assertSafeNumbers(nested);
71
+ }
72
+ }
73
+
74
+ /** Fetch all pages privately, verify counts and write a local Excel file. */
75
+ export async function exportExcel({ api, definition, moduleCode, apiCode, params = {}, firstPage, expectedTotal }) {
76
+ const resultPath = definition?.resultPath || "";
77
+ if (!/data\.(?:pageInfo\.list|page\.list|list)/.test(resultPath)) {
78
+ throw new Error("此接口不是支持验证的分页列表,暂不支持导出。");
79
+ }
80
+ // This API documents that filtered totals can be inaccurate, including valid short pages.
81
+ if (apiCode === "finance.sale.receipt.list" && ["fa_accounting_voucher.amount1", "fa_accounting_voucher.amount2"].some((key) => params.searches?.[key] !== undefined && params.searches?.[key] !== null && params.searches?.[key] !== "")) {
82
+ throw new Error("该接口的分页总数可能不准确,暂不支持完整导出,请调整查询范围并逐页核对。");
83
+ }
84
+ let first;
85
+ if (firstPage) {
86
+ try { first = inspectPage(firstPage, resultPath); } catch { first = null; }
87
+ if (first?.pageNum !== 1) first = null;
88
+ }
89
+ const fixedParams = { ...params, pageNum: 1, pageSize: PAGE_SIZE };
90
+ if (!first) first = inspectPage(await api.queryRaw({ moduleCode, apiCode, params: fixedParams }), resultPath);
91
+ if (first.pageNum !== 1) throw new Error("接口未返回请求的第一页,已终止导出。");
92
+ if (expectedTotal !== undefined && first.total !== expectedTotal) throw new Error("查询总数在导出开始前发生变化,已终止导出,请重新查询。");
93
+
94
+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "ysy-export-"));
95
+ const spoolPath = path.join(dir, "rows.ndjson");
96
+ const filePath = path.join(dir, "export.xlsx");
97
+ let stream;
98
+ try {
99
+ await fsp.chmod(dir, 0o700);
100
+ await fsp.writeFile(spoolPath, "", { mode: 0o600 });
101
+ const keys = new Set();
102
+ const fingerprints = new Set();
103
+ let rowCount = 0;
104
+ const totalPages = first.pages;
105
+ for (let p = 1; p <= Math.max(1, totalPages); p++) {
106
+ const current = p === 1 ? first : inspectPage(await api.queryRaw({ moduleCode, apiCode, params: { ...fixedParams, pageNum: p } }), resultPath);
107
+ if (current.pageNum !== p || current.total !== first.total || current.pages !== totalPages) {
108
+ throw new Error("分页序号或总数发生变化,已终止导出,请重新查询。");
109
+ }
110
+ const expected = totalPages === 0 ? 0 : Math.min(PAGE_SIZE, first.total - (p - 1) * PAGE_SIZE);
111
+ if (current.rows.length !== expected) throw new Error("实际分页数量与总数不一致,无法确认导出完整性。");
112
+ if (current.rows.length) {
113
+ const fingerprint = createHash("sha256").update(JSON.stringify(current.rows)).digest("hex");
114
+ if (fingerprints.has(fingerprint)) throw new Error("后端返回重复分页,已终止导出。");
115
+ fingerprints.add(fingerprint);
116
+ }
117
+ for (const row of current.rows) {
118
+ if (!row || typeof row !== "object" || Array.isArray(row)) throw new Error("接口返回的记录不是对象,无法导出。");
119
+ for (const key of Object.keys(row)) {
120
+ asCell(key);
121
+ keys.add(key);
122
+ if (keys.size > MAX_COLUMNS) throw new Error("字段超过 Excel 列数限制,无法完整导出。");
123
+ asCell(row[key]);
124
+ }
125
+ }
126
+ if (current.rows.length) await fsp.appendFile(spoolPath, current.rows.map((row) => JSON.stringify(row)).join("\n") + "\n");
127
+ rowCount += current.rows.length;
128
+ }
129
+ if (rowCount !== first.total) throw new Error("导出数量与总数不一致,无法确认完整性。");
130
+ const columns = [...keys];
131
+ stream = fs.createWriteStream(filePath, { flags: "wx", mode: 0o600 });
132
+ const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream, useStyles: false, useSharedStrings: false });
133
+ let sheet;
134
+ let inSheet = 0;
135
+ let sheetNum = 0;
136
+ const newSheet = () => {
137
+ if (sheet) sheet.commit();
138
+ sheet = workbook.addWorksheet(`数据${++sheetNum}`);
139
+ sheet.addRow(columns).commit();
140
+ inSheet = 0;
141
+ };
142
+ newSheet();
143
+ const lines = readline.createInterface({ input: fs.createReadStream(spoolPath), crlfDelay: Infinity });
144
+ for await (const line of lines) {
145
+ if (!line) continue;
146
+ if (inSheet >= MAX_SHEET_ROWS) newSheet();
147
+ const row = JSON.parse(line);
148
+ sheet.addRow(columns.map((key) => asCell(row[key]))).commit();
149
+ inSheet++;
150
+ }
151
+ sheet.commit();
152
+ await workbook.commit();
153
+ await fsp.unlink(spoolPath);
154
+ return { filePath, rowCount, total: first.total, pages: totalPages, pageSize: PAGE_SIZE, warnings: [NOT_SNAPSHOT] };
155
+ } catch (error) {
156
+ if (stream) stream.destroy();
157
+ await fsp.rm(dir, { recursive: true, force: true });
158
+ throw error;
159
+ }
160
+ }
161
+
162
+ /** Export an already complete, non-paginated JSON array without inventing pagination. */
163
+ export async function exportArrayExcel({ apiCode, rows }) {
164
+ if (!Array.isArray(rows)) throw new Error("接口返回的完整数据不是数组,无法导出。");
165
+ const keys = new Set();
166
+ for (const row of rows) {
167
+ assertSafeNumbers(row);
168
+ if (row && typeof row === "object" && !Array.isArray(row)) {
169
+ for (const key of Object.keys(row)) {
170
+ asCell(key);
171
+ keys.add(key);
172
+ if (keys.size >= MAX_COLUMNS) throw new Error("字段超过 Excel 列数限制,无法完整导出。");
173
+ asCell(row[key]);
174
+ }
175
+ }
176
+ // Complete JSON stays alongside columns, including null and primitive rows.
177
+ // Reject values not faithfully representable in JSON rather than lose them.
178
+ const serialized = JSON.stringify(row);
179
+ if (serialized === undefined || (typeof row === "number" && !Number.isFinite(row))) {
180
+ throw new Error("数据包含无法保存为 JSON 的值,已终止导出。");
181
+ }
182
+ asCell(serialized);
183
+ }
184
+ let rawHeader = "原始数据(JSON)";
185
+ while (keys.has(rawHeader)) rawHeader += "_";
186
+ const columns = [...keys];
187
+ const dir = await fsp.mkdtemp(path.join(os.tmpdir(), "ysy-export-"));
188
+ const filePath = path.join(dir, "export.xlsx");
189
+ let stream;
190
+ try {
191
+ await fsp.chmod(dir, 0o700);
192
+ stream = fs.createWriteStream(filePath, { flags: "wx", mode: 0o600 });
193
+ const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream, useStyles: false, useSharedStrings: false });
194
+ let sheet, inSheet = 0, sheetNum = 0;
195
+ const newSheet = () => {
196
+ if (sheet) sheet.commit();
197
+ sheet = workbook.addWorksheet(`数据${++sheetNum}`);
198
+ sheet.addRow([...columns, rawHeader]).commit();
199
+ inSheet = 0;
200
+ };
201
+ newSheet();
202
+ for (const row of rows) {
203
+ if (inSheet >= MAX_SHEET_ROWS) newSheet();
204
+ const object = row && typeof row === "object" && !Array.isArray(row) ? row : null;
205
+ const cells = columns.map(key => {
206
+ const value = object && Object.prototype.hasOwnProperty.call(object, key) ? object[key] : null;
207
+ return asCell(value);
208
+ });
209
+ sheet.addRow([...cells, JSON.stringify(row)]).commit();
210
+ inSheet++;
211
+ }
212
+ sheet.commit();
213
+ await workbook.commit();
214
+ return { filePath, apiCode, rowCount: rows.length, total: rows.length, warnings: [] };
215
+ } catch (error) {
216
+ if (stream) stream.destroy();
217
+ await fsp.rm(dir, { recursive: true, force: true });
218
+ throw error;
219
+ }
220
+ }
package/src/server.mjs CHANGED
@@ -10,6 +10,7 @@ import { z } from "zod";
10
10
  import { DATA_MAP, loadConfig, configuredModules, missingModules } from "./config.mjs";
11
11
  import { TokenManager } from "./token-manager.mjs";
12
12
  import { ApiClient } from "./api-client.mjs";
13
+ import { exportExcel, exportArrayExcel } from "./export-excel.mjs";
13
14
 
14
15
  const cfg = loadConfig();
15
16
  const tokens = new TokenManager(cfg);
@@ -26,6 +27,44 @@ const wrap = async (fn) => {
26
27
  }
27
28
  };
28
29
 
30
+ // 分页按 Unicode 字符计数,避免切断汉字或 emoji;每页始终返回续读位置。
31
+ function pageDocument(value, offset = 0, limit = 3000) {
32
+ const format = typeof value === "string" ? "text" : "json";
33
+ const content = format === "text" ? value : JSON.stringify(value, null, 2);
34
+ const chars = Array.from(content ?? "");
35
+ const start = Math.min(offset, chars.length);
36
+ const next = Math.min(start + limit, chars.length);
37
+ return {
38
+ format,
39
+ text: chars.slice(start, next).join(""),
40
+ offset: start,
41
+ returnedChars: next - start,
42
+ totalChars: chars.length,
43
+ hasMore: next < chars.length,
44
+ nextOffset: next < chars.length ? next : null,
45
+ hint: format === "json" && chars.length > limit ? "JSON 按字符分页;需要完整 JSON 时请按 nextOffset 拼接所有 text。" : undefined,
46
+ };
47
+ }
48
+
49
+ const DOC_PAGE_SCHEMA = {
50
+ offset: z.number().int().min(0).optional().describe("字符偏移,从 0 开始;续读时传上次返回的 nextOffset"),
51
+ limit: z.number().int().min(1).max(4000).optional().describe("每页最多 4000 个 Unicode 字符,默认 3000"),
52
+ };
53
+
54
+ // 保留旧字段,限制摘要大小;被省略的内容可通过 read_api_document 完整续读。
55
+ function briefArray(value, maxItems = 40, maxChars = 5000) {
56
+ const all = Array.isArray(value) ? value : [];
57
+ const items = [];
58
+ let used = 0;
59
+ for (const item of all) {
60
+ const size = JSON.stringify(item).length;
61
+ if (items.length >= maxItems || used + size > maxChars) break;
62
+ items.push(item);
63
+ used += size;
64
+ }
65
+ return { items, total: all.length, returned: items.length, hasMore: items.length < all.length };
66
+ }
67
+
29
68
  function resolveApi(args) {
30
69
  const code = args.apiCode || args.actionCode;
31
70
  if (!code) throw new Error("请提供 apiCode(文档中的字段名为 apiCode,不是 actionCode;actionCode 仅作为兼容别名)。");
@@ -37,13 +76,27 @@ function resolveApi(args) {
37
76
  return found;
38
77
  }
39
78
 
79
+ function pageMetadata(definition, data) {
80
+ const resultPath = definition.resultPath || "";
81
+ if (/data\.pageInfo\.list/.test(resultPath)) return data?.pageInfo;
82
+ if (/data\.page\.list/.test(resultPath)) return data?.page;
83
+ if (/data\.list/.test(resultPath)) return data;
84
+ return null;
85
+ }
86
+
87
+ function isPageable(definition) {
88
+ const names = (definition.params || []).map((p) => p.name || "").join(" ");
89
+ return !definition.apiCode.includes(".detail.") && /\bpageNum\b/i.test(names) && /\bpageSize\b/i.test(names) && /data\.(?:pageInfo\.list|page\.list|list)/.test(definition.resultPath || "");
90
+ }
91
+
40
92
  function createServer() {
41
- const server = new McpServer({ name: "ysy-openapi", version: "1.0.0" });
93
+ const { version } = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
94
+ const server = new McpServer({ name: "ysy-openapi", version });
42
95
 
43
96
  server.registerTool(
44
97
  "list_modules",
45
98
  {
46
- description: "列出悦商云开放接口的业务模块。一个客户端只对应一个模块,取 Token 前需确认该模块已配置密钥。返回模块名、接口数和密钥配置状态。",
99
+ description: "列出开放接口的业务模块与密钥配置状态。配置状态不代表模块或接口已获授权,实际权限由服务端校验。",
47
100
  inputSchema: {},
48
101
  },
49
102
  () =>
@@ -59,7 +112,7 @@ function createServer() {
59
112
  credentialsConfigured: ready.has(code),
60
113
  })),
61
114
  notConfigured: missingModules(cfg),
62
- hint: "一个客户端对应一个模块,多模块需分别领取密钥并分别取 Token。",
115
+ hint: "密钥已配置只表示客户端已填写凭据;各模块及接口能否调用,以服务端授权为准。",
63
116
  };
64
117
  }),
65
118
  );
@@ -81,7 +134,7 @@ function createServer() {
81
134
  if (args.kind) list = list.filter((a) => a.kind === args.kind);
82
135
  if (args.keyword) {
83
136
  const k = args.keyword.toLowerCase();
84
- list = list.filter((a) => a.apiCode.toLowerCase().includes(k) || a.name.toLowerCase().includes(k) || (a.summary || "").toLowerCase().includes(k));
137
+ list = list.filter((a) => a.apiCode.toLowerCase().includes(k) || a.name.toLowerCase().includes(k) || (a.summary || "").toLowerCase().includes(k) || (a.searchText || "").toLowerCase().includes(k));
85
138
  }
86
139
  return {
87
140
  total: list.length,
@@ -94,9 +147,9 @@ function createServer() {
94
147
  server.registerTool(
95
148
  "describe_api",
96
149
  {
97
- description: "查看某个 apiCode 的完整参数说明:params 参数表、报表 searches 可用 key、请求示例、返回字段与数据路径。填写 query 的 params 前必须先调用此工具。",
150
+ description: "查看接口摘要与参数。完整请求、响应、公共说明、附表和所有示例请用 read_api_document 分节分页读取。",
98
151
  inputSchema: {
99
- apiCode: z.string().describe("完整接口 code,区分大小写,如 sale.list"),
152
+ apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list"),
100
153
  actionCode: z.string().optional().describe("apiCode 的兼容别名,二选一"),
101
154
  },
102
155
  },
@@ -104,6 +157,9 @@ function createServer() {
104
157
  wrap(() => {
105
158
  const a = resolveApi(args);
106
159
  const rules = DATA_MAP.commonRules;
160
+ const fieldNames = ["params", "formFields", "executeFields", "searchKeys", "responseFields"];
161
+ const brief = Object.fromEntries(fieldNames.map((name) => [name, briefArray(a[name])]));
162
+ const exampleOmitted = JSON.stringify(a.requestExample ?? null).length > 5000;
107
163
  const out = {
108
164
  apiCode: a.apiCode,
109
165
  name: a.name,
@@ -112,12 +168,12 @@ function createServer() {
112
168
  entry: a.entry,
113
169
  resultPath: a.resultPath,
114
170
  summary: a.summary,
115
- params: a.params,
116
- formFields: a.formFields,
117
- executeFields: a.executeFields,
118
- searchKeys: a.searchKeys,
119
- requestExample: a.requestExample,
120
- responseFields: a.responseFields.slice(0, 40),
171
+ params: brief.params.items,
172
+ formFields: brief.formFields.items,
173
+ executeFields: brief.executeFields.items,
174
+ searchKeys: brief.searchKeys.items,
175
+ requestExample: exampleOmitted ? null : a.requestExample,
176
+ responseFields: brief.responseFields.items,
121
177
  responseNotes: a.responseNotes,
122
178
  rules: {
123
179
  success: rules.success,
@@ -127,6 +183,11 @@ function createServer() {
127
183
  detailId: rules.detailId,
128
184
  sort: rules.sort,
129
185
  },
186
+ documentAccess: {
187
+ fields: Object.fromEntries(fieldNames.map((name) => [name, { total: brief[name].total, returned: brief[name].returned, hasMore: brief[name].hasMore }])),
188
+ requestExampleOmitted: exampleOmitted,
189
+ hint: "摘要和部分字段可能省略;调用 read_api_document 按 section 与 nextOffset 查看完整内容。",
190
+ },
130
191
  };
131
192
  if (a.kind !== "query") {
132
193
  out.warning = `此 code 属于 ${a.entry} 入口(写入类),不能用 query 工具调用;且写入工具默认禁用。`;
@@ -137,17 +198,63 @@ function createServer() {
137
198
  }),
138
199
  );
139
200
 
201
+ server.registerTool(
202
+ "read_api_document",
203
+ {
204
+ description: "按章节和字符偏移完整读取指定接口文档。大章节按 nextOffset 续读;所有示例、附表、请求、响应和公共说明均可读取。",
205
+ inputSchema: {
206
+ apiCode: z.string().describe("完整接口 code,例如 sale.list"),
207
+ section: z.enum(["requestText", "responseText", "commonText", "searchText", "params", "searchKeys", "formFields", "executeFields", "responseFields", "extraTables", "sourceTables", "requestExamples", "responseExamples", "commonExamples"]).describe("接口文档章节名称"),
208
+ ...DOC_PAGE_SCHEMA,
209
+ },
210
+ },
211
+ (args) => wrap(() => {
212
+ const a = resolveApi(args);
213
+ const value = a[args.section];
214
+ if (value === undefined) throw new Error(`该接口尚未包含 ${args.section} 章节,请先用新版生成脚本更新数据地图。`);
215
+ return { apiCode: a.apiCode, section: args.section, ...pageDocument(value, args.offset, args.limit) };
216
+ }),
217
+ );
218
+
219
+ server.registerTool(
220
+ "read_reference_document",
221
+ {
222
+ description: "列出或按章节分页读取公共指南与公共规则。category=guides 时不传 guideId 列出指南;传 guideId 和 section 读取内容;category=rules 按 rule 读取公共规则。",
223
+ inputSchema: {
224
+ category: z.enum(["guides", "rules"]).describe("guides=文档公共指南;rules=连接器公共规则"),
225
+ guideId: z.string().optional().describe("指南 id,先不传以查看目录"),
226
+ section: z.enum(["text", "tables", "examples"]).optional().describe("指南章节;默认 text"),
227
+ rule: z.string().optional().describe("公共规则键;不传时列出可用键"),
228
+ ...DOC_PAGE_SCHEMA,
229
+ },
230
+ },
231
+ (args) => wrap(() => {
232
+ if (args.category === "rules") {
233
+ const rules = DATA_MAP.commonRules || {};
234
+ if (!args.rule) return { category: "rules", keys: Object.keys(rules) };
235
+ if (!Object.hasOwn(rules, args.rule)) throw new Error(`未找到公共规则 ${args.rule}`);
236
+ return { category: "rules", rule: args.rule, ...pageDocument(rules[args.rule], args.offset, args.limit) };
237
+ }
238
+ const guides = DATA_MAP.guides || [];
239
+ if (!args.guideId) return { category: "guides", total: guides.length, ...pageDocument(guides.map(({ id, title }) => ({ id, title })), args.offset, args.limit) };
240
+ const guide = guides.find((g) => g.id === args.guideId);
241
+ if (!guide) throw new Error(`未找到公共指南 ${args.guideId}`);
242
+ const section = args.section || "text";
243
+ return { category: "guides", guideId: guide.id, title: guide.title, section, ...pageDocument(guide[section] ?? (section === "text" ? "" : []), args.offset, args.limit) };
244
+ }),
245
+ );
246
+
140
247
  server.registerTool(
141
248
  "query",
142
249
  {
143
- description: "调用悦商云策略网关查询数据(POST /openapi/v1/query)。请求外壳为 {moduleCode, apiCode, params}。自动取 Token、缓存并在 401 时刷新;自动把 YYYY-MM-DD 日期转为毫秒时间戳;自动按数据地图校验 code 并截断超大结果。",
250
+ description: "查询经营数据。分页接口先查询符合条件的总数,超过 500 条则自动分页生成本机 Excel;不超过 500 条完整返回请求页。非分页接口一次返回超过 500 行时生成 Excel。查询结果并非事务快照。",
144
251
  inputSchema: {
145
252
  apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list、goods.list"),
146
253
  actionCode: z.string().optional().describe("apiCode 的兼容别名,与 apiCode 二选一"),
147
254
  moduleCode: z.string().optional().describe("模块 code;省略时按数据地图自动推断"),
148
255
  params: z.record(z.any()).optional().describe("业务参数,放筛选/分页/排序;报表筛选放 params.searches"),
149
256
  pageNum: z.number().int().min(1).optional().describe("页码,从 1 开始;翻页时保持其他筛选条件不变"),
150
- pageSize: z.number().int().min(1).max(500).optional().describe("每页条数,1~500,默认 100"),
257
+ pageSize: z.number().int().min(1).max(500).optional().describe("每页条数,1~500;MCP 未指定时使用 500"),
151
258
  },
152
259
  },
153
260
  (args) =>
@@ -186,7 +293,50 @@ function createServer() {
186
293
  warnings.push("timeType 快捷日期与 dateStart/dateEnd 自定义区间应二选一,同时传入可能导致筛选不符合预期。");
187
294
  }
188
295
 
189
- const result = await api.query({ moduleCode, apiCode: a.apiCode, params, api: a });
296
+ const receiptAmountFilter = a.apiCode === "finance.sale.receipt.list" && ["fa_accounting_voucher.amount1", "fa_accounting_voucher.amount2"].some((key) => params.searches?.[key] !== undefined && params.searches?.[key] !== null && params.searches?.[key] !== "");
297
+ if (receiptAmountFilter && params.pageNum === undefined && params.pageSize === undefined) {
298
+ throw new Error("该接口使用金额筛选时分页总数可能不准确,无法确认全部结果完整;请明确指定页码或页大小后逐页核对。");
299
+ }
300
+ if (receiptAmountFilter) warnings.push("金额筛选时接口总数可能不准确;本次仅返回指定页,不能判断全部结果是否完整,请逐页核对。");
301
+ const useProbe = isPageable(a) && !receiptAmountFilter;
302
+ let raw;
303
+ let total;
304
+ if (useProbe) {
305
+ const probe = await api.queryRaw({ moduleCode, apiCode: a.apiCode, params: { ...params, pageNum: 1, pageSize: 1 } });
306
+ const probePage = pageMetadata(a, probe.data);
307
+ total = Number(probePage?.total);
308
+ if (probePage?.total == null || !Number.isSafeInteger(total) || total < 0 || Number(probePage.pageNum) !== 1 || Number(probePage.pageSize) !== 1) {
309
+ throw new Error("接口未返回有效的分页总数,无法确定是否需要导出,请缩小查询范围并核对接口分页信息。");
310
+ }
311
+ if (total > 500) {
312
+ if (a.apiCode === "finance.cash.flow.list") throw new Error("现金银行明细账末页可能含未计入总数的余额行,暂不支持自动完整导出,请缩小查询范围并核对。");
313
+ const exported = await exportExcel({ api, definition: a, moduleCode, apiCode: a.apiCode, params, expectedTotal: total });
314
+ return { ok: true, apiCode: a.apiCode, moduleCode, exported: true, ...exported, warnings: [...warnings, ...exported.warnings] };
315
+ }
316
+ const requestParams = { ...params, pageNum: params.pageNum ?? 1, pageSize: params.pageSize ?? 500 };
317
+ raw = await api.queryRaw({ moduleCode, apiCode: a.apiCode, params: requestParams });
318
+ const actual = pageMetadata(a, raw.data);
319
+ if (!actual || Number(actual.pageNum) !== Number(requestParams.pageNum) || Number(actual.pageSize) !== Number(requestParams.pageSize) || Number(actual.total) !== total) {
320
+ throw new Error("查询过程中分页信息或总数发生变化,无法确认结果完整,请重新查询。");
321
+ }
322
+ } else {
323
+ raw = await api.queryRaw({ moduleCode, apiCode: a.apiCode, params });
324
+ }
325
+ const result = api.shapeQuery({ api: a, raw, moduleCode, apiCode: a.apiCode });
326
+ if (useProbe) {
327
+ const actual = pageMetadata(a, raw.data);
328
+ const expected = Math.max(0, Math.min(Number(actual.pageSize), total - (Number(actual.pageNum) - 1) * Number(actual.pageSize)));
329
+ const hasExtraBalance = a.apiCode === "finance.cash.flow.list" && Number(actual.pageNum) === Math.max(1, Math.ceil(total / Number(actual.pageSize))) && Array.isArray(result.rows) && result.rows.length > expected;
330
+ if (!Array.isArray(result.rows) || (!hasExtraBalance && result.rows.length !== expected)) throw new Error("接口返回的行数与分页总数不一致,无法确认结果完整,请重新查询。");
331
+ if (hasExtraBalance) warnings.push("末页包含未计入业务总数的余额行,已完整返回。");
332
+ }
333
+ if (!isPageable(a) && Array.isArray(result.rows) && result.rows.length > 500) {
334
+ const page = pageMetadata(a, raw.data);
335
+ if (page && page.total != null) throw new Error("接口返回的行数与分页信息不一致,无法确认结果完整性。");
336
+ const exported = await exportArrayExcel({ apiCode: a.apiCode, rows: result.rows });
337
+ const { listDetail: ignoredListDetail, ...orderInfo } = raw.data && !Array.isArray(raw.data) && Array.isArray(raw.data.listDetail) ? raw.data : {};
338
+ return { ok: true, apiCode: a.apiCode, moduleCode, exported: true, ...exported, ...(ignoredListDetail ? { singleObject: orderInfo } : {}), warnings: [...warnings, ...exported.warnings, "文件包含本次接口实际返回的全部行;接口未提供可核验的分页总数,无法判断后端是否还有其他记录。"] };
339
+ }
190
340
  return { ...result, warnings: [...warnings, ...result.warnings] };
191
341
  }),
192
342
  );
@@ -194,7 +344,7 @@ function createServer() {
194
344
  server.registerTool(
195
345
  "check_connection",
196
346
  {
197
- description: "自检连接器配置:环境地址、各模块密钥是否齐全、能否成功获取 Token。不返回 Token 明文。排查 401/403 时先用此工具。",
347
+ description: "自检配置和 Token 获取情况,不返回 Token 明文。获取成功并不证明任一模块或接口已获授权;接口权限以实际调用和服务端授权为准。",
198
348
  inputSchema: {
199
349
  moduleCode: z.string().optional().describe("只检查某个模块;省略则检查全部已配置模块"),
200
350
  },
@@ -219,7 +369,7 @@ function createServer() {
219
369
  try {
220
370
  const before = Date.now();
221
371
  await tokens.get(m, { force: true });
222
- results.push({ moduleCode: m, ok: true, elapsedMs: Date.now() - before, message: "Token 获取成功" });
372
+ results.push({ moduleCode: m, ok: true, elapsedMs: Date.now() - before, message: "Token 获取成功;这不代表该模块或接口已获授权,请以实际接口调用和服务端授权为准。" });
223
373
  } catch (err) {
224
374
  results.push({ moduleCode: m, ok: false, message: err.message });
225
375
  }
@@ -231,6 +381,7 @@ function createServer() {
231
381
  queryUrl: cfg.queryUrl,
232
382
  allowWrites: cfg.allowWrites,
233
383
  results,
384
+ authorizationNote: "此检查仅验证能否获取 Token;成功不代表每个模块或接口都已获授权。",
234
385
  notConfigured: missingModules(cfg),
235
386
  };
236
387
  }),