@chaoyue-erp/ysy-openapi-mcp 1.0.3 → 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.
package/README.md CHANGED
@@ -47,13 +47,17 @@ Token 由 MCP Server 获取和使用,工具结果不会主动返回 Token;
47
47
  | `describe_api` | 读取指定接口的参数摘要、报表 `searchKeys`、请求示例与返回字段 |
48
48
  | `read_api_document` | 按 `apiCode`、`section` 分段读取指定接口的详细说明、字段及示例 |
49
49
  | `read_reference_document` | 按 `category`、`guideId`、`section` 或 `rule` 分段读取公共指南和规则 |
50
- | `query` | 执行查询,内置白名单校验、日期转时间戳、明细主单 ID 校验、结果截断 |
50
+ | `query` | 执行查询,校验接口及参数;超过 500 条时自动分页生成 Excel |
51
51
  | `check_connection` | 检查环境地址、各模块密钥并尝试取 Token |
52
52
 
53
53
  标准调用顺序:`list_apis` → `describe_api` → 按需读取接口或公共规则 → `query`。两个读取工具通过 `offset` 按 Unicode 字符分页,每次默认 3000、最多 4000 字符;保持其他参数不变,按返回的 `nextOffset` 继续读取至 `null`。JSON 内容按顺序拼接各段 `text` 后再解析。接口文档内容可能经过正式环境及敏感信息过滤,具体以服务端实际接口和授权为准。完整字段规则见 `skills/ysy-openapi/SKILL.md`。
54
54
 
55
55
  例如:`read_api_document` 的 `section` 可选 `requestText`、`responseText`、`params`、`responseFields`、`requestExamples` 等;`read_reference_document` 的 `category` 选择 `guides` 或 `rules`,未指定 `guideId` 或 `rule` 时先列出可用目录。
56
56
 
57
+ 支持分页的接口会先按相同筛选条件查询总数;超过 500 条时 `query` 会每次最多读取 500 条并在 MCP 所在机器生成 Excel 文件,返回本机绝对路径。总数不超过 500 条时按用户指定页码与页大小查询,未指定页大小时默认 500,并完整返回该页。非分页接口一次返回超过 500 行也会生成 Excel;未提供总数时无法确认后端是否还有其他记录。文件是否能由 WorkBuddy 提供下载取决于运行环境;分页是多次请求,并非数据库事务快照。若分页元数据或行数不一致,导出会报错。`finance.sale.receipt.list` 金额筛选的分页总数可能不准确,明确指定分页时仅返回该页并提示结果可能不完整;`finance.cash.flow.list` 末页可能有额外余额行,暂不支持超过 500 条时自动完整导出。
58
+
59
+ 当前接口文档未定义后端原生导出接口,因此由 MCP 调用 `query` 分页并在本机生成 Excel。后续如正式提供导出接口,须根据实际接口单独接入并优先使用原生导出。
60
+
57
61
  ## 安全说明:正式环境已启用 HTTPS
58
62
 
59
63
  正式环境使用 `https://` 访问认证与业务网关,凭证与业务数据在传输中受到 TLS 保护。实际连通性和证书有效性需由服务方持续检查。
@@ -1,8 +1,6 @@
1
1
  {
2
2
  "env": "prod",
3
3
  "allowWrites": false,
4
- "maxRows": 50,
5
- "maxChars": 20000,
6
4
  "timeoutMs": 28000,
7
5
  "credentials": { "clientId": "", "clientSecret": "" },
8
6
  "_note": "支持单组 clientId / clientSecret 或按模块分别配置。是否可调用具体模块和接口由服务端授权决定。Token 由程序自动获取与缓存,不要把 access_token 写在这里;仅支持正式环境。"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaoyue-erp/ysy-openapi-mcp",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "悦商云开放接口 MCP Server:把 OAuth2 + 策略网关(query/import/execute)封装为 WorkBuddy 连接器工具",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -37,6 +37,7 @@
37
37
  ],
38
38
  "dependencies": {
39
39
  "@modelcontextprotocol/sdk": "^1.0.0",
40
+ "exceljs": "^4.4.0",
40
41
  "zod": "^3.23.0"
41
42
  }
42
43
  }
@@ -15,7 +15,10 @@ author: 广东超悦科技
15
15
  2. `describe_api(apiCode)` — 读取该接口的参数摘要、报表 `searchKeys`、请求示例和返回字段。**填 params 之前必须调用**。
16
16
  3. 细节不足时,用 `read_api_document(apiCode, section, offset?, limit?)` 读取接口详细说明,用 `read_reference_document(category, guideId?, section?, rule?, offset?, limit?)` 查公共指南与规则。`offset` 从 0 开始按 Unicode 字符计数,每页默认 3000、最多 4000 字符;保持其他参数不变,按 `nextOffset` 续读至 `null`,JSON 内容按顺序拼接 `text` 后解析。接口原文可能经过正式环境和敏感信息过滤,缺失内容应以服务端实际文档为准。
