@chaoyue-erp/ysy-openapi-mcp 1.0.0 → 1.0.3

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/src/server.mjs CHANGED
@@ -26,6 +26,44 @@ const wrap = async (fn) => {
26
26
  }
27
27
  };
28
28
 
29
+ // 分页按 Unicode 字符计数,避免切断汉字或 emoji;每页始终返回续读位置。
30
+ function pageDocument(value, offset = 0, limit = 3000) {
31
+ const format = typeof value === "string" ? "text" : "json";
32
+ const content = format === "text" ? value : JSON.stringify(value, null, 2);
33
+ const chars = Array.from(content ?? "");
34
+ const start = Math.min(offset, chars.length);
35
+ const next = Math.min(start + limit, chars.length);
36
+ return {
37
+ format,
38
+ text: chars.slice(start, next).join(""),
39
+ offset: start,
40
+ returnedChars: next - start,
41
+ totalChars: chars.length,
42
+ hasMore: next < chars.length,
43
+ nextOffset: next < chars.length ? next : null,
44
+ hint: format === "json" && chars.length > limit ? "JSON 按字符分页;需要完整 JSON 时请按 nextOffset 拼接所有 text。" : undefined,
45
+ };
46
+ }
47
+
48
+ const DOC_PAGE_SCHEMA = {
49
+ offset: z.number().int().min(0).optional().describe("字符偏移,从 0 开始;续读时传上次返回的 nextOffset"),
50
+ limit: z.number().int().min(1).max(4000).optional().describe("每页最多 4000 个 Unicode 字符,默认 3000"),
51
+ };
52
+
53
+ // 保留旧字段,限制摘要大小;被省略的内容可通过 read_api_document 完整续读。
54
+ function briefArray(value, maxItems = 40, maxChars = 5000) {
55
+ const all = Array.isArray(value) ? value : [];
56
+ const items = [];
57
+ let used = 0;
58
+ for (const item of all) {
59
+ const size = JSON.stringify(item).length;
60
+ if (items.length >= maxItems || used + size > maxChars) break;
61
+ items.push(item);
62
+ used += size;
63
+ }
64
+ return { items, total: all.length, returned: items.length, hasMore: items.length < all.length };
65
+ }
66
+
29
67
  function resolveApi(args) {
30
68
  const code = args.apiCode || args.actionCode;
31
69
  if (!code) throw new Error("请提供 apiCode(文档中的字段名为 apiCode,不是 actionCode;actionCode 仅作为兼容别名)。");
@@ -38,12 +76,13 @@ function resolveApi(args) {
38
76
  }
39
77
 
40
78
  function createServer() {
41
- const server = new McpServer({ name: "ysy-openapi", version: "1.0.0" });
79
+ const { version } = JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"));
80
+ const server = new McpServer({ name: "ysy-openapi", version });
42
81
 
43
82
  server.registerTool(
44
83
  "list_modules",
45
84
  {
46
- description: "列出悦商云开放接口的业务模块。一个客户端只对应一个模块,取 Token 前需确认该模块已配置密钥。返回模块名、接口数和密钥配置状态。",
85
+ description: "列出开放接口的业务模块与密钥配置状态。配置状态不代表模块或接口已获授权,实际权限由服务端校验。",
47
86
  inputSchema: {},
48
87
  },
49
88
  () =>
@@ -59,7 +98,7 @@ function createServer() {
59
98
  credentialsConfigured: ready.has(code),
60
99
  })),
61
100
  notConfigured: missingModules(cfg),
62
- hint: "一个客户端对应一个模块,多模块需分别领取密钥并分别取 Token。",
101
+ hint: "密钥已配置只表示客户端已填写凭据;各模块及接口能否调用,以服务端授权为准。",
63
102
  };
64
103
  }),
65
104
  );
@@ -81,7 +120,7 @@ function createServer() {
81
120
  if (args.kind) list = list.filter((a) => a.kind === args.kind);
82
121
  if (args.keyword) {
83
122
  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));
123
+ 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
124
  }
