@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,226 @@
1
+ /**
2
+ * P0 身份工具:我是谁 / 我能做什么。
3
+ *
4
+ * 这两个工具是「模型的自检入口」:回答业务问题前先调 `sems_capabilities`,
5
+ * 就能知道该不该说「你没有权限」,而不是硬查一遍再被 403 打回。
6
+ *
7
+ * 🔴 两者都不透传上游原始响应。`GET /admin/user/info` 返回的是 `{sysUser, userVO, roles, permissions}`,
8
+ * 其中 **`SysUser.password` 与 `UserVO.password/salt` 都没有 @JsonIgnore**
9
+ * (只有 `SysUser.salt` 有),因此密码哈希会原样出现在响应里。
10
+ * proxy 侧的 `always_drop` 已在任意层级剪掉,但这里仍然只挑白名单字段输出 ——
11
+ * 两层各自独立成立,任何一层被改坏都不至于泄漏。
12
+ */
13
+ import { z } from "zod";
14
+ import { persistActiveTenant } from "../config.js";
15
+ import { PERMISSIONS } from "../generated/manifest.js";
16
+ import { extractPermissions } from "../permission-guard.js";
17
+ import { wrap } from "./runner.js";
18
+ function asRecord(value) {
19
+ return typeof value === "object" && value !== null && !Array.isArray(value)
20
+ ? value
21
+ : {};
22
+ }
23
+ /** 按白名单取值:上游字段名 → 输出字段名。未列出的字段(如 password)不会被读到。 */
24
+ function pick(source, mapping) {
25
+ const record = asRecord(source);
26
+ const out = {};
27
+ for (const [from, to] of mapping) {
28
+ const value = record[from];
29
+ if (value !== undefined && value !== null && value !== "")
30
+ out[to] = value;
31
+ }
32
+ return out;
33
+ }
34
+ const USER_FIELDS = [
35
+ ["userId", "userId"],
36
+ ["username", "username"],
37
+ ["name", "name"],
38
+ ["nickname", "nickname"],
39
+ ["phone", "phone"],
40
+ ["email", "email"],
41
+ ];
42
+ const TENANT_FIELDS = [
43
+ ["tenantId", "tenantId"],
44
+ ["deptId", "deptId"],
45
+ ["deptName", "deptName"],
46
+ ["position", "position"],
47
+ ];
48
+ /** `userVO.roleList` 是 `SysRole[]`,只要角色名。 */
49
+ function roleNames(value) {
50
+ if (!Array.isArray(value))
51
+ return [];
52
+ return value
53
+ .map((item) => asRecord(item)["roleName"])
54
+ .filter((name) => typeof name === "string" && name.length > 0);
55
+ }
56
+ export function registerIdentity(server, ctx) {
57
+ server.registerTool("sems_whoami", {
58
+ title: "当前绑定的海竣信息系统用户与租户",
59
+ description: "返回当前 WorkBuddy 绑定的海竣信息系统账号是谁:用户名、姓名、所属租户与部门、角色。"
60
+ + "回答「我的数据」「我们公司」这类问题前先调这个,避免把别家租户的数据当成用户的。",
61
+ inputSchema: {},
62
+ annotations: { readOnlyHint: true },
63
+ }, wrap(ctx, "sems_whoami", async () => {
64
+ const payload = await ctx.client.call({ method: "GET", path: "/admin/user/info" });
65
+ const data = asRecord(asRecord(payload.data)["data"]);
66
+ const sysUser = asRecord(data["sysUser"]);
67
+ const userVO = asRecord(data["userVO"]);
68
+ // 真实 SEMS 的 `findUserInfo()` 同时给 sysUser 与 userVO;但两者字段名一致,
69
+ // 且某些实现/桩只给其中之一。所以取「有内容的那个」,不写两套取值逻辑。
70
+ const identity = Object.keys(sysUser).length > 0 ? sysUser : userVO;
71
+ return {
72
+ user: pick(identity, USER_FIELDS),
73
+ tenant: pick(userVO, TENANT_FIELDS),
74
+ roles: roleNames(userVO["roleList"]),
75
+ // 直接从这次响应里数,不再为了一个数字多打一次 /admin/user/info
76
+ permissionCount: extractPermissions(payload.data).size,
77
+ note: "回答问题前请以这里的 tenantId 为准。同一台海竣信息系统上有多个租户,"
78
+ + "把别家租户的数据说成「你们的」属于严重错误。",
79
+ };
80
+ }));
81
+ server.registerTool("sems_capabilities", {
82
+ title: "我能做什么",
83
+ description: "列出当前账号可以使用的能力与对应中文权限名,同时列出「暂时不能做什么」以及缺哪个权限。"
84
+ + "用户问「为什么查不了销售利润」时用这个回答,不要猜。",
85
+ inputSchema: {
86
+ // 权限缓存 60s;用户刚被授权时会想立刻看到变化,所以留一个显式刷新开关。
87
+ refresh: z.boolean().optional().describe("传 true 强制重新拉取权限,忽略 60 秒缓存"),
88
+ },
89
+ annotations: { readOnlyHint: true },
90
+ }, wrap(ctx, "sems_capabilities", async (args) => {
91
+ const granted = await ctx.guard.load(args["refresh"] === true);
92
+ const allowed = [];
93
+ const missing = [];
94
+ for (const perm of PERMISSIONS) {
95
+ const item = { permission: perm.code, name: perm.name, covers: perm.covers };
96
+ (granted.has(perm.code) ? allowed : missing).push(item);
97
+ }
98
+ // 成本/利润类权限单独点出来:这是用户最常问「为什么看不到」的一类,
99
+ // 混在 20 多条权限里需要用户自己去比对,等于没回答。
100
+ const priceGaps = missing.filter((m) => /cost|profit|price|buy_price/.test(m.permission));
101
+ return {
102
+ allowed,
103
+ missing,
104
+ summary: `当前账号具备 ${allowed.length} 项功能权限,缺少 ${missing.length} 项。`,
105
+ priceVisibility: priceGaps.length === 0
106
+ ? "成本/利润类字段全部可见。"
107
+ : `以下成本/利润权限未开通,相关字段在返回结果里已被服务端删除(不是空值,是字段不存在):${priceGaps
108
+ .map((m) => `「${m.name}」`)
109
+ .join("、")}`,
110
+ note: "权限名与海竣信息系统角色配置页的勾选项一致。需要开通时把这些中文名给管理员;"
111
+ + "不要报权限码,海竣信息系统界面上看不到权限码。",
112
+ };
113
+ }));
114
+ server.registerTool("sems_list_tenants", {
115
+ title: "这把密钥绑定了哪几家公司",
116
+ description: "列出当前绑定可以进入的公司,并标出正在使用哪一家。"
117
+ + "用户问「我有几家公司」「现在查的是哪家」「怎么切到另一家」时用这个回答。",
118
+ inputSchema: {},
119
+ annotations: { readOnlyHint: true },
120
+ }, wrap(ctx, "sems_list_tenants", async () => {
121
+ const companies = await loadTenants(ctx);
122
+ const active = ctx.config.activeTenant;
123
+ const usable = companies.filter((item) => isActive(item));
124
+ const broken = companies.filter((item) => !isActive(item));
125
+ const current = active || usable.find((item) => item.isDefault)?.tenantId || null;
126
+ return {
127
+ companies,
128
+ current,
129
+ ...(broken.length > 0
130
+ ? {
131
+ unavailable: broken.map((item) => ({
132
+ tenantId: item.tenantId,
133
+ name: item.name,
134
+ status: item.status,
135
+ hint: "这家公司的身份已失效,切过去会一直报需要重绑;请重新绑定",
136
+ })),
137
+ }
138
+ : {}),
139
+ note: active === ""
140
+ ? "当前未指定公司,用的是绑定时选中的默认公司。"
141
+ : "当前指定了具体公司;切换用 sems_switch_tenant。",
142
+ };
143
+ }));
144
+ server.registerTool("sems_switch_tenant", {
145
+ title: "切换当前使用的公司",
146
+ description: "把后续查询切到另一家已绑定的公司(同一把密钥可绑多家)。"
147
+ + "传 default 表示回到绑定时选中的默认公司。切换只影响之后的调用,不会重绑、不需要密码。",
148
+ inputSchema: {
149
+ tenantId: z
150
+ .string()
151
+ .describe("要切换到的公司 tenantId(用 sems_list_tenants 查),传 default 回到默认公司"),
152
+ },
153
+ // 它会写本机 binding.json 并改进程内的 activeTenant,不是只读操作。
154
+ // 标成 readOnly 会让宿主放心地并发或缓存调用,切换结果就不可预测。
155
+ annotations: { readOnlyHint: false },
156
+ }, wrap(ctx, "sems_switch_tenant", async (args) => {
157
+ const wanted = String(args["tenantId"] ?? "").trim();
158
+ if (!wanted)
159
+ throw new Error("请提供 tenantId;如需回到默认公司请传 default");
160
+ if (wanted.toLowerCase() === "default") {
161
+ ctx.config.activeTenant = "";
162
+ const persisted = persistActiveTenant("");
163
+ ctx.guard.invalidate();
164
+ // 部门/经办人随公司变化,档案缓存必须一起清,否则 60 秒内会用旧公司的 deptId 起草
165
+ ctx.userProfile.invalidate();
166
+ return { ok: true, current: "default", persisted, message: "已切回默认公司。" };
167
+ }
168
+ // 以 proxy 的列表为准:本地文件里的公司可能已经被别处重绑作废
169
+ const companies = await loadTenants(ctx);
170
+ const hit = companies.find((item) => item.tenantId === wanted);
171
+ if (!hit) {
172
+ return {
173
+ ok: false,
174
+ message: `没有已绑定的公司 ${wanted}。可选:${companies
175
+ .filter((c) => isActive(c))
176
+ .map((c) => `${c.name}(${c.tenantId})`)
177
+ .join("、") || "(无)"}`,
178
+ };
179
+ }
180
+ // 切到已失效的身份不会立刻报错,而是此后每次调用都 401 ——
181
+ // 那种「能切、但什么都查不了」的体验比直接拒绝更难解释。
182
+ if (!isActive(hit)) {
183
+ return {
184
+ ok: false,
185
+ message: `「${hit.name}」这条身份已失效(状态 ${hit.status ?? "未知"}),`
186
+ + "切过去之后所有查询都会失败。请先在 WorkBuddy 重新绑定这家公司。",
187
+ };
188
+ }
189
+ ctx.config.activeTenant = hit.tenantId;
190
+ const persisted = persistActiveTenant(hit.tenantId);
191
+ // 换公司等于换令牌,权限集合与用户档案(deptId / handlerId)也随之不同,缓存都要作废
192
+ ctx.guard.invalidate();
193
+ ctx.userProfile.invalidate();
194
+ return {
195
+ ok: true,
196
+ current: hit.tenantId,
197
+ name: hit.name,
198
+ persisted,
199
+ message: persisted
200
+ ? `已切换到「${hit.name}」,后续查询都按这家公司。`
201
+ : `已切换到「${hit.name}」(本次会话生效;绑定文件不可写,重启后会回到默认公司)。`,
202
+ };
203
+ }));
204
+ }
205
+ /** 只有 ACTIVE(或 proxy 没给状态的老版本)才算能用。 */
206
+ function isActive(item) {
207
+ return item.status === undefined || item.status === "ACTIVE";
208
+ }
209
+ /** 从 proxy 取公司列表。本地 binding.json 里的列表会过期,权威来源只有 proxy。 */
210
+ async function loadTenants(ctx) {
211
+ const payload = await ctx.client.call({ method: "GET", path: "/identities" });
212
+ const data = asRecord(payload.data);
213
+ const list = data["identities"];
214
+ if (!Array.isArray(list))
215
+ return [];
216
+ return list.map((item) => {
217
+ const record = asRecord(item);
218
+ return {
219
+ tenantId: String(record["tenantId"] ?? ""),
220
+ name: String(record["name"] ?? record["username"] ?? "未命名企业"),
221
+ ...(record["isDefault"] === true ? { isDefault: true } : {}),
222
+ ...(typeof record["status"] === "string" ? { status: record["status"] } : {}),
223
+ };
224
+ });
225
+ }
226
+ //# sourceMappingURL=identity.js.map