17
17
  4. `query(apiCode, params?, pageNum?, pageSize?)` — 执行查询。
18
- 5. 结果超过 50 行会被截断,用 `pageNum` 递增翻页,翻页时保持其他筛选条件完全不变。
18
+ 5. 支持分页的接口会先按相同筛选条件查询总数;超过 500 条时自动每次获取 500 条并生成 Excel,返回本机文件路径与行数;如未实际上传附件,不要声称附件已上传。导出是多次请求而非数据库快照。
19
+ 6. 总数不超过 500 条时,按 `pageNum`、`pageSize` 查询并完整返回该页;`pageSize` 最大 500,未指定时为 500。非分页接口一次返回超过 500 行也会导出为 Excel,接口未提供总数时不能声称后端不存在更多记录。
20
+
21
+ 当前接口文档未定义后端原生导出接口,Excel 由 MCP 分页调用 `query` 后在本机生成。后续如正式提供导出接口,需单独接入并优先使用原生接口。
19
22
 
20
23
  排查连接问题时先调用 `check_connection()`,它会检查地址、各模块密钥并尝试取 Token。能取得 Token 仅表示认证成功,不代表具体模块或接口已经授权。获取 Token 时客户端凭据放 HTTP Basic 请求头,表单仅发送 `grant_type=client_credentials`。
21
24
 
@@ -38,7 +41,7 @@ author: 广东超悦科技
38
41
  - 自定义:`params.dateStart` / `dateEnd`(现金银行明细账用 `startDate` / `endDate`)。可直接传 `"2026-11-01"` 这类字符串,服务端会自动转成 Unix 毫秒时间戳(北京时间,结束日取当天 23:59:59.999);也可直接传毫秒时间戳。
39
42
  - 自定义区间时**省略 timeType**,两者不要同时传。
40
43
  - 排序用 `sortField` + `sortDirection`(`asc` / `desc`)成对填写,只能选该接口列出的字段别名,不能提交 SQL 片段。
41
- - 分页 `pageNum` 从 1 开始,`pageSize` 范围 1~500,默认 100(商城会员默认 20)。
44
+ - 分页 `pageNum` 从 1 开始,`pageSize` 范围 1~500;通过 MCP 调用且未指定页大小时使用 500。
42
45
 
43
46
  ### 单据明细
44
47
 
@@ -96,8 +96,8 @@ export class ApiClient {
96
96
  return new ApiError(`HTTP ${res.status}${msg ? `(${msg})` : ""}:${tips[res.status] || "请查看服务方错误说明。"}`);
97
97
  }
98
98
 
