@teamdream/sems-mcp 1.1.2 → 1.1.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.
@@ -5,15 +5,30 @@
5
5
  * (「配置服务器时…」「起草合同时…」),由模型判断何时应用,新增场景无需改代码。
6
6
  * 规则只按 tenantId 隔离,proxy 已按「这把密钥能进哪些公司」裁剪过可见范围。
7
7
  */
8
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, join } from "node:path";
8
11
  import { log } from "./logger.js";
9
12
  export const AGENT_RULES_PATH = "/agent-rules";
10
13
  /** 60 秒:管理员改完规则不必等客户端重连,又不至于每次工具调用都打一次 proxy。 */
11
14
  const REFRESH_TTL_MS = 60_000;
15
+ /**
16
+ * 规则快照落盘,与 binding.json 同目录。
17
+ *
18
+ * 目的不是替代 proxy:每次启动仍先向 proxy 拉最新规则,落盘只在「拉不到」时兜底,
19
+ * 让工具描述与首次工具调用都有规则。文件权限 0600;内容是不含密钥的纯文本规则。
20
+ */
21
+ export function defaultRulesCachePath() {
22
+ return process.env["WB_AGENT_RULES_FILE"] || join(homedir(), ".sems-mcp", "agent-rules.json");
23
+ }
12
24
  /** 所有工具共用同一个注入点,未配置/拉不到时返回 null,不改变原有返回结构。 */
13
25
  export const NULL_RULE_SOURCE = {
14
26
  async forTenant() {
15
27
  return null;
16
28
  },
29
+ snapshotText() {
30
+ return "";
31
+ },
17
32
  };
18
33
  function asRecord(value) {
19
34
  return typeof value === "object" && value !== null && !Array.isArray(value)
@@ -68,17 +83,47 @@ function renderRevocation(tenantId) {
68
83
  "该公司的操作改按工具描述里的默认口径处理;其它公司的规则不受影响。",
69
84
  ].join("\n");
70
85
  }
