@teamdream/sems-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.
@@ -0,0 +1,269 @@
1
+ /**
2
+ * P1 只读查询工具(10 个直连转发)。
3
+ *
4
+ * 这些工具的骨架完全一致(分页 + 若干过滤字段 → 一次 GET → 整理分页结构),
5
+ * 差异只在「哪个接口」和「允许哪些过滤字段」。所以用 `defineQuery` 声明,
6
+ * 而不是复制十份 handler —— 复制出来的代码改一处忘十处,是这类工具最常见的腐化方式。
7
+ *
8
+ * 过滤字段的来源见 `schemas.ts` 的说明:**必须是 SEMS 后端认识的字段名**。
9
+ */
10
+ import { z } from "zod";
11
+ import { ProxyError } from "../client/errors.js";
12
+ import { normalizePage } from "./payload.js";
13
+ import { wrap } from "./runner.js";
14
+ import { buildDateShape, PAGE_SHAPE, toQuery } from "./schemas.js";
15
+ function defineQuery(server, ctx, spec) {
16
+ const inputSchema = {
17
+ ...PAGE_SHAPE,
18
+ ...buildDateShape(spec.range),
19
+ ...spec.filters,
20
+ };
21
+ server.registerTool(spec.tool, {
22
+ title: spec.title,
23
+ description: spec.description,
24
+ inputSchema,
25
+ annotations: { readOnlyHint: true },
26
+ }, wrap(ctx, spec.tool, async (args) => {
27
+ const query = { ...spec.fixedQuery, ...toQuery(args, spec.range) };
28
+ if (spec.defaultOrder !== undefined && query["descs"] === undefined) {
29
+ query["descs"] = spec.defaultOrder;
30
+ }
31
+ try {
32
+ const result = await ctx.client.call({ method: "GET", path: spec.path, query });
33
+ return normalizePage(result.data);
34
+ }
35
+ catch (err) {
36
+ // 白名单没放行 ≠ 任务失败:可选数据源降级,其它错误照旧抛出
37
+ if (spec.optionalSource === undefined || !isUnavailableSource(err))
38
+ throw err;
39
+ return unavailableSourceResult(spec.optionalSource, {
40
+ current: query["current"],
41
+ size: query["size"],
42
+ });
43
+ }
44
+ }));
45
+ }
46
+ /** 代理返回 NOT_IN_ALLOWLIST:这个接口还没登记进白名单(新工具没重建 sems-proxy 时最常见)。 */
47
+ export function isUnavailableSource(err) {
48
+ return err instanceof ProxyError && err.code === "NOT_IN_ALLOWLIST";
49
+ }
50
+ /**
51
+ * 可选数据源不可用时的降级结果。
52
+ *
53
+ * 不直接抛错的原因:调用方看到「403 未开放」很容易把整个任务判死,而报价单的
54
+ * 产品来源是市场动态 / 库存 / 标准产品三家(按此顺序取),缺一家不该导致建不了单。
55
+ * 所以把「还能怎么干」写进返回体,而不是留在错误文案里。
56
+ */
57
+ export function unavailableSourceResult(fallback, page = {}) {
58
+ return {
59
+ available: false,
60
+ total: 0,
61
+ current: page.current,
62
+ size: page.size,
63
+ returned: 0,
64
+ records: [],
65
+ reason: "sems-proxy 的白名单里还没有放行这个数据源(白名单在构建期打进镜像,登记后要重建 sems-proxy 才生效)。",
66
+ next: `这个数据源暂时用不了,但**不影响创建报价单**:按 ${fallback.join(" → ")} 的顺位继续取,`
67
+ + "产品名称、规格与成本价仍然只能来自这三处,不要改用商品库或自行编造。",
68
+ };
69
+ }
70
+ const SOLD_TIME = {
71
+ beginField: "soldTimeBegin",
72
+ endField: "soldTimeEnd",
73
+ desc: "销售日期",
74
+ };
75
+ const ORDER_TIME = {
76
+ beginField: "orderTimeBegin",
77
+ endField: "orderTimeEnd",
78
+ desc: "订单日期",
79
+ };
80
+ // 合同用的是 Start 而不是 Begin,写错会静默失效
81
+ const CONTRACT_TIME = {
82
+ beginField: "createTimeStart",
83
+ endField: "createTimeEnd",
84
+ desc: "创建时间",
85
+ };
86
+ export function registerQueries(server, ctx) {
87
+ defineQuery(server, ctx, {
88
+ tool: "sems_query_sales",
89
+ title: "查询销售单",
90
+ path: "/invoicing/sale/page",
91
+ description: "分页查询销售单列表,默认按销售日期倒序。返回 total(总条数)、returned(本页条数)与 records。"
92
+ + "未指定日期区间时由海竣信息系统返回全部可见数据。成本/利润类字段是否返回取决于当前账号权限(无权限时服务端已剥离)。",
93
+ range: SOLD_TIME,
94
+ defaultOrder: "soldTime",
95
+ filters: {
96
+ status: z.string().optional().describe("销售单状态,如 待提交、待审核、待出库、已完成"),
97
+ overdueMonthCount: z.coerce
98
+ .number()
99
+ .int()
100
+ .min(0)
101
+ .optional()
102
+ .describe("收款超期月数阈值,例如传 3 表示筛选逾期超过 3 个月的"),
103
+ descs: z.string().optional().describe("排序字段(默认 soldTime)"),
104
+ ascs: z.string().optional().describe("升序排序字段,与 descs 二选一"),
105
+ },
106
+ });
107
+ defineQuery(server, ctx, {
108
+ tool: "sems_query_purchases",
109
+ title: "查询采购单",
110
+ path: "/invoicing/order-form/page",
111
+ description: "分页查询采购单列表。可用 completeStatus 过滤订单状态、payStatus 过滤付款状态。",
112
+ range: ORDER_TIME,
113
+ defaultOrder: "orderTime",
114
+ filters: {
115
+ completeStatus: z.string().optional().describe("订单完成状态,空字符串表示全部"),
116
+ payStatus: z.coerce
117
+ .number()
118
+ .int()
119
+ .min(1)
120
+ .max(5)
121
+ .optional()
122
+ .describe("付款状态:1=未付款(含部分) 2=部分付款 3=已付款 4=已申请待支付 5=已付未开发票"),
123
+ descs: z.string().optional().describe("排序字段"),
124
+ ascs: z.string().optional(),
125
+ },
126
+ });
127
+ defineQuery(server, ctx, {
128
+ tool: "sems_query_contracts",
129
+ title: "查询合同",
130
+ path: "/invoicing/contract/page",
131
+ description: "分页查询合同列表,默认按创建时间倒序。可按合同编号、客户名称、项目名称过滤。",
132
+ range: CONTRACT_TIME,
133
+ defaultOrder: "create_time",
134
+ filters: {
135
+ contractNo: z.string().optional().describe("合同编号(模糊匹配)"),
136
+ customerName: z.string().optional().describe("客户名称(模糊匹配)"),
137
+ projectName: z.string().optional().describe("项目名称(模糊匹配)"),
138
+ descs: z.string().optional().describe("排序字段(默认 create_time)"),
139
+ },
140
+ });
141
+ defineQuery(server, ctx, {
142
+ tool: "sems_query_quotations",
143
+ title: "查询报价单",
144
+ path: "/invoicing/pre-sale/page",
145
+ description: "分页查询报价单(售前)。可按客户过滤。",
146
+ filters: {
147
+ customer: z.string().optional().describe("客户名称或标识(后端按 customer 字段匹配)"),
148
+ },
149
+ });
150
+ defineQuery(server, ctx, {
151
+ tool: "sems_query_market_quotes",
152
+ title: "查询市场报价",
153
+ path: "/invoicing/market-quote/page",
154
+ description: "分页查询市场行情(市场动态页签的数据源),默认按报价日期倒序。"
155
+ + "🔴 起草报价单时这是**第一顺位**的产品来源:先用 productName / spec / specDetail 找同配置产品,"
156
+ + "命中的 unitPrice 即成本价、supplierName 即供应商,productName/spec/specDetail/unit/remarks 原样带进明细。"
157
+ + "⚠️ spec 参数在后端是「规格型号 OR 规格详情」模糊匹配,要精确比对请取回结果后自行核对。",
158
+ defaultOrder: "quoteDate",
159
+ optionalSource: [
160
+ "sems_query_stock(库存)",
161
+ "sems_query_vendor_prices(标准产品)",
162
+ ],
163
+ filters: {
164
+ productName: z.string().optional().describe("产品名称(模糊匹配)"),
165
+ spec: z.string().optional().describe("规格型号(模糊匹配,同时会匹配规格详情)"),
166
+ specDetail: z.string().optional().describe("规格详情(模糊匹配)"),
167
+ brand: z.string().optional().describe("品牌/物料(模糊匹配)"),
168
+ descs: z.string().optional().describe("排序字段(默认 quoteDate)"),
169
+ },
170
+ });
171
+ defineQuery(server, ctx, {
172
+ tool: "sems_query_vendor_prices",
173
+ title: "查询报价产品",
174
+ path: "/invoicing/market-quote/page",
175
+ fixedQuery: { bizType: "standard_product" },
176
+ description: "分页查询标准产品清单(市场动态页签旁的「标准产品」页签,与市场动态同表,本工具固定只取标准产品),"
177
+ + "成本参考价在 unitPrice 字段。"
178
+ + "🔴 起草报价单时它是**第三顺位**(最后一家)产品来源:前两顺位(市场动态、库存)都没有同配置时才用它。"
179
+ + "🔴 按 pre_sale_management 鉴权,没有报价单权限的账号会 403。",
180
+ defaultOrder: "quoteDate",
181
+ optionalSource: [
182
+ "sems_query_market_quotes(市场动态)",
183
+ "sems_query_stock(库存)",
184
+ ],
185
+ filters: {
186
+ productName: z.string().optional().describe("产品名称(模糊匹配)"),
187
+ spec: z.string().optional().describe("规格型号(模糊匹配,同时会匹配规格详情)"),
188
+ specDetail: z.string().optional().describe("规格详情(模糊匹配)"),
189
+ brand: z.string().optional().describe("品牌(模糊匹配)"),
190
+ descs: z.string().optional().describe("排序字段(默认 quoteDate)"),
191
+ },
192
+ });
193
+ defineQuery(server, ctx, {
194
+ tool: "sems_query_stock",
195
+ title: "查询库存",
196
+ path: "/invoicing/storage-manage-record/page",
197
+ description: "分页查询库存流水,默认按最近入库时间升序,且只返回有货的记录(可用量 amountRemain 或待出库量非 0)。"
198
+ + "🔴 起草报价单时这是**第二顺位**的产品来源(市场动态没同配置时用它):"
199
+ + "成本取 unitPrice(页面列名「销售成本」,需要 sale_cost_view_in_storage 权限,无权限时该字段不返回),"
200
+ + "name/spec/specDetail 原样带进明细,可用量 amountRemain 用于核对能不能交付。"
201
+ + "⚠️ name / spec / specDetail 在后端是 **OR** 关系(任一命中即返回),要按配置精确匹配请一次只传一个词,"
202
+ + "取回结果后自行比对名称与配置。"
203
+ + "另外:海竣信息系统没有「按商品汇总的库存」独立接口,要多商品汇总请用 sems_stat 的 inventory 类型。",
204
+ optionalSource: [
205
+ "sems_query_market_quotes(市场动态)",
206
+ "sems_query_vendor_prices(标准产品)",
207
+ ],
208
+ filters: {
209
+ name: z.string().optional().describe("产品名称(模糊匹配,与 spec/specDetail 是 OR 关系)"),
210
+ spec: z.string().optional().describe("规格型号(模糊匹配,与 name/specDetail 是 OR 关系)"),
211
+ specDetail: z.string().optional().describe("规格详情(模糊匹配,与 name/spec 是 OR 关系)"),
212
+ storageType: z.coerce
213
+ .number()
214
+ .int()
215
+ .min(1)
216
+ .max(2)
217
+ .optional()
218
+ .describe("库存类型:1=常规库存 2=临时库存"),
219
+ includingEmpty: z
220
+ .boolean()
221
+ .optional()
222
+ .describe("是否包含可用量为 0 的记录,默认 false(只看有货)"),
223
+ ascs: z.string().optional().describe("升序排序字段(默认 lastStorageTime)"),
224
+ },
225
+ });
226
+ defineQuery(server, ctx, {
227
+ tool: "sems_query_products",
228
+ title: "查询商品",
229
+ path: "/invoicing/product/page",
230
+ description: "分页查询商品档案。🔴 只支持按 name 模糊搜索,不支持按规格/编码搜索。"
231
+ + "🔴 **报价单不要用它取产品**:报价明细的产品只能来自市场动态 / 库存 / 标准产品三处,"
232
+ + "本工具仅用于查商品档案(如核对分类、单位、是否定制)。",
233
+ filters: {
234
+ name: z.string().optional().describe("商品名称(模糊匹配)"),
235
+ },
236
+ });
237
+ defineQuery(server, ctx, {
238
+ tool: "sems_query_daily_reports",
239
+ title: "查询工作日志",
240
+ path: "/synergy/daily-report/page",
241
+ description: "分页查询工作日志(周报素材)。受账号数据范围约束,普通员工通常只能看到自己与下属的。"
242
+ + "后端未提供可靠的日期过滤参数,需要按时间筛选请用返回记录里的日期字段自行判断。",
243
+ });
244
+ // 客户与供应商是两个接口但共用同一个查询对象(CustomerQuery),
245
+ // 参数名都是 customerName —— 写成 supplierName 不会被后端识别,会静默返回全量。
246
+ server.registerTool("sems_query_partners", {
247
+ title: "查询客户或供应商",
248
+ description: "分页查询客户(kind=customer)或供应商(kind=supplier)。供应商与客户共用同一张表与同一个查询对象,"
249
+ + "所以过滤参数都叫 customerName。",
250
+ inputSchema: {
251
+ ...PAGE_SHAPE,
252
+ kind: z
253
+ .enum(["customer", "supplier"])
254
+ .describe("查客户还是供应商"),
255
+ customerName: z.string().optional().describe("客户/供应商名称(模糊匹配)"),
256
+ },
257
+ annotations: { readOnlyHint: true },
258
+ }, wrap(ctx, "sems_query_partners", async (args) => {
259
+ const kind = args["kind"] === "supplier" ? "supplier" : "customer";
260
+ const query = toQuery({
261
+ current: args["current"],
262
+ size: args["size"],
263
+ customerName: args["customerName"],
264
+ }, undefined);
265
+ const result = await ctx.client.call({ method: "GET", path: `/scm/${kind}/page`, query });
266
+ return normalizePage(result.data);
267
+ }));
268
+ }
269
+ //# sourceMappingURL=queries.js.map
@@ -0,0 +1,67 @@
1
+ /**
2
+ * 工具执行的统一外壳:权限预检 → 执行 → 归一化错误 → 文本化。
3
+ *
4
+ * 所有工具都走这一条路径,好处是三件事只需要做对一次:
5
+ * ① 缺权限时不发上游请求 ② 错误码到中文文案的映射 ③ 上下文体积保护。
6
+ */
7
+ import { ProxyError } from "../client/errors.js";
8
+ import { log } from "../logger.js";
9
+ import { specOf } from "./context.js";
10
+ /**
11
+ * 进入对话上下文的文本上限。
12
+ *
13
+ * 一页 100 行 × 几十个字段轻易超过 100KB,全塞进上下文会挤掉真正的对话历史,
14
+ * 而且是「用户没感知的变慢/变贵」。超限时截断并明确提示怎么缩小范围,
15
+ * 而不是悄悄丢掉后半段。
16
+ */
17
+ const MAX_TEXT = 48_000;
18
+ function toText(data) {
19
+ const text = JSON.stringify(data) ?? "null";
20
+ if (text.length <= MAX_TEXT)
21
+ return text;
22
+ return `${text.slice(0, MAX_TEXT)}…(已截断,原始响应共 ${text.length} 字符。请缩小查询范围:减小 size、加上时间区间,或先查汇总再查明细)`;
23
+ }
24
+ function failure(tool, err) {
25
+ if (err instanceof ProxyError) {
26
+ const lines = [`调用 ${tool} 失败:${err.message}`, `错误码:${err.code}`];
27
+ if (err.hint)
28
+ lines.push(`怎么办:${err.hint}`);
29
+ if (err.detail)
30
+ lines.push(`详情:${err.detail}`);
31
+ log.warn(`${tool} 失败`, { code: err.code, detail: err.detail });
32
+ return { content: [{ type: "text", text: lines.join("\n") }], isError: true };
33
+ }
34
+ const message = err instanceof Error ? err.message : String(err);
35
+ log.error(`${tool} 未预期异常`, { message });
36
+ return {
37
+ content: [
38
+ {
39
+ type: "text",
40
+ text: `调用 ${tool} 时发生未预期错误:${message}\n这通常是 sems-mcp 的缺陷,请把这条信息反馈给管理员。`,
41
+ },
42
+ ],
43
+ isError: true,
44
+ };
45
+ }
46
+ /** 生成可直接交给 `server.registerTool` 的回调。 */
47
+ export function wrap(ctx, name, handler) {
48
+ const spec = specOf(name);
49
+ return async (args) => {
50
+ try {
51
+ // 只读工具在 tools.yaml 里没有 perm 的(如库存/商品)仍需登录态,
52
+ // 但登录态由 proxy 的签名校验保证,这里传 null 即跳过预检。
53
+ await ctx.guard.require(spec.perm);
54
+ const data = await handler(args);
55
+ return { content: [{ type: "text", text: toText(data) }] };
56
+ }
57
+ catch (err) {
58
+ // 令牌类错误往往意味着权限也变了,清掉缓存让下次重新拉;绑定换了账号时档案同样失效。
59
+ if (err instanceof ProxyError && (err.code === "REBIND_REQUIRED" || err.http === 401)) {
60
+ ctx.guard.invalidate();
61
+ ctx.userProfile.invalidate();
62
+ }
63
+ return failure(name, err);
64
+ }
65
+ };
66
+ }
67
+ //# sourceMappingURL=runner.js.map
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 工具入参的公共片段与查询串构造。
3
+ *
4
+ * 🔴 **参数名必须逐字等于 SEMS 后端的字段名**。写错不会有任何报错:SEMS 用
5
+ * MyBatis-Plus 动态构造条件,不认识的参数会被静默忽略,于是「按客户筛选」变成
6
+ * 「返回全部销售单」。LLM 拿到全量数据会当成筛选结果来回答,这类错误比报错危险得多。
7
+ * 所以本文件登记的字段全部来自前端 `stores/list-store-configs/*.js` 里实际在用的键名。
8
+ */
9
+ import { z } from "zod";
10
+ /** 分页参数。`size` 上限 100 与 proxy 的 `check_query` 一致,在 schema 层就拦住。 */
11
+ export const PAGE_SHAPE = {
12
+ current: z.coerce.number().int().min(1).optional().describe("页码,从 1 开始,默认 1"),
13
+ size: z.coerce.number().int().min(1).max(100).optional().describe("每页条数,1-100,默认 20"),
14
+ };
15
+ /** 日期参数:只写日期时自动补时分秒,避免「传 2026-10-01 结果查不到当天数据」。 */
16
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
17
+ export const DATE_FIELD_DESC = "格式 YYYY-MM-DD 或 YYYY-MM-DD HH:mm:ss";
18
+ export function buildDateShape(range) {
19
+ if (!range)
20
+ return {};
21
+ return {
22
+ [range.beginField]: z.string().optional().describe(`${range.desc}起(${DATE_FIELD_DESC})`),
23
+ [range.endField]: z.string().optional().describe(`${range.desc}止(${DATE_FIELD_DESC})`),
24
+ };
25
+ }
26
+ function padDay(value, end) {
27
+ if (!DATE_ONLY.test(value))
28
+ return value;
29
+ return `${value} ${end ? "23:59:59" : "00:00:00"}`;
30
+ }
31
+ /**
32
+ * 把工具入参转成 query 串:空值剔除、日期补齐、其余原样透传。
33
+ *
34
+ * 透传是安全的——因为每个工具的 `filters` 已用 zod 白名单固定了允许的键,
35
+ * 未声明的参数在 SDK 那一层就被丢弃了,不会到这里。
36
+ */
37
+ export function toQuery(args, range) {
38
+ const query = {};
39
+ for (const [key, value] of Object.entries(args)) {
40
+ // ⚠️ 只过滤 undefined/null/"":`false` 和 `0` 是有意义的取值
41
+ // (如 includingEmpty=false 表示「不包含空库存」),不能被当成「没传」。
42
+ if (value === undefined || value === null || value === "")
43
+ continue;
44
+ if (range && key === range.beginField && typeof value === "string") {
45
+ query[key] = padDay(value, false);
46
+ continue;
47
+ }
48
+ if (range && key === range.endField && typeof value === "string") {
49
+ query[key] = padDay(value, true);
50
+ continue;
51
+ }
52
+ if (typeof value === "boolean") {
53
+ query[key] = value ? "true" : "false";
54
+ continue;
55
+ }
56
+ if (typeof value === "string" || typeof value === "number")
57
+ query[key] = value;
58
+ }
59
+ return query;
60
+ }
61
+ //# sourceMappingURL=schemas.js.map