99
- /** 调用 /query,自动处理 401 重取 Token、503 有限重试。 */
100
- async query({ moduleCode, apiCode, params = {}, api }) {
99
+ /** 调用 /query,自动处理 401 重取 Token、503 有限重试,返回完整后端响应。 */
100
+ async queryRaw({ moduleCode, apiCode, params = {} }) {
101
101
  const payload = { moduleCode, apiCode, params: normalizeDates(params) };
102
102
  for (let attempt = 0; attempt < 2; attempt++) {
103
103
  const res = await this.#post(this.cfg.queryUrl, payload, moduleCode, { forceToken: attempt > 0 });
@@ -116,22 +116,26 @@ export class ApiClient {
116
116
  if (meta.success !== true) {
117
117
  throw new ApiError(`业务返回失败:${meta.message || "未知原因"}。不要按成功结构解析 data;检查参数、权限和主单 ID。`);
118
118
  }
119
- return this.#shape(api, raw, payload);
119
+ return raw;
120
120
  }
121
121
  throw new ApiError("查询重试后仍失败,请稍后再试或联系服务方。");
122
122
  }
123
123
 
124
+ /** 普通查询对后端响应进行整形,完整返回本页数据。 */
125
+ async query({ moduleCode, apiCode, params = {}, api }) {
126
+ const raw = await this.queryRaw({ moduleCode, apiCode, params });
127
+ return this.shapeQuery({ api, raw, moduleCode, apiCode });
128
+ }
129
+
130
+ /** 对已查询到的响应整形,不重新发送请求。 */
131
+ shapeQuery({ api, raw, moduleCode, apiCode }) {
132
+ return this.#shape(api, raw, { moduleCode, apiCode });
133
+ }
134
+
124
135
  #shape(api, raw, payload) {
125
136
  const data = raw.data;
126
137
  const { rows, page, extra } = pickRows(api?.resultPath, data);
127
138
  const warnings = [];
128
- let outRows = rows;
129
- let truncated = false;
130
- if (Array.isArray(rows) && rows.length > this.cfg.maxRows) {
131
- outRows = rows.slice(0, this.cfg.maxRows);
132
- truncated = true;
133
- warnings.push(`本页共 ${rows.length} 行,仅返回前 ${this.cfg.maxRows} 行;请用 pageNum 翻页或调小 pageSize。`);
134
- }
135
139
  const result = {
136
140
  ok: true,
137
141
  apiCode: api?.apiCode ?? payload.apiCode,
@@ -140,8 +144,8 @@ export class ApiClient {
140
144
  meta: raw.meta,
141
145
  message: Array.isArray(rows) && rows.length === 0 ? "查询成功,但当前筛选条件下没有数据。可放宽日期范围或减少筛选条件后重试。" : null,
142
146
  rowCount: Array.isArray(rows) ? rows.length : 0,
143
- returnedRows: Array.isArray(outRows) ? outRows.length : 0,
144
- truncated,
147
+ returnedRows: Array.isArray(rows) ? rows.length : 0,
148
+ truncated: false,
145
149
  pagination: page
146
150
  ? {
147
151
  pageNum: page.pageNum,
@@ -151,17 +155,13 @@ export class ApiClient {
151
155
  hasNextPage: page.hasNextPage,
152
156
  }
153
157
  : null,
154
- rows: outRows,
158
+ rows,
155
159
  statistics: extra?.statistics ?? null,
156
160
  summary: extra?.total ?? null,
157
161
  lastAmount: extra?.lastAmount ?? null,
158
162
  singleObject: Array.isArray(data) || Array.isArray(data?.list) ? null : data,
159
163
  warnings,
160
164
  };
161
- const text = JSON.stringify(result, null, 2);
162
- if (text.length > this.cfg.maxChars) {
163
- return { ...result, rows: outRows?.slice?.(0, Math.max(1, Math.floor(this.cfg.maxRows / 5))), truncated: true, warnings: [...warnings, "响应过大已进一步压缩行数,请缩小查询范围或翻页获取。"] };
164
- }
165
165
  return result;
166
166
  }
167
167
 
package/src/config.mjs CHANGED
@@ -111,8 +111,6 @@ export function loadConfig() {
111
111
  executeUrl: `${apiBase.replace(/\/$/, "")}/api/openapi/v1/execute`,
112
112
  credentials,
113
113
  allowWrites: process.env.YSY_ALLOW_WRITES === "true" || local.allowWrites === true,
114
- maxRows: Number(process.env.YSY_MAX_ROWS || local.maxRows || 50),
115
- maxChars: Number(process.env.YSY_MAX_CHARS || local.maxChars || 20000),
116
114
  timeoutMs: Number(process.env.YSY_TIMEOUT_MS || local.timeoutMs || 28000),
117
115
  transport: process.env.YSY_TRANSPORT || "stdio",
118
116
  httpPort: Number(process.env.YSY_HTTP_PORT || 3100),
@@ -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);
@@ -75,6 +76,19 @@ function resolveApi(args) {
75
76
  return found;
76
77
  }
77
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
+
78
92
  function createServer() {
79
93
  const { version } = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
80
94
  const server = new McpServer({ name: "ysy-openapi", version });
@@ -233,14 +247,14 @@ function createServer() {
233
247
  server.registerTool(
234
248
  "query",
235
249
  {
236
- description: "查询经营数据(POST /openapi/v1/query,策略网关)。请求外壳为 {moduleCode, apiCode, params}。自动取 Token、缓存并在 401 时刷新;自动把 YYYY-MM-DD 日期转为毫秒时间戳;自动按数据地图校验 code 并截断超大结果。先用 list_apis 找 apiCode,再用 describe_api 查参数。",
250
+ description: "查询经营数据。分页接口先查询符合条件的总数,超过 500 条则自动分页生成本机 Excel;不超过 500 条完整返回请求页。非分页接口一次返回超过 500 行时生成 Excel。查询结果并非事务快照。",
237
251
  inputSchema: {
238
252
  apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list、goods.list"),
239
253
  actionCode: z.string().optional().describe("apiCode 的兼容别名,与 apiCode 二选一"),
240
254
  moduleCode: z.string().optional().describe("模块 code;省略时按数据地图自动推断"),
241
255
  params: z.record(z.any()).optional().describe("业务参数,放筛选/分页/排序;报表筛选放 params.searches"),
242
256
  pageNum: z.number().int().min(1).optional().describe("页码,从 1 开始;翻页时保持其他筛选条件不变"),
243
- 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"),
244
258
  },
245
259
  },
246
260
  (args) =>
@@ -279,7 +293,50 @@ function createServer() {
279
293
  warnings.push("timeType 快捷日期与 dateStart/dateEnd 自定义区间应二选一,同时传入可能导致筛选不符合预期。");
280
294
  }
281
295
 
282
- 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
+ }
283
340
  return { ...result, warnings: [...warnings, ...result.warnings] };
284
341
  }),
285
342
  );