86
+ function renderCompactRule(tenantId, rule) {
87
+ // 这里要复制到 29 个工具的 description 里,每条只保留 tenantId 与版本,样板行一律省掉。
88
+ return [`【tenantId ${tenantId}|版本 ${rule.updatedAt}】`, rule.text].join("\n");
89
+ }
90
+ /**
91
+ * 把快照里所有规则拼成一段精简文本,注册工具时加到 description 末尾。
92
+ *
93
+ * 与响应侧注入的区别:这里是「会话开始前就进上下文」,解决第一发工具调用不带规则的问题。
94
+ * 不用 initialize 的 instructions:WorkBuddy 客户端只把它存进客户端对象,没有拼进模型上下文,
95
+ * tools/list 里的 description 才是调用前唯一可见的通道。为控制体积,这里用紧凑格式。
96
+ * 每条自带 tenantId 限定,模型按当前操作的公司选用,不按字典序挑。
97
+ */
98
+ export function renderSnapshotText(snapshot) {
99
+ if (snapshot.rules.size === 0)
100
+ return "";
101
+ const blocks = [...snapshot.rules.entries()]
102
+ .sort(([a], [b]) => a.localeCompare(b))
103
+ .map(([tenantId, rule]) => renderCompactRule(tenantId, rule));
104
+ return [
105
+ "【内置公司规则|海竣管理员按公司配置,调用工具前先读】",
106
+ "以下规则按 tenantId 划分,只适用于它写明的公司;操作哪家公司就用哪条,别家的忽略。"
107
+ + "同一公司若有多条,只执行版本号最大的一条。",
108
+ ...blocks,
109
+ ].join("\n");
110
+ }
71
111
  export class RuleBook {
72
112
  client;
73
113
  ttlMs;
114
+ keyId;
115
+ cachePath;
74
116
  snapshot = { rules: new Map(), defaultTenantId: "" };
75
117
  lastFetchAt = 0;
76
118
  inflight = null;
77
119
  /** 已下发过规则的租户 → 版本号;按公司去重,同时用于判断是否需要下发撤销。 */
78
120
  injectedVersions = new Map();
79
- constructor(client, ttlMs = REFRESH_TTL_MS) {
121
+ constructor(client, ttlMs = REFRESH_TTL_MS, keyId = "", cachePath = defaultRulesCachePath()) {
80
122
  this.client = client;
81
123
  this.ttlMs = ttlMs;
124
+ this.keyId = keyId;
125
+ this.cachePath = cachePath;
126
+ this.loadCache();
82
127
  }
83
128
  /** 启动时调一次;失败沿用上次成功快照,不能因此把在用的规则误判成撤销。 */
84
129
  async refresh() {
@@ -89,6 +134,7 @@ export class RuleBook {
89
134
  timeoutMs: 5_000,
90
135
  });
91
136
  this.snapshot = parseSnapshot(result.data);
137
+ this.saveCache();
92
138
  }
93
139
  catch (err) {
94
140
  // 老 proxy 没有这个端点时会被 catch-all 判成 NOT_IN_ALLOWLIST,属预期降级。
@@ -98,6 +144,49 @@ export class RuleBook {
98
144
  }
99
145
  this.lastFetchAt = Date.now();
100
146
  }
147
+ /**
148
+ * 全部可见公司的规则文本,注册工具时取一次(description 注册后是静态的)。
149
+ *
150
+ * 这里刻意不把版本登记为「已注入」:客户端可能截断过长的 description,
151
+ * 首次工具调用仍要再带一次(落在返回值里,影响下一发的参数构造)。
152
+ */
153
+ snapshotText() {
154
+ return renderSnapshotText(this.snapshot);
155
+ }
156
+ /** 读上次成功拉取的规则:proxy 暂时拉不到时,工具描述和首次工具调用仍有内容。 */
157
+ loadCache() {
158
+ try {
159
+ const doc = JSON.parse(readFileSync(this.cachePath, "utf8"));
160
+ if (this.keyId && doc.keyId && doc.keyId !== this.keyId) {
161
+ log.warn("内置规则缓存属于其它绑定,忽略");
162
+ return;
163
+ }
164
+ this.snapshot = parseSnapshot({ rules: doc.rules, defaultTenantId: doc.defaultTenantId });
165
+ }
166
+ catch (err) {
167
+ const code = err.code;
168
+ if (code !== "ENOENT") {
169
+ const reason = err instanceof Error ? err.message : String(err);
170
+ log.warn("内置规则缓存读取失败,按无缓存启动", { reason });
171
+ }
172
+ }
173
+ }
174
+ /** 写盘失败不能影响工具调用:规则仍在内存里,只是这次没留下兜底。 */
175
+ saveCache() {
176
+ try {
177
+ mkdirSync(dirname(this.cachePath), { recursive: true, mode: 0o700 });
178
+ const doc = {
179
+ keyId: this.keyId,
180
+ defaultTenantId: this.snapshot.defaultTenantId,
181
+ rules: Object.fromEntries([...this.snapshot.rules].map(([tenantId, rule]) => [tenantId, { text: rule.text, updatedAt: rule.updatedAt }])),
182
+ };
183
+ writeFileSync(this.cachePath, `${JSON.stringify(doc, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
184
+ }
185
+ catch (err) {
186
+ const reason = err instanceof Error ? err.message : String(err);
187
+ log.warn("内置规则缓存写入失败", { reason });
188
+ }
189
+ }
101
190
  async forTenant(activeTenant) {
102
191
  await this.maybeRefresh();
103
192
  // activeTenant 为空时 proxy 用的是绑定里的默认公司,规则也必须落到那一家。
@@ -124,3 +213,19 @@ export class RuleBook {
124
213
  await this.inflight;
125
214
  }
126
215
  }
216
+ /**
217
+ * 把启动规则快照写进所有工具的 description —— 模型拿到 tools/list 时就能读到,第一发调用即生效。
218
+ *
219
+ * WorkBuddy 只把 initialize 的 instructions 存进客户端对象,没有拼进模型上下文(已核对 app.asar),
220
+ * 所以 description 是调用前唯一可见的通道。包装 registerTool 而不是逐个工具改:
221
+ * 工具散在 5 个 register 文件里,逐个改既容易漏、新增工具时又会重新踩坑。
222
+ * suffix 为空(未配置规则 / 拉取失败且无缓存)时原样透传,不改变任何工具描述。
223
+ */
224
+ export function withRuleDescriptions(server, suffix) {
225
+ if (!suffix)
226
+ return server;
227
+ const original = server.registerTool.bind(server);
228
+ const wrapped = ((name, config, cb) => original(name, { ...config, description: `${config.description ?? ""}\n\n${suffix}` }, cb));
229
+ server.registerTool = wrapped;
230
+ return server;
231
+ }
package/dist/main.js CHANGED
@@ -14,7 +14,7 @@
14
14
  import { readFileSync } from "node:fs";
15
15
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
16
16
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
17
- import { RuleBook } from "./agent-rules.js";
17
+ import { RuleBook, withRuleDescriptions } from "./agent-rules.js";
18
18
  import { fetchHealth, ProxyClient } from "./client/proxy.js";
19
19
  import { loadConfig } from "./config.js";
20
20
  import { DraftStore } from "./drafts/store.js";
@@ -38,6 +38,9 @@ const SERVER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import
38
38
  * 所以这里只写「怎么选路」和「写操作怎么收口」两件事——业务细节留在工具描述里,
39
39
  * 免得每次连接都往上下文塞一大段会过期的口径。
40
40
  *
41
+ * 管理员配置的按公司规则不写在这里:WorkBuddy 客户端不消费 initialize 的 instructions,
42
+ * 规则随工具注册拼进 description(见 withRuleDescriptions)。
43
+ *
41
44
  * 客户端不读这个字段也不影响功能(协议里是可选项),读了能少走弯路。
42
45
  */
43
46
  const SERVER_INSTRUCTIONS = [
@@ -131,9 +134,13 @@ async function main() {
131
134
  const config = loaded.config;
132
135
  log.info(`配置来源:${config.source === "env" ? "环境变量" : `绑定文件(key_id ${config.keyId})`}`);
133
136
  const client = new ProxyClient(config);
134
- // 启动先拉一次:首个工具调用就能带上规则。拉不到按无规则继续,不阻断启动。
135
- const agentRules = new RuleBook(client);
137
+ // 启动先拉一次;拉不到时 RuleBook 会读本地缓存兜底,仍不阻断启动。
138
+ // keyId 让缓存按绑定隔离,换绑后不沿用旧公司的规则。
139
+ const agentRules = new RuleBook(client, undefined, config.keyId);
136
140
  await agentRules.refresh();
141
+ // 规则写进每个工具的 description:模型拿到 tools/list 时就读到,第一发调用即生效。
142
+ // 不能用 initialize 的 instructions —— WorkBuddy 客户端不把它喂给模型。
143
+ withRuleDescriptions(server, agentRules.snapshotText());
137
144
  const ctx = {
138
145
  client,
139
146
  // 权限预检与业务请求共用同一份签名密钥,没必要建两个 client
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teamdream/sems-mcp",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "description": "SEMS × WorkBuddy MCP 适配层(stdio,运行在用户电脑,不持有 SEMS 账号密码)",
5
5
  "license": "UNLICENSED",
6
6
  "author": "TeamDream",