86
125
  return {
87
126
  total: list.length,
@@ -94,9 +133,9 @@ function createServer() {
94
133
  server.registerTool(
95
134
  "describe_api",
96
135
  {
97
- description: "查看某个 apiCode 的完整参数说明:params 参数表、报表 searches 可用 key、请求示例、返回字段与数据路径。填写 query 的 params 前必须先调用此工具。",
136
+ description: "查看接口摘要与参数。完整请求、响应、公共说明、附表和所有示例请用 read_api_document 分节分页读取。",
98
137
  inputSchema: {
99
- apiCode: z.string().describe("完整接口 code,区分大小写,如 sale.list"),
138
+ apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list"),
100
139
  actionCode: z.string().optional().describe("apiCode 的兼容别名,二选一"),
101
140
  },
102
141
  },
@@ -104,6 +143,9 @@ function createServer() {
104
143
  wrap(() => {
105
144
  const a = resolveApi(args);
106
145
  const rules = DATA_MAP.commonRules;
146
+ const fieldNames = ["params", "formFields", "executeFields", "searchKeys", "responseFields"];
147
+ const brief = Object.fromEntries(fieldNames.map((name) => [name, briefArray(a[name])]));
148
+ const exampleOmitted = JSON.stringify(a.requestExample ?? null).length > 5000;
107
149
  const out = {
108
150
  apiCode: a.apiCode,
109
151
  name: a.name,
@@ -112,12 +154,12 @@ function createServer() {
112
154
  entry: a.entry,
113
155
  resultPath: a.resultPath,
114
156
  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),
157
+ params: brief.params.items,
158
+ formFields: brief.formFields.items,
159
+ executeFields: brief.executeFields.items,
160
+ searchKeys: brief.searchKeys.items,
161
+ requestExample: exampleOmitted ? null : a.requestExample,
162
+ responseFields: brief.responseFields.items,
121
163
  responseNotes: a.responseNotes,
122
164
  rules: {
123
165
  success: rules.success,
@@ -127,6 +169,11 @@ function createServer() {
127
169
  detailId: rules.detailId,
128
170
  sort: rules.sort,
129
171
  },
172
+ documentAccess: {
173
+ fields: Object.fromEntries(fieldNames.map((name) => [name, { total: brief[name].total, returned: brief[name].returned, hasMore: brief[name].hasMore }])),
174
+ requestExampleOmitted: exampleOmitted,
175
+ hint: "摘要和部分字段可能省略;调用 read_api_document 按 section 与 nextOffset 查看完整内容。",
176
+ },
130
177
  };
131
178
  if (a.kind !== "query") {
132
179
  out.warning = `此 code 属于 ${a.entry} 入口(写入类),不能用 query 工具调用;且写入工具默认禁用。`;
@@ -137,10 +184,56 @@ function createServer() {
137
184
  }),
138
185
  );
139
186
 
187
+ server.registerTool(
188
+ "read_api_document",
189
+ {
190
+ description: "按章节和字符偏移完整读取指定接口文档。大章节按 nextOffset 续读;所有示例、附表、请求、响应和公共说明均可读取。",
191
+ inputSchema: {
192
+ apiCode: z.string().describe("完整接口 code,例如 sale.list"),
193
+ section: z.enum(["requestText", "responseText", "commonText", "searchText", "params", "searchKeys", "formFields", "executeFields", "responseFields", "extraTables", "sourceTables", "requestExamples", "responseExamples", "commonExamples"]).describe("接口文档章节名称"),
194
+ ...DOC_PAGE_SCHEMA,
195
+ },
196
+ },
197
+ (args) => wrap(() => {
198
+ const a = resolveApi(args);
199
+ const value = a[args.section];
200
+ if (value === undefined) throw new Error(`该接口尚未包含 ${args.section} 章节,请先用新版生成脚本更新数据地图。`);
201
+ return { apiCode: a.apiCode, section: args.section, ...pageDocument(value, args.offset, args.limit) };
202
+ }),
203
+ );
204
+
205
+ server.registerTool(
206
+ "read_reference_document",
207
+ {
208
+ description: "列出或按章节分页读取公共指南与公共规则。category=guides 时不传 guideId 列出指南;传 guideId 和 section 读取内容;category=rules 按 rule 读取公共规则。",
209
+ inputSchema: {
210
+ category: z.enum(["guides", "rules"]).describe("guides=文档公共指南;rules=连接器公共规则"),
211
+ guideId: z.string().optional().describe("指南 id,先不传以查看目录"),
212
+ section: z.enum(["text", "tables", "examples"]).optional().describe("指南章节;默认 text"),
213
+ rule: z.string().optional().describe("公共规则键;不传时列出可用键"),
214
+ ...DOC_PAGE_SCHEMA,
215
+ },
216
+ },
217
+ (args) => wrap(() => {
218
+ if (args.category === "rules") {
219
+ const rules = DATA_MAP.commonRules || {};
220
+ if (!args.rule) return { category: "rules", keys: Object.keys(rules) };
221
+ if (!Object.hasOwn(rules, args.rule)) throw new Error(`未找到公共规则 ${args.rule}`);
222
+ return { category: "rules", rule: args.rule, ...pageDocument(rules[args.rule], args.offset, args.limit) };
223
+ }
224
+ const guides = DATA_MAP.guides || [];
225
+ if (!args.guideId) return { category: "guides", total: guides.length, ...pageDocument(guides.map(({ id, title }) => ({ id, title })), args.offset, args.limit) };
226
+ const guide = guides.find((g) => g.id === args.guideId);
227
+ if (!guide) throw new Error(`未找到公共指南 ${args.guideId}`);
228
+ const section = args.section || "text";
229
+ return { category: "guides", guideId: guide.id, title: guide.title, section, ...pageDocument(guide[section] ?? (section === "text" ? "" : []), args.offset, args.limit) };
230
+ }),
231
+ );
232
+
140
233
  server.registerTool(
141
234
  "query",
142
235
  {
143
- description: "调用悦商云策略网关查询数据(POST /openapi/v1/query)。请求外壳为 {moduleCode, apiCode, params}。自动取 Token、缓存并在 401 时刷新;自动把 YYYY-MM-DD 日期转为毫秒时间戳;自动按数据地图校验 code 并截断超大结果。",
236
+ description: "查询经营数据(POST /openapi/v1/query,策略网关)。请求外壳为 {moduleCode, apiCode, params}。自动取 Token、缓存并在 401 时刷新;自动把 YYYY-MM-DD 日期转为毫秒时间戳;自动按数据地图校验 code 并截断超大结果。先用 list_apis 找 apiCode,再用 describe_api 查参数。",
144
237
  inputSchema: {
145
238
  apiCode: z.string().optional().describe("完整接口 code,区分大小写,如 sale.list、goods.list"),
146
239
  actionCode: z.string().optional().describe("apiCode 的兼容别名,与 apiCode 二选一"),
@@ -194,7 +287,7 @@ function createServer() {
194
287
  server.registerTool(
195
288
  "check_connection",
196
289
  {
197
- description: "自检连接器配置:环境地址、各模块密钥是否齐全、能否成功获取 Token。不返回 Token 明文。排查 401/403 时先用此工具。",
290
+ description: "自检配置和 Token 获取情况,不返回 Token 明文。获取成功并不证明任一模块或接口已获授权;接口权限以实际调用和服务端授权为准。",
198
291
  inputSchema: {
199
292
  moduleCode: z.string().optional().describe("只检查某个模块;省略则检查全部已配置模块"),
200
293
  },
@@ -219,7 +312,7 @@ function createServer() {
219
312
  try {
220
313
  const before = Date.now();
221
314
  await tokens.get(m, { force: true });
222
- results.push({ moduleCode: m, ok: true, elapsedMs: Date.now() - before, message: "Token 获取成功" });
315
+ results.push({ moduleCode: m, ok: true, elapsedMs: Date.now() - before, message: "Token 获取成功;这不代表该模块或接口已获授权,请以实际接口调用和服务端授权为准。" });
223
316
  } catch (err) {
224
317
  results.push({ moduleCode: m, ok: false, message: err.message });
225
318
  }
@@ -231,6 +324,7 @@ function createServer() {
231
324
  queryUrl: cfg.queryUrl,
232
325
  allowWrites: cfg.allowWrites,
233
326
  results,
327
+ authorizationNote: "此检查仅验证能否获取 Token;成功不代表每个模块或接口都已获授权。",
234
328
  notConfigured: missingModules(cfg),
235
329
  };
236
330
  }),
@@ -1,9 +1,12 @@
1
- import { DATA_MAP } from "./config.mjs";
1
+ import { DATA_MAP, SHARED, credentialFor } from "./config.mjs";
2
2
  import { TokenError } from "./errors.mjs";
3
3
 
4
4
  const REFRESH_MARGIN_MS = 60_000;
5
5
 
6
- /** 多模块 Token 管理:一个客户端对应一个模块,分别取 Token、分别缓存。 */
6
+ /**
7
+ * Token 管理:按模块缓存 access_token,到期前 60 秒提前刷新。
8
+ * 只有一个客户端时各模块共用同一凭据,缓存也共用一份,避免重复换票。
9
+ */
7
10
  export class TokenManager {
8
11
  constructor(cfg) {
9
12
  this.cfg = cfg;
@@ -11,8 +14,12 @@ export class TokenManager {
11
14
  this.inflight = new Map();
12
15
  }
13
16
 
17
+ #cacheKey(moduleCode) {
18
+ return this.cfg.credentials[moduleCode] ? moduleCode : SHARED;
19
+ }
20
+
14
21
  hasCredentials(moduleCode) {
15
- const c = this.cfg.credentials[moduleCode];
22
+ const c = credentialFor(this.cfg.credentials, moduleCode);
16
23
  return Boolean(c?.clientId && c?.clientSecret);
17
24
  }
18
25
 
@@ -21,28 +28,30 @@ export class TokenManager {
21
28
  if (!this.hasCredentials(moduleCode)) {
22
29
  const hint = DATA_MAP.commonRules.auth.note;
23
30
  throw new TokenError(
24
- `模块 ${moduleCode} 未配置客户端凭据。请在 config.json 的 credentials.${moduleCode} 填写 clientId / clientSecret,或填写 YSY_CLIENT_CREDENTIALS。规范:${hint}`,
31
+ `未配置客户端凭据。请在连接器表单的 YSY_CLIENT_CREDENTIALS 填写 {"clientId":"..","clientSecret":".."}(单个客户端通用),` +
32
+ `或按模块分别填写 {"${moduleCode}":{"clientId":"..","clientSecret":".."}}。规范:${hint}`,
25
33
  );
26
34
  }
27
35
 
28
- const cached = this.cache.get(moduleCode);
36
+ const key = this.#cacheKey(moduleCode);
37
+ const cached = this.cache.get(key);
29
38
  if (!force && cached && Date.now() < cached.expiresAt - REFRESH_MARGIN_MS) {
30
39
  return cached.value;
31
40
  }
32
- if (this.inflight.has(moduleCode)) return this.inflight.get(moduleCode);
41
+ if (this.inflight.has(key)) return this.inflight.get(key);
33
42
 
34
43
  const job = this.#fetch(moduleCode)
35
44
  .then((entry) => {
36
- this.cache.set(moduleCode, entry);
45
+ this.cache.set(key, entry);
37
46
  return entry.value;
38
47
  })
39
- .finally(() => this.inflight.delete(moduleCode));
40
- this.inflight.set(moduleCode, job);
48
+ .finally(() => this.inflight.delete(key));
49
+ this.inflight.set(key, job);
41
50
  return job;
42
51
  }
43
52
 
44
53
  async #fetch(moduleCode) {
45
- const { clientId, clientSecret } = this.cfg.credentials[moduleCode];
54
+ const { clientId, clientSecret } = credentialFor(this.cfg.credentials, moduleCode);
46
55
  const basic = Buffer.from(`${clientId}:${clientSecret}`, "utf8").toString("base64");
47
56
  const controller = new AbortController();
48
57
  const timer = setTimeout(() => controller.abort(), 10_000);
@@ -59,7 +68,7 @@ export class TokenManager {
59
68
  signal: controller.signal,
60
69
  });
61
70
  } catch (err) {
62
- throw new TokenError(`获取 Token 失败(模块 ${moduleCode}):无法连接认证服务 ${this.cfg.tokenUrl}。${err.message}`);
71
+ throw new TokenError(`获取 Token 失败:无法连接认证服务 ${this.cfg.tokenUrl}。${err.message}`);
63
72
  } finally {
64
73
  clearTimeout(timer);
65
74
  }
@@ -79,10 +88,10 @@ export class TokenManager {
79
88
  unsupported_grant_type: "grant_type 固定为 client_credentials。",
80
89
  temporarily_unavailable: "认证服务暂不可用(503),稍后重试。",
81
90
  };
82
- throw new TokenError(`获取 Token 失败(模块 ${moduleCode},HTTP ${res.status},${code}):${tips[code] || text.slice(0, 200)}`);
91
+ throw new TokenError(`获取 Token 失败(HTTP ${res.status},${code}):${tips[code] || text.slice(0, 200)}`);
83
92
  }
84
93
  if (!body.access_token) {
85
- throw new TokenError(`获取 Token 失败(模块 ${moduleCode}):响应缺少 access_token。`);
94
+ throw new TokenError("获取 Token 失败:响应缺少 access_token。");
86
95
  }
87
96
  const expiresIn = Number(body.expires_in) || 3600;
88
97
  return {
@@ -93,6 +102,6 @@ export class TokenManager {
93
102
  }
94
103
 
95
104
  invalidate(moduleCode) {
96
- this.cache.delete(moduleCode);
105
+ this.cache.delete(this.#cacheKey(moduleCode));
97
106
  }
98
107
  }