@teamdream/sems-mcp 1.1.2 → 1.3.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.
- package/README.md +115 -101
- package/dist/agent-rules.js +107 -2
- package/dist/client/errors.js +9 -3
- package/dist/generated/manifest.js +10 -30
- package/dist/main.js +76 -61
- package/dist/tools/channel.js +212 -0
- package/dist/tools/context.js +10 -14
- package/dist/tools/{runner.js → respond.js} +8 -17
- package/package.json +1 -1
- package/dist/drafts/digest.js +0 -24
- package/dist/drafts/store.js +0 -105
- package/dist/permission-guard.js +0 -72
- package/dist/tools/composite.js +0 -246
- package/dist/tools/identity.js +0 -225
- package/dist/tools/orchestrate.js +0 -470
- package/dist/tools/payload.js +0 -52
- package/dist/tools/queries.js +0 -304
- package/dist/tools/schemas.js +0 -60
- package/dist/tools/writes.js +0 -1545
- package/dist/user-profile.js +0 -86
package/dist/main.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
/**
|
|
3
|
-
* sems-mcp 进程入口:stdio 传输层 +
|
|
3
|
+
* sems-mcp 进程入口:stdio 传输层 + 5 个通道工具注册。
|
|
4
4
|
*
|
|
5
5
|
* 🔴 三条硬约束,每条踩了都表现为「连接器不正常」而报错现场不在这里:
|
|
6
6
|
*
|
|
@@ -10,103 +10,116 @@
|
|
|
10
10
|
* WorkBuddy 认为连接器崩溃。
|
|
11
11
|
* 3. **未绑定不能让进程崩**。起不来 → 连工具列表都没有 → 用户无从自助。
|
|
12
12
|
* 正确做法是照常暴露工具,调用时统一返回「请先绑定」。
|
|
13
|
+
*
|
|
14
|
+
* 🔴 这个进程里**没有业务逻辑**:能力清单、参数校验、body 构造、草稿状态机、
|
|
15
|
+
* 权限判定、错误解释全在 sems-proxy。所以新增业务能力不需要发 npm 包——
|
|
16
|
+
* 改 proxy 的能力注册表即可,这里长期不动。
|
|
13
17
|
*/
|
|
14
18
|
import { readFileSync } from "node:fs";
|
|
15
19
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
16
20
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
17
|
-
import { RuleBook } from "./agent-rules.js";
|
|
21
|
+
import { RuleBook, withRuleDescriptions } from "./agent-rules.js";
|
|
18
22
|
import { fetchHealth, ProxyClient } from "./client/proxy.js";
|
|
19
|
-
import { loadConfig } from "./config.js";
|
|
20
|
-
import { DraftStore } from "./drafts/store.js";
|
|
23
|
+
import { loadConfig, persistActiveTenant } from "./config.js";
|
|
21
24
|
import { CONTRACT_VERSION, TOOLS } from "./generated/manifest.js";
|
|
22
25
|
import { log, setLogLevel } from "./logger.js";
|
|
23
|
-
import { PermissionGuard } from "./permission-guard.js";
|
|
24
26
|
import { redeemIfNeeded } from "./redeem.js";
|
|
25
|
-
import {
|
|
26
|
-
import { registerIdentity } from "./tools/identity.js";
|
|
27
|
-
import { registerOrchestration } from "./tools/orchestrate.js";
|
|
28
|
-
import { registerQueries } from "./tools/queries.js";
|
|
29
|
-
import { registerWrites } from "./tools/writes.js";
|
|
30
|
-
import { UserProfileCache } from "./user-profile.js";
|
|
27
|
+
import { registerChannel } from "./tools/channel.js";
|
|
31
28
|
const SERVER_NAME = "sems";
|
|
32
29
|
/** 自报版本取自包清单,换版本号时无需改这里。 */
|
|
33
30
|
const SERVER_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
34
31
|
/**
|
|
35
32
|
* 随 initialize 下发的服务说明。
|
|
36
33
|
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* 免得每次连接都往上下文塞一大段会过期的口径。
|
|
34
|
+
* 只写「怎么选路」和「写操作怎么收口」两件事:能力细节由 sems_help 按当前账号
|
|
35
|
+
* 实时下发,不塞进这里——写在这里的内容一发版就固定了,会很快过期。
|
|
40
36
|
*
|
|
41
|
-
*
|
|
37
|
+
* 管理员配置的按公司规则不写在这里:WorkBuddy 客户端不消费 initialize 的 instructions,
|
|
38
|
+
* 规则随工具注册拼进 description(见 withRuleDescriptions)。
|
|
42
39
|
*/
|
|
43
40
|
const SERVER_INSTRUCTIONS = [
|
|
44
41
|
"这是海竣信息系统(SEMS,ERP)的连接器,工具全部以 sems_ 开头。",
|
|
45
42
|
"涉及销售单、采购单、报价单、合同、库存、商品、客户供应商、工作日志、经营统计的请求,一律使用 sems_* 工具,"
|
|
46
|
-
+ "
|
|
47
|
-
"
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
+ "调用前先向用户确认客户全称、合同类型、关联单据等关键字段。",
|
|
43
|
+
+ "不要用其它连接器的同类工具替代。",
|
|
44
|
+
"不确定能做什么时,先调 sems_help:它按当前账号的权限下发能力清单,含每个能力的参数名与用法。",
|
|
45
|
+
"查数据用 sems_call(name, args)。写操作分两段:先 sems_prepare 出草稿,把 summary 与 warnings 完整呈现给用户,"
|
|
46
|
+
+ "用户明确同意后再用 draftId 与 digest 调 sems_commit;用户要改任何一项就重新 prepare,不要改旧草稿。",
|
|
51
47
|
"单据编号只能来自返回值,回查不到就说让用户到系统里查看,不要自己编。",
|
|
52
48
|
"成本、利润、采购价等字段受账号权限控制,无权限时服务端已删除,不要当成数据缺失。",
|
|
53
49
|
].join("\n");
|
|
54
50
|
/** 未绑定时占位工具用的空 schema:占位不是为了能用,而是为了让用户看见「有这个工具」。 */
|
|
55
51
|
const EMPTY_SCHEMA = {};
|
|
56
52
|
/**
|
|
57
|
-
*
|
|
53
|
+
* 注册占位工具:全部工具名照常暴露,调用时统一返回同一条说明。
|
|
58
54
|
*
|
|
59
|
-
*
|
|
60
|
-
*
|
|
55
|
+
* 占位不是为了能用,而是为了让用户看见「有这个工具」:WorkBuddy 拿不到工具列表时
|
|
56
|
+
* 只显示一个空连接器,用户不知道是没配置、没绑定,还是服务坏了。
|
|
57
|
+
* 目前两个场景用它:尚未绑定、服务器端版本过旧。
|
|
61
58
|
*/
|
|
62
|
-
function
|
|
63
|
-
// 连接器把服务地址写死在 mcp.json 里,用户只需要一个绑定码,所以这里直接把完整网址给出来
|
|
64
|
-
const base = (process.env["WB_PROXY_BASE_URL"] ?? "").replace(/\/+$/, "");
|
|
65
|
-
const bindUrl = base ? `${base}/bind` : "「连接服务地址」+ /bind";
|
|
59
|
+
function registerPlaceholders(server, describe, text) {
|
|
66
60
|
for (const spec of TOOLS) {
|
|
67
61
|
server.registerTool(spec.name, {
|
|
68
62
|
title: spec.desc,
|
|
69
|
-
description: `⚠️
|
|
63
|
+
description: `⚠️ ${describe}`,
|
|
70
64
|
inputSchema: EMPTY_SCHEMA,
|
|
71
65
|
annotations: { readOnlyHint: !spec.write },
|
|
72
66
|
}, async () => ({
|
|
73
67
|
isError: true,
|
|
74
|
-
content: [
|
|
75
|
-
{
|
|
76
|
-
type: "text",
|
|
77
|
-
text: `无法调用 ${spec.name}:${reason}\n\n`
|
|
78
|
-
+ "解决方式:\n"
|
|
79
|
-
+ `1. 在浏览器打开 ${bindUrl},用系统账号登录、勾选公司,页面会给出一个绑定码;\n`
|
|
80
|
-
+ "2. 回到 WorkBuddy 重新连接这个连接器,把绑定码填进表单;\n"
|
|
81
|
-
+ "3. 手工配置 mcp.json 时,可直接补 WB_PROXY_BASE_URL / WB_KEY_ID / WB_SECRET。",
|
|
82
|
-
},
|
|
83
|
-
],
|
|
68
|
+
content: [{ type: "text", text: text(spec.name) }],
|
|
84
69
|
}));
|
|
85
70
|
}
|
|
71
|
+
}
|
|
72
|
+
/** 没绑定成功:给出绑定页地址,让用户能自助。 */
|
|
73
|
+
function registerUnbound(server, reason) {
|
|
74
|
+
// 连接器把服务地址写死在 mcp.json 里,用户只需要一个绑定码,所以这里直接把完整网址给出来
|
|
75
|
+
const base = (process.env["WB_PROXY_BASE_URL"] ?? "").replace(/\/+$/, "");
|
|
76
|
+
const bindUrl = base ? `${base}/bind` : "「连接服务地址」+ /bind";
|
|
77
|
+
registerPlaceholders(server, `尚未绑定海竣信息系统:${reason}`, (name) => `无法调用 ${name}:${reason}\n\n`
|
|
78
|
+
+ "解决方式:\n"
|
|
79
|
+
+ `1. 在浏览器打开 ${bindUrl},用系统账号登录、勾选公司,页面会给出一个绑定码;\n`
|
|
80
|
+
+ "2. 回到 WorkBuddy 重新连接这个连接器,把绑定码填进表单;\n"
|
|
81
|
+
+ "3. 手工配置 mcp.json 时,可直接补 WB_PROXY_BASE_URL / WB_KEY_ID / WB_SECRET。");
|
|
86
82
|
log.warn(`以「未绑定」模式启动,暴露 ${TOOLS.length} 个占位工具`);
|
|
87
83
|
}
|
|
88
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* 服务器端版本过旧:本机连接器已不支持它的接口,工具照常列出、调用了才说明原因。
|
|
86
|
+
*
|
|
87
|
+
* 不直接退出的理由同上:工具列表为空时用户只看到一个坏掉的连接器。
|
|
88
|
+
* 提示必须给出「找谁做什么」——终端用户不懂版本号,也够不着服务器。
|
|
89
|
+
*/
|
|
90
|
+
function registerUpgradeRequired(server, detail) {
|
|
91
|
+
registerPlaceholders(server, `服务器端版本过旧,请立即升级:${detail}`, (name) => `无法调用 ${name}:${detail}\n\n`
|
|
92
|
+
+ "解决办法:让运维升级服务器上的 sems-proxy 后重新连接这个连接器。");
|
|
93
|
+
log.warn(`以「需升级服务端」模式启动:${detail}`);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* 校验 proxy 契约版本。返回 null 表示就绪;返回字符串表示不可用的原因(服务器端要升级)。
|
|
97
|
+
*
|
|
98
|
+
* 连不上不阻断:proxy 可能稍后启动,工具列表先给出来更有用,真调用时会拿到明确错误。
|
|
99
|
+
*/
|
|
89
100
|
async function checkContract(config) {
|
|
90
101
|
try {
|
|
91
102
|
const health = await fetchHealth(config);
|
|
92
103
|
if (health.contractVersion !== CONTRACT_VERSION) {
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
return;
|
|
104
|
+
const detail = `服务器端契约 v${health.contractVersion},本机连接器需要 v${CONTRACT_VERSION}`;
|
|
105
|
+
log.warn(detail);
|
|
106
|
+
return detail;
|
|
96
107
|
}
|
|
97
108
|
// profile / upstream / allow_write 可能不返回:内部诊断由 deploy/proxy/deploy.sh status 查看。
|
|
98
|
-
|
|
99
|
-
const detail = [
|
|
109
|
+
const extra = [
|
|
100
110
|
health.profile === undefined ? "" : `profile ${health.profile}`,
|
|
101
111
|
health.upstream === undefined ? "" : `上游 ${health.upstream}`,
|
|
102
112
|
health.allowWrite === undefined ? "" : `写入 ${health.allowWrite ? "开启" : "关闭"}`,
|
|
103
|
-
]
|
|
113
|
+
]
|
|
114
|
+
.filter(Boolean)
|
|
115
|
+
.join("|");
|
|
104
116
|
log.info(`proxy 已连通|版本 ${health.version}|契约 v${health.contractVersion}`
|
|
105
|
-
+ (
|
|
117
|
+
+ (extra ? `|${extra}` : ""));
|
|
118
|
+
return null;
|
|
106
119
|
}
|
|
107
120
|
catch (err) {
|
|
108
|
-
// 连不上不阻断:proxy 可能稍后启动,而工具列表先给出来更有用
|
|
109
121
|
log.warn(`proxy /health 探测失败:${err instanceof Error ? err.message : String(err)}`);
|
|
122
|
+
return null;
|
|
110
123
|
}
|
|
111
124
|
}
|
|
112
125
|
async function main() {
|
|
@@ -131,26 +144,28 @@ async function main() {
|
|
|
131
144
|
const config = loaded.config;
|
|
132
145
|
log.info(`配置来源:${config.source === "env" ? "环境变量" : `绑定文件(key_id ${config.keyId})`}`);
|
|
133
146
|
const client = new ProxyClient(config);
|
|
134
|
-
//
|
|
135
|
-
|
|
147
|
+
// 启动先拉一次;拉不到时 RuleBook 会读本地缓存兜底,仍不阻断启动。
|
|
148
|
+
// keyId 让缓存按绑定隔离,换绑后不沿用旧公司的规则。
|
|
149
|
+
const agentRules = new RuleBook(client, undefined, config.keyId);
|
|
136
150
|
await agentRules.refresh();
|
|
151
|
+
// 规则写进每个工具的 description:模型拿到 tools/list 时就读到,第一发调用即生效。
|
|
152
|
+
// 不能用 initialize 的 instructions —— WorkBuddy 客户端不把它喂给模型。
|
|
153
|
+
withRuleDescriptions(server, agentRules.snapshotText());
|
|
137
154
|
const ctx = {
|
|
138
155
|
client,
|
|
139
|
-
// 权限预检与业务请求共用同一份签名密钥,没必要建两个 client
|
|
140
|
-
guard: new PermissionGuard(client),
|
|
141
|
-
userProfile: new UserProfileCache(client),
|
|
142
|
-
// 草稿只活在本进程内存里:进程一退就失效,避免旧草稿被当成新单提交
|
|
143
|
-
drafts: new DraftStore(),
|
|
144
156
|
config,
|
|
145
157
|
agentRules,
|
|
158
|
+
persistActiveTenant,
|
|
146
159
|
};
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
160
|
+
// 契约不符时通道端点不存在,注册了只会让每个调用都失败(策略见 contracts/compat.yaml)。
|
|
161
|
+
const blocked = await checkContract(config);
|
|
162
|
+
if (blocked === null) {
|
|
163
|
+
registerChannel(server, ctx);
|
|
164
|
+
log.info(`已注册通道工具 ${TOOLS.length} 个(help / call / prepare / commit / switch_tenant)`);
|
|
165
|
+
}
|
|
166
|
+
else {
|
|
167
|
+
registerUpgradeRequired(server, blocked);
|
|
168
|
+
}
|
|
154
169
|
}
|
|
155
170
|
const transport = new StdioServerTransport();
|
|
156
171
|
await server.connect(transport);
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通道工具:MCP 只剩「转发 + 展示」,业务判定全在 proxy。
|
|
3
|
+
*
|
|
4
|
+
* 五个工具解决全部场景:
|
|
5
|
+
* sems_help 我能做什么(能力清单 + 已绑定公司 + 当前公司)
|
|
6
|
+
* sems_call 执行只读能力
|
|
7
|
+
* sems_prepare 起草写操作(出摘要与 warnings,不写库)
|
|
8
|
+
* sems_commit 提交草稿(只认 draftId + digest)
|
|
9
|
+
* sems_switch_tenant 切换当前公司(改本机 binding.json,proxy 做不到)
|
|
10
|
+
*
|
|
11
|
+
* 🔴 新增业务能力不要在这里加工具:已有 handler 的能力在 proxy 后台改注册表即可,MCP 不用发版;
|
|
12
|
+
* 需要新 handler 时仍要改 proxy 的 Python 并发版(后台不接受未登记的 handler)。
|
|
13
|
+
*
|
|
14
|
+
* 🔴 sems_switch_tenant 留在这里的原因:它改的是**本机** binding.json 的
|
|
15
|
+
* activeTenant,属于客户端本地状态,proxy 不可能代劳。这是唯一一个
|
|
16
|
+
* 「不是转发」的工具,其余四个都是纯通道。
|
|
17
|
+
*/
|
|
18
|
+
import { readFile } from "node:fs/promises";
|
|
19
|
+
import { basename } from "node:path";
|
|
20
|
+
import { z } from "zod";
|
|
21
|
+
import { runTool } from "./respond.js";
|
|
22
|
+
const CAPABILITIES_PATH = "/_proxy/capabilities";
|
|
23
|
+
const INVOKE_PATH = "/_proxy/invoke";
|
|
24
|
+
const DRAFT_PATH = "/_proxy/draft";
|
|
25
|
+
const COMMIT_PATH = "/_proxy/commit";
|
|
26
|
+
/**
|
|
27
|
+
* 把 `files: [{path}]` 解析成 `{name, contentBase64}`。
|
|
28
|
+
*
|
|
29
|
+
* proxy 读不到客户机磁盘,所以这一步只能在 MCP 做。已经带了 contentBase64 的
|
|
30
|
+
* 条目原样透传(便于上游脚本直接给内容)。读失败抛错而不是跳过——静默跳过
|
|
31
|
+
* 会让用户以为附件已经传上去了。
|
|
32
|
+
*/
|
|
33
|
+
async function resolveFiles(args) {
|
|
34
|
+
const raw = args["files"];
|
|
35
|
+
if (!Array.isArray(raw) || raw.length === 0)
|
|
36
|
+
return args;
|
|
37
|
+
const out = [];
|
|
38
|
+
for (const item of raw) {
|
|
39
|
+
const entry = typeof item === "object" && item !== null ? item : {};
|
|
40
|
+
const preset = typeof entry["contentBase64"] === "string" ? entry["contentBase64"] : "";
|
|
41
|
+
const path = typeof entry["path"] === "string" ? entry["path"] : "";
|
|
42
|
+
const name = (typeof entry["name"] === "string" && entry["name"]) || (path ? basename(path) : "upload.bin");
|
|
43
|
+
if (preset) {
|
|
44
|
+
out.push({ name, contentBase64: preset });
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (!path)
|
|
48
|
+
throw new Error(`附件 ${name} 既没有 path 也没有 contentBase64`);
|
|
49
|
+
let bytes;
|
|
50
|
+
try {
|
|
51
|
+
bytes = await readFile(path);
|
|
52
|
+
}
|
|
53
|
+
catch (err) {
|
|
54
|
+
throw new Error(`读不到附件 ${path}:${err instanceof Error ? err.message : String(err)}。`
|
|
55
|
+
+ "请确认路径正确且当前用户有读权限。");
|
|
56
|
+
}
|
|
57
|
+
out.push({ name, contentBase64: bytes.toString("base64") });
|
|
58
|
+
}
|
|
59
|
+
return { ...args, files: out };
|
|
60
|
+
}
|
|
61
|
+
export function registerChannel(server, ctx) {
|
|
62
|
+
server.registerTool("sems_help", {
|
|
63
|
+
title: "我能做什么(能力清单 / 已绑定公司 / 当前公司)",
|
|
64
|
+
description: "回答「你能做什么」「我有几家公司」「为什么查不了销售利润」这类问题时先调这个。"
|
|
65
|
+
+ "返回当前账号可用的能力清单(每条带 name、title、usage、params 与是否写操作)、"
|
|
66
|
+
+ "这把密钥绑定了哪几家公司、以及当前正在用哪家。"
|
|
67
|
+
+ "🔴 能力清单已按你的权限过滤:不在清单里的就是没权限,不要硬调,"
|
|
68
|
+
+ "也不要报权限码(海竣信息系统界面上看不到权限码,只有中文权限名)。"
|
|
69
|
+
+ "调用其它工具前先用这里的 name 与 params 确认参数名,参数名写错会被服务端拒绝。",
|
|
70
|
+
inputSchema: {},
|
|
71
|
+
annotations: { readOnlyHint: true },
|
|
72
|
+
}, runTool(ctx, "sems_help", async () => {
|
|
73
|
+
const [caps, companies] = await Promise.all([
|
|
74
|
+
ctx.client.call({ method: "GET", path: CAPABILITIES_PATH }),
|
|
75
|
+
ctx.client.call({ method: "GET", path: "/identities" }).catch(() => ({ data: null })),
|
|
76
|
+
]);
|
|
77
|
+
const capDoc = (caps.data ?? {});
|
|
78
|
+
const companyDoc = (companies.data ?? {});
|
|
79
|
+
const list = Array.isArray(companyDoc.identities) ? companyDoc.identities : [];
|
|
80
|
+
const usable = list.filter((item) => {
|
|
81
|
+
const status = item.status;
|
|
82
|
+
return status === undefined || status === "ACTIVE";
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
currentTenant: ctx.config.activeTenant || "default",
|
|
86
|
+
companies: usable,
|
|
87
|
+
capabilities: capDoc.capabilities ?? [],
|
|
88
|
+
usage: {
|
|
89
|
+
"只读(查数据)": "sems_call(name, args)",
|
|
90
|
+
写操作: "先 sems_prepare(name, args) 出草稿,用户确认后 sems_commit(draftId, digest)",
|
|
91
|
+
"切换公司": "sems_switch_tenant(tenantId),传 default 回到默认公司",
|
|
92
|
+
},
|
|
93
|
+
note: "写操作必须把 summary 与 warnings 完整念给用户,得到明确同意后才能提交;"
|
|
94
|
+
+ "用户要改任何一项就重新 prepare,不要改旧草稿。",
|
|
95
|
+
};
|
|
96
|
+
}));
|
|
97
|
+
server.registerTool("sems_call", {
|
|
98
|
+
title: "执行只读能力",
|
|
99
|
+
description: "按能力名执行一次只读查询。name 与 args 的字段名必须来自 sems_help 的能力清单,"
|
|
100
|
+
+ "写错参数名会被服务端拒绝(不会静默忽略)。"
|
|
101
|
+
+ "写操作不走这里——用 sems_prepare + sems_commit。",
|
|
102
|
+
inputSchema: {
|
|
103
|
+
name: z.string().min(1).describe("能力名,来自 sems_help 的 capabilities[].name"),
|
|
104
|
+
args: z.record(z.unknown()).optional().describe("能力参数,字段名见该能力的 params"),
|
|
105
|
+
},
|
|
106
|
+
annotations: { readOnlyHint: true },
|
|
107
|
+
}, runTool(ctx, "sems_call", async (args) => {
|
|
108
|
+
const res = await ctx.client.call({
|
|
109
|
+
method: "POST",
|
|
110
|
+
path: INVOKE_PATH,
|
|
111
|
+
body: { name: String(args.name ?? ""), args: args.args ?? {} },
|
|
112
|
+
});
|
|
113
|
+
const doc = (res.data ?? {});
|
|
114
|
+
return doc.data ?? res.data;
|
|
115
|
+
}));
|
|
116
|
+
server.registerTool("sems_prepare", {
|
|
117
|
+
title: "起草写操作(不写库)",
|
|
118
|
+
description: "按能力名生成一份待确认草稿,**不会写入海竣信息系统**。"
|
|
119
|
+
+ "返回 draftId、digest、summary(给用户看的确认清单,可能多行,逐行完整念、不要压缩成一句)"
|
|
120
|
+
+ "与 warnings(必须完整转述的风险提示)。"
|
|
121
|
+
+ "拿到后先念 summary 与 warnings,用户明确同意再调 sems_commit;用户要改就用新的参数重新 prepare。",
|
|
122
|
+
inputSchema: {
|
|
123
|
+
name: z
|
|
124
|
+
.string()
|
|
125
|
+
.min(1)
|
|
126
|
+
.describe("写能力名,如 create_sale_order / create_partner / manage_contract"),
|
|
127
|
+
args: z.record(z.unknown()).optional().describe("能力参数,字段名见该能力的 params"),
|
|
128
|
+
},
|
|
129
|
+
annotations: { readOnlyHint: false },
|
|
130
|
+
}, runTool(ctx, "sems_prepare", async (args) => {
|
|
131
|
+
const resolved = await resolveFiles(args.args ?? {});
|
|
132
|
+
const res = await ctx.client.call({
|
|
133
|
+
method: "POST",
|
|
134
|
+
path: DRAFT_PATH,
|
|
135
|
+
body: { name: String(args.name ?? ""), args: resolved },
|
|
136
|
+
});
|
|
137
|
+
return res.data;
|
|
138
|
+
}));
|
|
139
|
+
server.registerTool("sems_commit", {
|
|
140
|
+
title: "提交草稿(真正写库)",
|
|
141
|
+
description: "用 sems_prepare 返回的 draftId 与 digest 提交。服务端只认这两个值,不接受任何业务参数覆盖——"
|
|
142
|
+
+ "这是「用户确认的是 A、提交的也必须是 A」的唯一保证。"
|
|
143
|
+
+ "🔴 提交失败不会自动重试(建单接口没有幂等键):先到海竣信息系统核实单据是否已创建,确认没有再重新起草。"
|
|
144
|
+
+ "同一份草稿重复提交会返回上次结果并标注 alreadyCommitted,不会建第二张单。",
|
|
145
|
+
inputSchema: {
|
|
146
|
+
draftId: z.string().min(1).describe("sems_prepare 返回的 draftId"),
|
|
147
|
+
digest: z.string().min(1).describe("sems_prepare 返回的 digest,用于防篡改"),
|
|
148
|
+
},
|
|
149
|
+
annotations: { readOnlyHint: false },
|
|
150
|
+
}, runTool(ctx, "sems_commit", async (args) => {
|
|
151
|
+
const res = await ctx.client.call({
|
|
152
|
+
method: "POST",
|
|
153
|
+
path: COMMIT_PATH,
|
|
154
|
+
body: { draftId: String(args.draftId ?? ""), digest: String(args.digest ?? "") },
|
|
155
|
+
});
|
|
156
|
+
return res.data;
|
|
157
|
+
}));
|
|
158
|
+
server.registerTool("sems_switch_tenant", {
|
|
159
|
+
title: "切换当前使用的公司",
|
|
160
|
+
description: "把后续查询切到另一家已绑定的公司(同一把密钥可绑多家)。传 default 回到绑定时选中的默认公司。"
|
|
161
|
+
+ "切换只影响之后的调用,不重绑、不需要密码。",
|
|
162
|
+
inputSchema: {
|
|
163
|
+
tenantId: z
|
|
164
|
+
.string()
|
|
165
|
+
.min(1)
|
|
166
|
+
.describe("目标公司 tenantId(用 sems_help 查),传 default 回到默认公司"),
|
|
167
|
+
},
|
|
168
|
+
// 它写本机 binding.json 并改进程内 activeTenant,不是只读操作。
|
|
169
|
+
annotations: { readOnlyHint: false },
|
|
170
|
+
}, runTool(ctx, "sems_switch_tenant", async (args) => {
|
|
171
|
+
const wanted = String(args.tenantId ?? "").trim();
|
|
172
|
+
if (!wanted)
|
|
173
|
+
throw new Error("请提供 tenantId;回到默认公司请传 default");
|
|
174
|
+
const doc = (await ctx.client.call({ method: "GET", path: "/identities" })).data;
|
|
175
|
+
const list = Array.isArray(doc?.identities) ? doc.identities : [];
|
|
176
|
+
const companies = list.map((item) => {
|
|
177
|
+
const row = (item ?? {});
|
|
178
|
+
return {
|
|
179
|
+
tenantId: String(row["tenantId"] ?? ""),
|
|
180
|
+
name: String(row["name"] ?? row["username"] ?? "未命名企业"),
|
|
181
|
+
status: typeof row["status"] === "string" ? row["status"] : undefined,
|
|
182
|
+
};
|
|
183
|
+
});
|
|
184
|
+
if (wanted.toLowerCase() === "default") {
|
|
185
|
+
ctx.config.activeTenant = "";
|
|
186
|
+
const persisted = ctx.persistActiveTenant("");
|
|
187
|
+
return { ok: true, current: "default", persisted, message: "已切回默认公司。" };
|
|
188
|
+
}
|
|
189
|
+
const hit = companies.find((item) => item.tenantId === wanted);
|
|
190
|
+
if (!hit) {
|
|
191
|
+
const options = companies.map((c) => `${c.name}(${c.tenantId})`).join("、") || "(无)";
|
|
192
|
+
throw new Error(`没有已绑定的公司 ${wanted}。可选:${options}`);
|
|
193
|
+
}
|
|
194
|
+
// 切到已失效的身份不会立刻报错,而是此后每次调用都 401 ——
|
|
195
|
+
// 那种「能切、但什么都查不了」的体验比直接拒绝更难解释。
|
|
196
|
+
if (hit.status !== undefined && hit.status !== "ACTIVE") {
|
|
197
|
+
throw new Error(`「${hit.name}」这条身份已失效(状态 ${hit.status}),切过去之后所有查询都会失败。`
|
|
198
|
+
+ "请先在 WorkBuddy 重新绑定这家公司。");
|
|
199
|
+
}
|
|
200
|
+
ctx.config.activeTenant = hit.tenantId;
|
|
201
|
+
const persisted = ctx.persistActiveTenant(hit.tenantId);
|
|
202
|
+
return {
|
|
203
|
+
ok: true,
|
|
204
|
+
current: hit.tenantId,
|
|
205
|
+
name: hit.name,
|
|
206
|
+
persisted,
|
|
207
|
+
message: persisted
|
|
208
|
+
? `已切换到「${hit.name}」,后续查询都按这家公司。`
|
|
209
|
+
: `已切换到「${hit.name}」(本次会话生效;绑定文件不可写,重启后回到默认公司)。`,
|
|
210
|
+
};
|
|
211
|
+
}));
|
|
212
|
+
}
|
package/dist/tools/context.js
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 通道模式下的工具上下文。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* 只剩四样东西:签名客户端、本机配置(当前公司)、按公司内置规则、
|
|
5
|
+
* 以及把公司选择写回 binding.json 的钩子。
|
|
6
|
+
*
|
|
7
|
+
* 权限预检、用户档案、草稿暂存都已搬到 proxy:
|
|
8
|
+
* · 权限:由 proxy 的 /invoke 判定(能力清单也按权限过滤,无权能力不下发)
|
|
9
|
+
* · 用户档案:由 proxy 自己调 /admin/user/info 补全,19 位 ID 不会过 JS
|
|
10
|
+
* · 草稿:落 proxy 的 SQLite,按「账号 × 公司」隔离,多客户端可共享、提交后可回查
|
|
11
|
+
* 所以这里不再有 PermissionGuard / UserProfileCache / DraftStore。
|
|
7
12
|
*/
|
|
8
|
-
|
|
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
|
-
}
|
|
13
|
+
export {};
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* 工具执行的统一出口:执行 → 归一化错误 → 文本化 → 注入按公司内置规则。
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
4
|
+
* 通道模式下只剩这一层:权限预检已搬到 proxy(能力清单按权限过滤、/invoke 再判一次),
|
|
5
|
+
* 所以这里不再有 guard.require;但「错误码到中文文案」「上下文体积保护」
|
|
6
|
+
* 「规则拼在结果前面」三件事仍然只需要做对一次。
|
|
6
7
|
*/
|
|
7
8
|
import { ProxyError } from "../client/errors.js";
|
|
8
9
|
import { log } from "../logger.js";
|
|
9
|
-
import { specOf } from "./context.js";
|
|
10
10
|
/**
|
|
11
11
|
* 进入对话上下文的文本上限。
|
|
12
12
|
*
|
|
@@ -15,13 +15,13 @@ import { specOf } from "./context.js";
|
|
|
15
15
|
* 而不是悄悄丢掉后半段。
|
|
16
16
|
*/
|
|
17
17
|
const MAX_TEXT = 48_000;
|
|
18
|
-
function toText(data, limit = MAX_TEXT) {
|
|
18
|
+
export function toText(data, limit = MAX_TEXT) {
|
|
19
19
|
const text = JSON.stringify(data) ?? "null";
|
|
20
20
|
if (text.length <= limit)
|
|
21
21
|
return text;
|
|
22
|
-
return `${text.slice(0, limit)}…(已截断,原始响应共 ${text.length}
|
|
22
|
+
return `${text.slice(0, limit)}…(已截断,原始响应共 ${text.length} 字符。请缩小范围:减小 size、加上时间区间,或先查汇总再查明细)`;
|
|
23
23
|
}
|
|
24
|
-
function failure(tool, err) {
|
|
24
|
+
export function failure(tool, err) {
|
|
25
25
|
if (err instanceof ProxyError) {
|
|
26
26
|
const lines = [`调用 ${tool} 失败:${err.message}`, `错误码:${err.code}`];
|
|
27
27
|
if (err.hint)
|
|
@@ -44,13 +44,9 @@ function failure(tool, err) {
|
|
|
44
44
|
};
|
|
45
45
|
}
|
|
46
46
|
/** 生成可直接交给 `server.registerTool` 的回调。 */
|
|
47
|
-
export function
|
|
48
|
-
const spec = specOf(name);
|
|
47
|
+
export function runTool(ctx, name, handler) {
|
|
49
48
|
return async (args) => {
|
|
50
49
|
try {
|
|
51
|
-
// 只读工具在 tools.yaml 里没有 perm 的(如库存/商品)仍需登录态,
|
|
52
|
-
// 但登录态由 proxy 的签名校验保证,这里传 null 即跳过预检。
|
|
53
|
-
await ctx.guard.require(spec.perm);
|
|
54
50
|
const data = await handler(args);
|
|
55
51
|
// 规则注入放在统一出口:不做工具白名单,规则文本自带适用场景,模型按内容判断。
|
|
56
52
|
const ruleText = await ctx.agentRules.forTenant(ctx.config.activeTenant);
|
|
@@ -66,11 +62,6 @@ export function wrap(ctx, name, handler) {
|
|
|
66
62
|
};
|
|
67
63
|
}
|
|
68
64
|
catch (err) {
|
|
69
|
-
// 令牌类错误往往意味着权限也变了,清掉缓存让下次重新拉;绑定换了账号时档案同样失效。
|
|
70
|
-
if (err instanceof ProxyError && (err.code === "REBIND_REQUIRED" || err.http === 401)) {
|
|
71
|
-
ctx.guard.invalidate();
|
|
72
|
-
ctx.userProfile.invalidate();
|
|
73
|
-
}
|
|
74
65
|
return failure(name, err);
|
|
75
66
|
}
|
|
76
67
|
};
|
package/package.json
CHANGED
package/dist/drafts/digest.js
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 草稿内容摘要:让「用户确认的那份」与「实际提交的那份」可证明是同一份。
|
|
3
|
-
*
|
|
4
|
-
* 做法是对规范化后的 JSON 取 SHA-256 前 16 位。规范化 = 递归按 key 排序,
|
|
5
|
-
* 这样 `{a:1,b:2}` 与 `{b:2,a:1}` 得到同一个值——参数顺序不该影响「是不是同一份草稿」。
|
|
6
|
-
*/
|
|
7
|
-
import { createHash } from "node:crypto";
|
|
8
|
-
function canonicalize(value) {
|
|
9
|
-
if (Array.isArray(value))
|
|
10
|
-
return value.map(canonicalize);
|
|
11
|
-
if (value !== null && typeof value === "object") {
|
|
12
|
-
const source = value;
|
|
13
|
-
const out = {};
|
|
14
|
-
for (const key of Object.keys(source).sort())
|
|
15
|
-
out[key] = canonicalize(source[key]);
|
|
16
|
-
return out;
|
|
17
|
-
}
|
|
18
|
-
return value;
|
|
19
|
-
}
|
|
20
|
-
/** 只保留前 16 位:够防碰撞,又短到能在对话里念出来。 */
|
|
21
|
-
export function digestOf(payload) {
|
|
22
|
-
const text = JSON.stringify(canonicalize(payload)) ?? "null";
|
|
23
|
-
return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
|
|
24
|
-
}
|
package/dist/drafts/store.js
DELETED
|
@@ -1,105 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 两阶段草稿的暂存区。
|
|
3
|
-
*
|
|
4
|
-
* 为什么放在 MCP 进程内存而不是数据库:
|
|
5
|
-
* ① 草稿含客户名、金额、联系方式,落库等于多一处泄露面;
|
|
6
|
-
* ② 草稿的有效期只有「用户看一眼并确认」这一小段时间,进程重启后应该失效而不是复活
|
|
7
|
-
* —— 否则会出现「三天前的草稿被提交」,那正是最该防的错单。
|
|
8
|
-
*
|
|
9
|
-
* 因此这里只有内存 Map:进程一退就全丢,这是特性不是缺陷。
|
|
10
|
-
*/
|
|
11
|
-
import { randomBytes } from "node:crypto";
|
|
12
|
-
/** 草稿 30 分钟未提交即失效。够用户看完一屏并回一句「确认」,又不至于让旧草稿长期可提交。 */
|
|
13
|
-
const TTL_MS = 30 * 60 * 1000;
|
|
14
|
-
/** 同时最多保留 20 份。超出时丢最旧的——草稿是临时物,不该无限增长。 */
|
|
15
|
-
const MAX_DRAFTS = 20;
|
|
16
|
-
export class DraftStore {
|
|
17
|
-
#map = new Map();
|
|
18
|
-
create(input) {
|
|
19
|
-
this.#evictExpired();
|
|
20
|
-
if (this.#map.size >= MAX_DRAFTS) {
|
|
21
|
-
// Map 保持插入顺序,第一个就是最旧的
|
|
22
|
-
const oldest = this.#map.keys().next();
|
|
23
|
-
if (!oldest.done)
|
|
24
|
-
this.#map.delete(oldest.value);
|
|
25
|
-
}
|
|
26
|
-
const draft = {
|
|
27
|
-
...input,
|
|
28
|
-
id: `dr_${randomBytes(8).toString("hex")}`,
|
|
29
|
-
createdAt: Date.now(),
|
|
30
|
-
state: "pending",
|
|
31
|
-
};
|
|
32
|
-
this.#map.set(draft.id, draft);
|
|
33
|
-
return draft;
|
|
34
|
-
}
|
|
35
|
-
/**
|
|
36
|
-
* 取出一份待提交草稿。三道校验缺一不可:
|
|
37
|
-
*
|
|
38
|
-
* 1. **存在且未过期** —— 过期的草稿必须当作不存在,不能「刚好还没清」就放行;
|
|
39
|
-
* 2. **工具匹配** —— 防止把销售草稿交给采购的 commit;
|
|
40
|
-
* 3. **摘要匹配** —— 用户确认的是 A,提交的必须是 A。不匹配就拒绝并要求重新起草,
|
|
41
|
-
* 而不是「悄悄按新内容提交」。这条是防「AI 在确认后又改了金额」的唯一手段。
|
|
42
|
-
*/
|
|
43
|
-
take(id, tool, digest) {
|
|
44
|
-
this.#evictExpired();
|
|
45
|
-
const draft = this.#map.get(id);
|
|
46
|
-
if (!draft) {
|
|
47
|
-
return { ok: false, reason: `草稿 ${id} 不存在或已过期(草稿 30 分钟内有效)。请重新起草。` };
|
|
48
|
-
}
|
|
49
|
-
if (draft.tool !== tool) {
|
|
50
|
-
return {
|
|
51
|
-
ok: false,
|
|
52
|
-
reason: `草稿 ${id} 属于 ${draft.tool},不能用于 ${tool}。请重新起草。`,
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
if (draft.state === "committed") {
|
|
56
|
-
return {
|
|
57
|
-
ok: false,
|
|
58
|
-
reason: `草稿 ${id} 已经提交过,不会重复创建。上次的提交结果见下:\n`
|
|
59
|
-
+ `${JSON.stringify(draft.result ?? null)}`,
|
|
60
|
-
};
|
|
61
|
-
}
|
|
62
|
-
if (draft.state === "submitting") {
|
|
63
|
-
return {
|
|
64
|
-
ok: false,
|
|
65
|
-
reason: `草稿 ${id} 正在提交中。请勿重复提交;若长时间无响应,请先用查询工具核实单据是否已创建。`,
|
|
66
|
-
};
|
|
67
|
-
}
|
|
68
|
-
if (draft.digest !== digest) {
|
|
69
|
-
return {
|
|
70
|
-
ok: false,
|
|
71
|
-
reason: `摘要不匹配:草稿 ${id} 的摘要是 ${draft.digest},收到 ${digest}。\n`
|
|
72
|
-
+ "草稿内容与用户确认的内容不一致时不会提交。请重新起草并让用户确认新的内容。",
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
return { ok: true, draft };
|
|
76
|
-
}
|
|
77
|
-
/**
|
|
78
|
-
* 标记为提交中。提交是「至多一次」的:SEMS 的建单接口没有幂等键,
|
|
79
|
-
* 网络超时既可能「没建成」也可能「建成了但没收到响应」,
|
|
80
|
-
* 所以失败后不自动重试,而是让调用方去核实——这比自动重试造出两张单安全。
|
|
81
|
-
*/
|
|
82
|
-
markSubmitting(draft) {
|
|
83
|
-
draft.state = "submitting";
|
|
84
|
-
}
|
|
85
|
-
markCommitted(draft, result) {
|
|
86
|
-
draft.state = "committed";
|
|
87
|
-
draft.result = result;
|
|
88
|
-
}
|
|
89
|
-
markFailed(draft) {
|
|
90
|
-
draft.state = "failed";
|
|
91
|
-
}
|
|
92
|
-
get size() {
|
|
93
|
-
this.#evictExpired();
|
|
94
|
-
return this.#map.size;
|
|
95
|
-
}
|
|
96
|
-
#evictExpired() {
|
|
97
|
-
const now = Date.now();
|
|
98
|
-
for (const [id, draft] of this.#map) {
|
|
99
|
-
// failed 也清掉:它的价值只在「这一次请求的上下文里」,
|
|
100
|
-
// 留着只会让用户误以为还能再提交一次。
|
|
101
|
-
if (now - draft.createdAt > TTL_MS)
|
|
102
|
-
this.#map.delete(id);
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
}
|