@teamdream/sems-mcp 0.0.0-stage → 1.1.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,72 @@
1
+ /**
2
+ * 权限预检:调用前先问「这个人有没有权限」,没有就不发请求。
3
+ *
4
+ * 为什么不能只靠 SEMS 拒绝:
5
+ * 1. SEMS 的越权返回是通用错误,用户看不懂「为什么不行」;我们能说清缺的是哪个权限的中文名。
6
+ * 2. 少一次无效上游请求,也少一条会被误读的审计记录。
7
+ *
8
+ * 权限来源与前端 `stores/user.js` 同源:`GET /admin/user/info` 的 `data.permissions`。
9
+ *
10
+ * 🔴 **fail-closed**:拿到的结构不认识(字段改名、被中间层改写)时按「一个权限都没有」处理。
11
+ * 反过来(结构异常就放行)会让越权在配置漂移时静默发生,而这类错误没有任何报错。
12
+ */
13
+ import { localError } from "./client/errors.js";
14
+ import { permissionName } from "./generated/manifest.js";
15
+ import { log } from "./logger.js";
16
+ /** 从 SEMS 响应里取出权限码集合。结构不认识就返回空集合(fail-closed)。 */
17
+ export function extractPermissions(payload) {
18
+ const data = payload?.data;
19
+ if (typeof data !== "object" || data === null)
20
+ return new Set();
21
+ const raw = data.permissions;
22
+ if (!Array.isArray(raw))
23
+ return new Set();
24
+ const codes = raw.filter((item) => typeof item === "string" && item.length > 0);
25
+ return new Set(codes);
26
+ }
27
+ export class PermissionGuard {
28
+ client;
29
+ ttlMs;
30
+ now;
31
+ #cache = null;
32
+ #expiresAt = 0;
33
+ constructor(client, ttlMs = 60_000, now = Date.now) {
34
+ this.client = client;
35
+ this.ttlMs = ttlMs;
36
+ this.now = now;
37
+ }
38
+ /** 带缓存地取权限集合;`force` 用于收到 401/403 之后的重载。 */
39
+ async load(force = false) {
40
+ if (!force && this.#cache !== null && this.now() < this.#expiresAt) {
41
+ return this.#cache;
42
+ }
43
+ const result = await this.client.call({ method: "GET", path: "/admin/user/info" });
44
+ const permissions = extractPermissions(result.data);
45
+ this.#cache = permissions;
46
+ this.#expiresAt = this.now() + this.ttlMs;
47
+ log.debug(`权限已加载:${permissions.size} 项`);
48
+ return permissions;
49
+ }
50
+ /**
51
+ * 缺少权限时抛本地错误(不发任何上游请求)。`codes` 为空表示该工具只需登录态。
52
+ *
53
+ * 为什么是列表:SEMS 后端多处用 `hasPermission('a','b')` 表达**或**语义
54
+ * (市场动态读接口即「管理|只读|报价单」任一个)。这里必须同样取任一命中,
55
+ * 否则持有另一种合法权限的用户会在本地预检被拦掉——表现为「我明明有权限却用不了」。
56
+ */
57
+ async require(codes) {
58
+ if (!codes || codes.length === 0)
59
+ return;
60
+ const permissions = await this.load();
61
+ if (codes.some((code) => permissions.has(code)))
62
+ return;
63
+ const names = codes.map((code) => `「${permissionName(code)}」`).join("或");
64
+ // 单码时不能说「权限之一」,绝大多数工具都是单码
65
+ const need = codes.length > 1 ? `${names}权限之一` : `${names}权限`;
66
+ throw localError("PERMISSION_DENIED", `你需要${need}(权限码 ${codes.join(" / ")})。请让管理员在海竣信息系统的角色里勾选对应菜单。`);
67
+ }
68
+ invalidate() {
69
+ this.#cache = null;
70
+ this.#expiresAt = 0;
71
+ }
72
+ }
package/dist/redeem.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * 用连接器表单里填的绑定码换取本机密钥。
3
+ *
4
+ * ## 为什么需要这一步
5
+ *
6
+ * 连接器的「用户自填凭证」表单只能收文本,没法替用户打开浏览器,所以绑定必须先在
7
+ * 网页上做完:用户在 `<proxy>/bind` 输入账号密码、勾选公司,页面给出一个一次性绑定码。
8
+ * 这个码就是 proxy 的 `poll_token` —— 与 `sems-mcp-bind` 命令行拿到的是同一个东西,
9
+ * 区别只在「谁拿着它去 poll」。
10
+ *
11
+ * 换到密钥后写入 `binding.json`,之后的行为与手工跑绑定命令完全一样。
12
+ *
13
+ * ## 有码就兑换,不提前跳过
14
+ *
15
+ * 网页重新绑定会把同账号同公司的旧密钥置为失效。若这里在「本机已有同一地址的绑定」时
16
+ * 直接跳过,用户拿到的新绑定码就永远用不上,只能手删 binding.json 才能自救。所以只要
17
+ * 表单带回了码就尝试兑换;兑换失败时再回退到本机已有的绑定,不让一个过期码挡住启动。
18
+ *
19
+ * ## 失败不阻断开机
20
+ *
21
+ * 兑换失败(码过期、网页还没提交完、proxy 连不上、文件写不进去)只返回原因,不抛异常。
22
+ * 进程必须起得来,工具列表先给出来,用户才有地方看到「请重新绑定」的提示。
23
+ */
24
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { dirname } from "node:path";
26
+ import { defaultBindingPath } from "./config.js";
27
+ /** 网页刚提交完、proxy 还没把票置为 APPROVED 时的重试节奏。 */
28
+ const RETRY_INTERVAL_MS = 900;
29
+ const MAX_ATTEMPTS = 6;
30
+ function pick(value) {
31
+ return typeof value === "string" ? value.trim() : "";
32
+ }
33
+ function sleep(ms) {
34
+ return new Promise((resolve) => setTimeout(resolve, ms));
35
+ }
36
+ /** 已绑定的地址与当前填的地址一致才算「同一套环境」;换服务器时应当重新兑换。 */
37
+ function boundToSameProxy(path, base) {
38
+ try {
39
+ const doc = JSON.parse(readFileSync(path, "utf8"));
40
+ const saved = pick(doc["proxy_base_url"]).replace(/\/+$/, "");
41
+ const hasKey = pick(doc["key_id"]) && pick(doc["secret"]);
42
+ return Boolean(hasKey) && saved === base;
43
+ }
44
+ catch {
45
+ // 文件损坏或读不到:当作没绑定,让兑换流程重建一份
46
+ return false;
47
+ }
48
+ }
49
+ function persist(path, payload, fallbackBase) {
50
+ const identities = Array.isArray(payload.identities) ? payload.identities : [];
51
+ const doc = {
52
+ proxy_base_url: pick(payload.proxy_base_url) || fallbackBase,
53
+ key_id: pick(payload.key_id),
54
+ secret: pick(payload.secret),
55
+ ...(payload.sems_username ? { sems_username: payload.sems_username } : {}),
56
+ ...(payload.sems_tenant_id === undefined
57
+ ? {}
58
+ : { sems_tenant_id: String(payload.sems_tenant_id) }),
59
+ identities,
60
+ };
61
+ mkdirSync(dirname(path), { recursive: true });
62
+ writeFileSync(path, `${JSON.stringify(doc, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
63
+ return identities.length;
64
+ }
65
+ export async function redeemIfNeeded() {
66
+ const token = pick(process.env["WB_BIND_TOKEN"]);
67
+ const base = pick(process.env["WB_PROXY_BASE_URL"]).replace(/\/+$/, "");
68
+ if (!token)
69
+ return { status: "skipped", reason: "no-token" };
70
+ if (!base)
71
+ return { status: "skipped", reason: "no-base" };
72
+ const path = defaultBindingPath();
73
+ // 本机已有同一地址的绑定:兑换失败时可以沿用它,不必让用户因为一个过期码连不上
74
+ const hasExisting = existsSync(path) && boundToSameProxy(path, base);
75
+ const fallback = (reason) => hasExisting ? { status: "skipped", reason: "already-bound" } : { status: "failed", reason };
76
+ let lastReason = "绑定码无效";
77
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) {
78
+ let response;
79
+ try {
80
+ response = await fetch(`${base}/bind/poll`, {
81
+ method: "POST",
82
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
83
+ body: JSON.stringify({ poll_token: token }),
84
+ signal: AbortSignal.timeout(20_000),
85
+ });
86
+ }
87
+ catch (err) {
88
+ return {
89
+ status: "failed",
90
+ reason: `连不上 ${base}:${err instanceof Error ? err.message : String(err)}`,
91
+ };
92
+ }
93
+ const text = await response.text();
94
+ let payload;
95
+ try {
96
+ payload = text ? JSON.parse(text) : {};
97
+ }
98
+ catch {
99
+ return { status: "failed", reason: `返回了非 JSON 内容(HTTP ${response.status})` };
100
+ }
101
+ if (!response.ok) {
102
+ // 409 = 码已被用掉(换机器重装、或者上次已兑换成功但文件被删)
103
+ if (response.status === 409) {
104
+ return fallback("绑定码已被使用过,请在网页重新获取一个");
105
+ }
106
+ return { status: "failed", reason: pick(payload.message) || `HTTP ${response.status}` };
107
+ }
108
+ if (payload.status === "APPROVED") {
109
+ if (!pick(payload.secret) || !pick(payload.key_id)) {
110
+ return fallback("返回结果缺少密钥,请重新绑定");
111
+ }
112
+ try {
113
+ return { status: "ok", tenants: persist(path, payload, base) };
114
+ }
115
+ catch (err) {
116
+ // 写不进 home(只读、磁盘满、权限被改)也只报原因:进程必须起得来
117
+ return {
118
+ status: "failed",
119
+ reason: `密钥写入失败(${path}):${err instanceof Error ? err.message : String(err)}`,
120
+ };
121
+ }
122
+ }
123
+ if (payload.status === "EXPIRED") {
124
+ return fallback("绑定码已过期,请在网页重新获取一个");
125
+ }
126
+ lastReason = pick(payload.message) || "网页那边还没提交完成";
127
+ await sleep(RETRY_INTERVAL_MS);
128
+ }
129
+ return fallback(lastReason);
130
+ }
@@ -0,0 +1,246 @@
1
+ /**
2
+ * P1 复合编排工具:一次调用内部打多个白名单接口。
3
+ *
4
+ * 为什么需要复合工具:用户问的是「上周业绩怎么样」,不是「调哪个接口」。
5
+ * 把「选接口 + 拼参数 + 合并口径」留给模型,它会在多轮里试错,
6
+ * 既慢又容易把不同区间的数字混在一起算。
7
+ *
8
+ * 🔴 复合工具的每个子请求都必须落在白名单内、都走同一套签名与净化;
9
+ * 它们不是「绕过白名单的后门」,只是把多个合法请求编排到一次工具调用里。
10
+ */
11
+ import { z } from "zod";
12
+ import { localError, ProxyError } from "../client/errors.js";
13
+ import { normalizePage, unwrapSems } from "./payload.js";
14
+ import { wrap } from "./runner.js";
15
+ import { DATE_FIELD_DESC, toQuery } from "./schemas.js";
16
+ const SOLD_RANGE = {
17
+ beginField: "soldTimeBegin",
18
+ endField: "soldTimeEnd",
19
+ desc: "销售日期",
20
+ };
21
+ /** dashboard 的视图名。逐个来自 `DashboardController` 的 `@GetMapping`,且都必须带 `dateRange`。 */
22
+ const DASHBOARD_VIEWS = [
23
+ "monthly-trend",
24
+ "funds-overview",
25
+ "business-overview",
26
+ "monthly-income-expense",
27
+ "salesman-ranking",
28
+ "completion-rate-distribution",
29
+ "tech-support",
30
+ "monthly-tech-support",
31
+ ];
32
+ /** dashboard 的时间范围是枚举字符串,不是日期——传日期会解析成 null 并算出一个空区间。 */
33
+ const DASHBOARD_RANGES = ["year", "quarter", "month", "week", "last30days"];
34
+ const STAT_TYPES = ["sales", "purchase", "inventory", "contract", "dashboard"];
35
+ function asRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value)
37
+ ? value
38
+ : {};
39
+ }
40
+ /** 取本周一 00:00:00(本地时区)。周报口径按自然周,不按「最近 7 天」。 */
41
+ function mondayOf(date) {
42
+ const d = new Date(date.getFullYear(), date.getMonth(), date.getDate());
43
+ // getDay(): 周日=0,需要折算成「距本周一的天数」
44
+ const offset = (d.getDay() + 6) % 7;
45
+ d.setDate(d.getDate() - offset);
46
+ const mm = String(d.getMonth() + 1).padStart(2, "0");
47
+ const dd = String(d.getDate()).padStart(2, "0");
48
+ return `${d.getFullYear()}-${mm}-${dd}`;
49
+ }
50
+ function addDays(day, delta) {
51
+ const [y, m, d] = day.split("-").map(Number);
52
+ const date = new Date(y, m - 1, d + delta);
53
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
54
+ const dd = String(date.getDate()).padStart(2, "0");
55
+ return `${date.getFullYear()}-${mm}-${dd}`;
56
+ }
57
+ /**
58
+ * 并发取多个接口。任何一个失败都让整次工具调用失败 ——
59
+ * 半份数据比没有数据更危险:模型会把「缺了一半的报表」当成完整结论来说。
60
+ */
61
+ async function gather(client, requests) {
62
+ const settled = await Promise.allSettled(requests.map((r) => client.call(r.call)));
63
+ const out = {};
64
+ const failures = [];
65
+ settled.forEach((result, i) => {
66
+ const req = requests[i];
67
+ if (result.status === "fulfilled") {
68
+ out[req.label] = { path: req.call.path, data: unwrapSems(result.value.data) };
69
+ return;
70
+ }
71
+ const err = result.reason;
72
+ if (err instanceof ProxyError) {
73
+ failures.push(`${req.label}(${req.call.path}):${err.message}`);
74
+ }
75
+ else {
76
+ failures.push(`${req.label}(${req.call.path}):${err instanceof Error ? err.message : String(err)}`);
77
+ }
78
+ });
79
+ if (failures.length > 0) {
80
+ throw localError("UPSTREAM_ERROR", `聚合查询失败,未返回任何数据:${failures.join(";")}`);
81
+ }
82
+ return out;
83
+ }
84
+ export function registerComposite(server, ctx) {
85
+ server.registerTool("sems_stat", {
86
+ title: "统计报表入口",
87
+ description: "统一统计入口。type 取值:\n"
88
+ + "· sales — 销售汇总(金额/成本/利润,成本利润字段受权限控制)\n"
89
+ + "· purchase — 采购汇总\n"
90
+ + "· inventory — 库存汇总(金额、总量、可用量、待出库量)\n"
91
+ + "· contract — 合同按类型分布 + 月度趋势(需要 year)\n"
92
+ + "· dashboard — 公司经营看板,需再指定 dashboardView 与 dashboardRange\n"
93
+ + "每类统计的字段口径不同,返回值里会带上实际调用的接口与区间,回答时请说明口径。",
94
+ inputSchema: {
95
+ type: z.enum(STAT_TYPES).describe("统计类型"),
96
+ soldTimeBegin: z.string().optional().describe(`销售日期起(${DATE_FIELD_DESC}),sales 用`),
97
+ soldTimeEnd: z.string().optional().describe(`销售日期止(${DATE_FIELD_DESC}),sales 用`),
98
+ orderTimeBegin: z.string().optional().describe(`订单日期起(${DATE_FIELD_DESC}),purchase 用`),
99
+ orderTimeEnd: z.string().optional().describe(`订单日期止(${DATE_FIELD_DESC}),purchase 用`),
100
+ storageType: z.coerce
101
+ .number()
102
+ .int()
103
+ .min(1)
104
+ .max(2)
105
+ .optional()
106
+ .describe("库存类型:1=常规 2=临时,inventory 用"),
107
+ includingEmpty: z
108
+ .boolean()
109
+ .optional()
110
+ .describe("是否把可用量为 0 的条目计入库存金额,inventory 用,默认 false"),
111
+ year: z.coerce.number().int().min(2000).max(2100).optional().describe("年份,contract 用,默认今年"),
112
+ dashboardView: z.enum(DASHBOARD_VIEWS).optional().describe("看板视图,dashboard 用"),
113
+ dashboardRange: z
114
+ .enum(DASHBOARD_RANGES)
115
+ .optional()
116
+ .describe("看板时间粒度(year/quarter/month/week/last30days),dashboard 用,默认 month"),
117
+ },
118
+ annotations: { readOnlyHint: true },
119
+ }, wrap(ctx, "sems_stat", async (args) => {
120
+ const type = String(args["type"] ?? "");
121
+ if (type === "sales") {
122
+ const query = toQuery({ soldTimeBegin: args["soldTimeBegin"], soldTimeEnd: args["soldTimeEnd"] }, SOLD_RANGE);
123
+ const result = await ctx.client.call({ method: "GET", path: "/invoicing/sale/stat", query });
124
+ return { type, path: "/invoicing/sale/stat", range: query, data: unwrapSems(result.data) };
125
+ }
126
+ if (type === "purchase") {
127
+ const query = toQuery({ orderTimeBegin: args["orderTimeBegin"], orderTimeEnd: args["orderTimeEnd"] }, { beginField: "orderTimeBegin", endField: "orderTimeEnd", desc: "订单日期" });
128
+ const result = await ctx.client.call({ method: "GET", path: "/invoicing/order-form/stat", query });
129
+ return { type, path: "/invoicing/order-form/stat", range: query, data: unwrapSems(result.data) };
130
+ }
131
+ if (type === "inventory") {
132
+ const query = toQuery({ storageType: args["storageType"], includingEmpty: args["includingEmpty"] }, undefined);
133
+ const result = await ctx.client.call({
134
+ method: "GET",
135
+ path: "/invoicing/storage-manage-record/stat",
136
+ query,
137
+ });
138
+ return {
139
+ type,
140
+ path: "/invoicing/storage-manage-record/stat",
141
+ range: query,
142
+ data: unwrapSems(result.data),
143
+ note: "amount 是「(可用量+待出库量)×单价」的合计。单价字段受「库存-查看成本」权限控制,"
144
+ + "无权限时金额相关字段会被服务端删除。",
145
+ };
146
+ }
147
+ if (type === "contract") {
148
+ const year = typeof args["year"] === "number" ? args["year"] : new Date().getFullYear();
149
+ const data = await gather(ctx.client, [
150
+ { label: "byType", call: { method: "GET", path: `/invoicing/contract/stat/type/${year}` } },
151
+ {
152
+ label: "monthlyTrend",
153
+ call: { method: "GET", path: `/invoicing/contract/stat/monthly-trend/${year}` },
154
+ },
155
+ ]);
156
+ return { type, year, ...data };
157
+ }
158
+ if (type === "dashboard") {
159
+ const view = args["dashboardView"];
160
+ if (typeof view !== "string") {
161
+ throw localError("PARAM_INVALID", `type=dashboard 时必须指定 dashboardView,可选值:${DASHBOARD_VIEWS.join(" / ")}`);
162
+ }
163
+ const range = typeof args["dashboardRange"] === "string" ? args["dashboardRange"] : "month";
164
+ const result = await ctx.client.call({
165
+ method: "GET",
166
+ path: `/invoicing/dashboard/stat/${view}`,
167
+ query: { dateRange: range },
168
+ });
169
+ return {
170
+ type,
171
+ view,
172
+ range,
173
+ path: `/invoicing/dashboard/stat/${view}`,
174
+ data: unwrapSems(result.data),
175
+ note: "看板各视图有各自的功能权限,无权限时海竣信息系统会返回缺少的具体权限名。",
176
+ };
177
+ }
178
+ // zod 的 enum 已经在 schema 层拦住了非法值,走到这里说明代码不一致
179
+ throw localError("PARAM_INVALID", `不支持的统计类型:${type}`);
180
+ }));
181
+ server.registerTool("sems_weekly_report_data", {
182
+ title: "周报数据聚合",
183
+ description: "按自然周(周一到周日)汇总周报素材:本周工作日志 + 本周销售统计。"
184
+ + "不传 weekStart 时取本周一。返回里会标明实际区间与数据缺口,写周报时请照实说明缺口。",
185
+ inputSchema: {
186
+ weekStart: z
187
+ .string()
188
+ .optional()
189
+ .describe("周起始日(YYYY-MM-DD,应为周一)。不传则取当前自然周的周一"),
190
+ },
191
+ annotations: { readOnlyHint: true },
192
+ }, wrap(ctx, "sems_weekly_report_data", async (args) => {
193
+ const raw = args["weekStart"];
194
+ const start = (typeof raw === "string" ? raw.trim() : "") || mondayOf(new Date());
195
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(start)) {
196
+ throw localError("PARAM_INVALID", `weekStart 需要 YYYY-MM-DD 格式,收到「${start}」`);
197
+ }
198
+ const end = addDays(start, 6);
199
+ // 工作日志接口**没有可靠的日期过滤参数**,只能取一页后按 createTime 自行过滤。
200
+ // 取 100 条是白名单允许的上限;日志量大的账号可能不够,所以结果里如实标注。
201
+ const DAILY_PAGE_SIZE = 100;
202
+ const data = await gather(ctx.client, [
203
+ {
204
+ label: "dailyReports",
205
+ call: {
206
+ method: "GET",
207
+ path: "/synergy/daily-report/page",
208
+ query: { current: 1, size: DAILY_PAGE_SIZE },
209
+ },
210
+ },
211
+ {
212
+ label: "salesStat",
213
+ call: {
214
+ method: "GET",
215
+ path: "/invoicing/sale/stat",
216
+ query: { soldTimeBegin: `${start} 00:00:00`, soldTimeEnd: `${end} 23:59:59` },
217
+ },
218
+ },
219
+ ]);
220
+ const page = asRecord(normalizePage({ data: data["dailyReports"]?.data }));
221
+ const records = Array.isArray(page["records"]) ? page["records"] : [];
222
+ const inWeek = records.filter((item) => {
223
+ const created = asRecord(item)["createTime"];
224
+ if (typeof created !== "string" || created.length < 10)
225
+ return false;
226
+ const day = created.slice(0, 10);
227
+ return day >= start && day <= end;
228
+ });
229
+ const total = page["total"];
230
+ return {
231
+ range: { start, end },
232
+ dailyReports: {
233
+ total: total,
234
+ scanned: records.length,
235
+ inWeek: inWeek.length,
236
+ records: inWeek,
237
+ caveat: typeof total === "number" && total > records.length
238
+ ? `工作日志共 ${total} 条,本次只扫描了最近 ${records.length} 条,`
239
+ + "更早的本周日志可能未被包含 —— 如果本周日志不多则不影响。"
240
+ : undefined,
241
+ },
242
+ salesStat: data["salesStat"]?.data,
243
+ note: "销售统计的区间是「销售日期」落在本周内,不是「本周录入」。两者口径不同,别混着说。",
244
+ };
245
+ }));
246
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 工具上下文与清单查找。
3
+ *
4
+ * 工具元数据(tier / 权限码 / 描述)不在各工具文件里重复声明,统一从生成物
5
+ * `generated/manifest.ts` 查——那份文件的真源是 `configs/tools.yaml`。
6
+ * 这样「工具清单」只有一处可改,不会出现「yaml 改了、工具里还留着旧权限码」。
7
+ */
8
+ import { TOOLS } from "../generated/manifest.js";
9
+ const TOOL_MAP = new Map(TOOLS.map((t) => [t.name, t]));
10
+ /** 取工具定义。名字写错在这里就会炸,而不是静默地「不加权限预检」。 */
11
+ export function specOf(name) {
12
+ const spec = TOOL_MAP.get(name);
13
+ if (!spec) {
14
+ throw new Error(`工具 ${name} 未在 configs/tools.yaml 中登记(请先重跑 gen_mcp_manifest.py)`);
15
+ }
16
+ return spec;
17
+ }