@miaocedata/mbi-bi-mcp 0.2.5 → 0.2.7
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 +7 -1
- package/package.json +1 -1
- package/src/auth-helper.js +129 -0
- package/src/auth.js +4 -2
- package/src/client.js +159 -26
- package/src/index.js +4 -3
- package/src/tool-manifest.json +1 -1
package/README.md
CHANGED
|
@@ -80,6 +80,10 @@ MBI_PLATFORM_URL = "https://bi.example.com"
|
|
|
80
80
|
2. `query_metrics` 每次只查询一个 App。要限定日期,例如传 `dateRange: { "dimensionId": "205", "from": "2026-10-01", "toExclusive": "2026-11-01" }`。起日包含,止日不包含,最多 366 天。用配置中 `dateRangeSupported` 的真实日历维度;有多个时明确指定,不能用字段名或表达式。
|
|
81
81
|
3. 中台校验实际日期选择和指定版本的本体规则。不能安全应用筛选、版本无权访问或存在未支持的约束时,工具返回错误;不要移除用户要求的约束重试。旧服务端不支持这些新参数,本地连接器和中台各服务应按 [部署与验收](../mbi-agent-service/docs/50-external-bi-mcp-deployment.md) 配套升级。
|
|
82
82
|
|
|
83
|
+
**工具清单按服务端实际能力下发。** 连接器会用一次 `tools/list` 探测服务端真正提供的工具(结果缓存 60 秒),只把服务端认识的清单工具列给宿主,本地的 `configure_platform`、`reauthorize` 始终保留。这样中台未升级时,模型不会去调用注定返回 `Unknown tool` 的工具;探测失败(网络异常等)时退回完整清单,不影响正常使用。
|
|
84
|
+
|
|
85
|
+
**错误信息一定有可读原因。** 服务端的工具错误只带错误码,连接器会按码补一句中文说明(例如 `DATE_DIMENSION_UNAVAILABLE` → 「指定的日期维度不可用,请从 get_analysis_config 返回的日期维度中选择。」),并且只翻译白名单里的错误码,绝不把服务端原始文本透传给模型。协议级错误(例如旧版服务端不认识某个工具)会显示为 `TOOL_NOT_SUPPORTED`,并提示改用 `get_analysis_config`、`get_business_ontology`、`query_metrics`。HTTP 层失败也会带上状态码与排查方向(门户地址、网关路由),不再是一句空的 `BI_SERVICE_UNAVAILABLE`。
|
|
86
|
+
|
|
83
87
|
## Profile 控制的能力
|
|
84
88
|
|
|
85
89
|
1. 调用 `get_agent_profiles`。只返回当前平台账号通过 USE/MANAGE ACL、且未停用、未被显式 DENY 的业务 Profile;同时给出当前角色下真正可用的能力。内部 `supervisor` 与 `demo_delivery` 不对外暴露。
|
|
@@ -88,9 +92,11 @@ MBI_PLATFORM_URL = "https://bi.example.com"
|
|
|
88
92
|
|
|
89
93
|
如果 `agent:write` 被收回、Profile ACL 被撤销、Profile 被停用、能力被移出白名单或工具管理关闭,下一次调用会拒绝。`get_agent_tools` 不返回未授权的写工具;`publish_mashup_extension` 不直接开放,大屏发布必须经过 `mashup_board` 的版本化验收闸门。
|
|
90
94
|
|
|
95
|
+
`mashup_board` 必须按 `contract → validate → prepare → preflight → verify → publish` 执行,并复用同一个 `executionId`。`publish` 只接受 `prepare` 返回的 `artifact_id`,不能重新传 spec。交互式 Sense X 可以继续启用 `design-only`;已通过 `agent:write`、Profile USE ACL 和 `mashup_board` 能力校验的外部 MCP 执行上下文可以使用同一套版本化自动发布链。
|
|
96
|
+
|
|
91
97
|
## 打包与上架
|
|
92
98
|
|
|
93
|
-
运行 `npm pack --dry-run` 检查文件,再运行 `npm publish --access public` 发布到 `@miaocedata/mbi-bi-mcp@0.2.
|
|
99
|
+
运行 `npm pack --dry-run` 检查文件,再运行 `npm publish --access public` 发布到 `@miaocedata/mbi-bi-mcp@0.2.6`(发布前需在 npmjs.com 拥有 `miaocedata` 组织,否则会报 `404 Scope not found`),市场包用 `connector/mcp.json` 里固定的版本号启动。`connector/mcp.json` 的 `npmRegistries` 按 `registry.npmjs.org` → `registry.npmmirror.com` 顺序回退:npm 官方仓库是权威源,国内镜像只做兜底,避免只配镜像时新版本尚未同步导致 `npx` 404。后续每次升级必须先递增 `package.json` 的版本号再发布,并同步修改 `connector/mcp.json` 与 `connector/connector-meta.json` 里的版本号;只向 WorkBuddy 提交所需连接器材料,不把中台服务、Python connector、客户地址或任何凭证打进市场包。
|
|
94
100
|
|
|
95
101
|
> **提审前须知(本地定制)**:当前 `src/client.js` 将滑动 7 天令牌持久化到本机用户目录(`~/.mbi-bi/grant.json`),目的是避免宿主关闭或每轮对话重启进程后反复授权。令牌文件不在本包目录内,不会随 `npm pack` 进入市场包;但长期凭据落盘属于安全敏感行为,正式提审前须重新评估是否接受。若需恢复短时令牌设计,用同目录的 `src/client.js.bak` 覆盖 `src/client.js`,并把上面的有效期说明同步改回。
|
|
96
102
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// 授权助手:MCP 主进程缺少授权时用 detached 方式拉起本文件,本进程独立于宿主会话存活。
|
|
3
|
+
// 职责:固定端口接收浏览器回调 → 换取令牌 → 原子写入 grant.json → 退出。
|
|
4
|
+
// 独立成进程的原因:WorkBuddy 每次工具调用结束就回收沙箱会话并结束 MCP 进程,
|
|
5
|
+
// 授权若在 MCP 进程内等待,浏览器回调只会得到 ERR_CONNECTION_REFUSED。
|
|
6
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { createServer } from 'node:http';
|
|
9
|
+
import { dirname, join } from 'node:path';
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
12
|
+
import { authorize, openBrowser, platformUrls } from './auth.js';
|
|
13
|
+
|
|
14
|
+
// 固定端口便于在浏览器里一眼看出是本机授权回调;端口被占用即视为已有助手在等回调
|
|
15
|
+
export const AUTH_HELPER_PORT = Number(process.env.MBI_AUTH_PORT ?? 18765);
|
|
16
|
+
|
|
17
|
+
const STORE_DIR = join(homedir(), '.mbi-bi');
|
|
18
|
+
const GRANT_FILE = join(STORE_DIR, 'grant.json');
|
|
19
|
+
const LOCK_FILE = join(STORE_DIR, 'auth-helper.lock');
|
|
20
|
+
const LOG_FILE = join(STORE_DIR, 'auth-helper.log');
|
|
21
|
+
// 与本进程等待窗口一致:超过这个时间没有回调,视为本轮授权失败
|
|
22
|
+
const TIMEOUT_MS = Number(process.env.MBI_AUTH_TIMEOUT_MS ?? 180_000);
|
|
23
|
+
|
|
24
|
+
function log(text) {
|
|
25
|
+
try {
|
|
26
|
+
mkdirSync(STORE_DIR, { recursive: true });
|
|
27
|
+
appendFileSync(LOG_FILE, `${new Date().toISOString()} [${process.pid}] ${text}\n`);
|
|
28
|
+
} catch {}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// 原子落盘:先写同目录临时文件再改名,避免宿主读到只写了一半的 JSON
|
|
32
|
+
function writeAtomically(file, content) {
|
|
33
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
34
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
35
|
+
writeFileSync(temp, content, { mode: 0o600 });
|
|
36
|
+
renameSync(temp, file);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// 锁文件表示「已有助手在等回调」,避免每次工具调用都新开一个授权窗口
|
|
40
|
+
function readLock() {
|
|
41
|
+
try {
|
|
42
|
+
const data = JSON.parse(readFileSync(LOCK_FILE, 'utf8'));
|
|
43
|
+
if (Number.isInteger(data?.pid) && Number.isInteger(data?.startedAt)
|
|
44
|
+
&& Date.now() - data.startedAt < TIMEOUT_MS + 60_000) return data;
|
|
45
|
+
} catch {}
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 由 MCP 进程调用:已有助手在等就直接返回 pending,不再重复开浏览器
|
|
50
|
+
export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
|
|
51
|
+
const lock = readLock();
|
|
52
|
+
if (lock) return { started: false, pending: true, pid: lock.pid };
|
|
53
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
|
|
54
|
+
detached: true,
|
|
55
|
+
stdio: 'ignore',
|
|
56
|
+
windowsHide: true,
|
|
57
|
+
env: {
|
|
58
|
+
...env,
|
|
59
|
+
...(platformUrl ? { MBI_PLATFORM_URL: platformUrl } : {}),
|
|
60
|
+
...(apiBasePath ? { MBI_API_BASE_PATH: apiBasePath } : {}),
|
|
61
|
+
...(scope ? { MBI_GRANT_SCOPE: scope } : {}),
|
|
62
|
+
MBI_AUTH_PORT: String(AUTH_HELPER_PORT)
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
child.unref();
|
|
66
|
+
return { started: true, pid: child.pid };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// 先自己试绑一次固定端口:失败说明已有助手在跑,本进程直接退出,不碰对方的锁文件
|
|
70
|
+
async function ensurePortFree() {
|
|
71
|
+
const probe = createServer();
|
|
72
|
+
try {
|
|
73
|
+
await new Promise((resolve, reject) => {
|
|
74
|
+
probe.once('error', reject);
|
|
75
|
+
probe.listen(AUTH_HELPER_PORT, '127.0.0.1', resolve);
|
|
76
|
+
});
|
|
77
|
+
} finally {
|
|
78
|
+
await new Promise((resolve) => probe.close(resolve));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 只有本进程真正写过锁文件,退出时才回收它,避免误删另一个助手的锁
|
|
83
|
+
let lockOwned = false;
|
|
84
|
+
|
|
85
|
+
async function main() {
|
|
86
|
+
const scope = process.env.MBI_GRANT_SCOPE;
|
|
87
|
+
if (!scope) throw new Error('缺少 MBI_GRANT_SCOPE');
|
|
88
|
+
const urls = platformUrls(process.env);
|
|
89
|
+
await ensurePortFree();
|
|
90
|
+
writeAtomically(LOCK_FILE, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
91
|
+
lockOwned = true;
|
|
92
|
+
log(`start port=${AUTH_HELPER_PORT} consent=${urls.consent.href}`);
|
|
93
|
+
// 浏览器打不开不是致命错误:授权地址同时写进日志,用户可手工打开
|
|
94
|
+
const launch = async (uri) => {
|
|
95
|
+
log(`authorize url: ${uri.href}`);
|
|
96
|
+
try {
|
|
97
|
+
await openBrowser(uri);
|
|
98
|
+
} catch (error) {
|
|
99
|
+
log(`open browser failed: ${error?.message ?? error}`);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const grant = await authorize(urls, { port: AUTH_HELPER_PORT, timeoutMs: TIMEOUT_MS, launch });
|
|
103
|
+
writeAtomically(GRANT_FILE, JSON.stringify({ ...grant, platformScope: scope }));
|
|
104
|
+
return grant;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async function run() {
|
|
108
|
+
const grant = await main();
|
|
109
|
+
log(`grant saved expiresAt=${new Date(grant.expiresAt).toISOString()}`);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 只有被直接执行时才运行助手逻辑;被 import 时仅导出 launchAuthHelper
|
|
113
|
+
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
|
114
|
+
run()
|
|
115
|
+
.catch((error) => {
|
|
116
|
+
if (error?.code === 'EADDRINUSE') {
|
|
117
|
+
log(`port ${AUTH_HELPER_PORT} 已被占用,已有助手在监听`);
|
|
118
|
+
} else {
|
|
119
|
+
log(`failed: ${error?.message ?? error}`);
|
|
120
|
+
process.exitCode = 1;
|
|
121
|
+
}
|
|
122
|
+
})
|
|
123
|
+
.finally(() => {
|
|
124
|
+
if (!lockOwned) return;
|
|
125
|
+
try {
|
|
126
|
+
rmSync(LOCK_FILE, { force: true });
|
|
127
|
+
} catch {}
|
|
128
|
+
});
|
|
129
|
+
}
|
package/src/auth.js
CHANGED
|
@@ -166,7 +166,9 @@ export function openBrowser(url) {
|
|
|
166
166
|
}
|
|
167
167
|
|
|
168
168
|
// 授权窗口默认 5 分钟:宿主 mcp.json 的 timeout 必须比它更长,否则进程会先被结束,浏览器只能看到 ERR_CONNECTION_REFUSED。
|
|
169
|
-
|
|
169
|
+
// port 省略时用系统分配的随机端口(同进程内完成授权);传入固定端口时由独立助手进程长期占用,
|
|
170
|
+
// 这样即使拉起它的 MCP 进程被宿主回收,浏览器回调依然能连上监听。
|
|
171
|
+
export async function authorize(urls, { launch = openBrowser, fetcher = fetch, timeoutMs = 300_000, signal, port } = {}) {
|
|
170
172
|
const state = random();
|
|
171
173
|
const verifier = random();
|
|
172
174
|
let accept;
|
|
@@ -211,7 +213,7 @@ export async function authorize(urls, { launch = openBrowser, fetcher = fetch, t
|
|
|
211
213
|
signal?.addEventListener('abort', abort, { once: true });
|
|
212
214
|
await new Promise((resolve, reject) => {
|
|
213
215
|
listener.once('error', reject);
|
|
214
|
-
listener.listen(0, '127.0.0.1', resolve);
|
|
216
|
+
listener.listen(port ?? 0, '127.0.0.1', resolve);
|
|
215
217
|
});
|
|
216
218
|
listener.on('error', fail);
|
|
217
219
|
authority = `127.0.0.1:${listener.address().port}`;
|
package/src/client.js
CHANGED
|
@@ -2,7 +2,8 @@ import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
|
|
2
2
|
import { dirname, join } from 'node:path';
|
|
3
3
|
import { homedir } from 'node:os';
|
|
4
4
|
import Ajv from 'ajv';
|
|
5
|
-
import { ACCESS_TOKEN_SECONDS, CLIENT_ID,
|
|
5
|
+
import { ACCESS_TOKEN_SECONDS, CLIENT_ID, platformUrls, readJson } from './auth.js';
|
|
6
|
+
import { launchAuthHelper } from './auth-helper.js';
|
|
6
7
|
|
|
7
8
|
export const configurationTool = {
|
|
8
9
|
name: 'configure_platform',
|
|
@@ -33,6 +34,8 @@ export const reauthorizeTool = {
|
|
|
33
34
|
};
|
|
34
35
|
const jvmTools = JSON.parse(readFileSync(new URL('./tool-manifest.json', import.meta.url), 'utf8'));
|
|
35
36
|
export const tools = [configurationTool, reauthorizeTool, ...jvmTools];
|
|
37
|
+
// 本地桥接器自带的两个工具,与服务端清单无关,始终对模型可见
|
|
38
|
+
const bridgeTools = new Set([configurationTool.name, reauthorizeTool.name]);
|
|
36
39
|
const ajv = new Ajv({ strict: true });
|
|
37
40
|
const validators = new Map(tools.map(({ name, inputSchema }) => [name, ajv.compile(inputSchema)]));
|
|
38
41
|
const allowedErrors = new Set(['AUTH_REQUIRED', 'AUTH_UNAVAILABLE', 'SCOPE_DENIED', 'LICENSE_REQUIRED', 'BI_MCP_NOT_ENABLED',
|
|
@@ -43,7 +46,48 @@ const allowedErrors = new Set(['AUTH_REQUIRED', 'AUTH_UNAVAILABLE', 'SCOPE_DENIE
|
|
|
43
46
|
'AGENT_PROFILE_DISABLED', 'AGENT_PROFILE_FORBIDDEN', 'AGENT_PROFILE_NOT_FOUND', 'AGENT_CAPABILITY_FORBIDDEN',
|
|
44
47
|
'AGENT_CAPABILITY_UNAVAILABLE', 'AGENT_WRITE_FORBIDDEN', 'AGENT_EXECUTION_BUSY', 'AGENT_EXECUTION_NOT_FOUND',
|
|
45
48
|
'AGENT_EXECUTION_UNAVAILABLE', 'PLATFORM_IDENTITY_UNAVAILABLE', 'PLAN_REQUIRED', 'DELIVERY_GATE_REQUIRED',
|
|
46
|
-
'TOOL_EXECUTION_FAILED']);
|
|
49
|
+
'DELIVERY_ARTIFACT_REQUIRED', 'TOOL_EXECUTION_FAILED']);
|
|
50
|
+
// 服务端的工具错误只带错误码、不带说明文案(见 ExternalBiMcpController.toolError),
|
|
51
|
+
// 这里按错误码给出我们自己的一句中文提示,既让模型知道下一步怎么做,也不会把服务端原始文本透传出去。
|
|
52
|
+
const toolHints = new Map([
|
|
53
|
+
['AUTH_REQUIRED', '授权已失效,请重新授权后再试。'],
|
|
54
|
+
['AUTH_UNAVAILABLE', '授权服务暂不可用,请稍后重试。'],
|
|
55
|
+
['SCOPE_DENIED', '当前授权不包含该操作所需的权限范围。'],
|
|
56
|
+
['LICENSE_REQUIRED', '当前租户的 BI 授权不可用,请联系管理员。'],
|
|
57
|
+
['BI_MCP_NOT_ENABLED', '当前租户尚未开通 MCP 取数能力。'],
|
|
58
|
+
['RESOURCE_FORBIDDEN', '当前账号无权访问该资源。'],
|
|
59
|
+
['RATE_LIMITED', '调用过于频繁,请稍后重试。'],
|
|
60
|
+
['INVALID_ARGUMENT', '参数不符合该工具声明的输入结构。'],
|
|
61
|
+
['SEMANTIC_VERSION_MISMATCH', '语义版本与平台不一致,请重新调用 get_analysis_config 获取最新配置。'],
|
|
62
|
+
['UNSUPPORTED_QUERY_CONSTRAINT', '该查询条件不被支持,请改用已注册的指标与维度。'],
|
|
63
|
+
['DATE_DIMENSION_REQUIRED', '该 App 有多个日期维度,请在 dateRange 中显式指定 dimensionId。'],
|
|
64
|
+
['DATE_DIMENSION_UNAVAILABLE', '指定的日期维度不可用,请从 get_analysis_config 返回的日期维度中选择。'],
|
|
65
|
+
['DATE_RANGE_NO_SELECTION', '该日期范围内没有命中数据,请调整起止日期。'],
|
|
66
|
+
['DATE_MEASURE_UNSUPPORTED', '该指标不支持按日期聚合。'],
|
|
67
|
+
['DATE_RANGE_UNVERIFIED', '日期范围的可用性未确认,请重新读取分析配置后再查。'],
|
|
68
|
+
['ONTOLOGY_VERSION_UNAVAILABLE', '指定的业务本体版本不可用,请重新调用 get_business_ontology。'],
|
|
69
|
+
['ONTOLOGY_QUERY_NOT_ALLOWED', '当前业务本体不允许该查询。'],
|
|
70
|
+
['ONTOLOGY_CONSTRAINT_UNSUPPORTED', '该约束不被当前业务本体支持。'],
|
|
71
|
+
['ONTOLOGY_UNAVAILABLE', '业务本体暂不可用,请稍后重试。'],
|
|
72
|
+
['CONFIG_TOO_LARGE', '分析配置超出大小限制,请联系管理员。'],
|
|
73
|
+
['BI_SERVICE_UNAVAILABLE', '数据中台暂不可用,请稍后重试。'],
|
|
74
|
+
['QLIK_IDENTITY_NOT_CONFIGURED', '数据源访问身份未配置,请联系管理员。'],
|
|
75
|
+
['QLIK_QUERY_FAILED', '数据源查询失败,请稍后重试。'],
|
|
76
|
+
['AGENT_PROFILE_DISABLED', '该 Agent Profile 已停用。'],
|
|
77
|
+
['AGENT_PROFILE_FORBIDDEN', '当前账号无权使用该 Agent Profile。'],
|
|
78
|
+
['AGENT_PROFILE_NOT_FOUND', '未找到该 Agent Profile。'],
|
|
79
|
+
['AGENT_CAPABILITY_FORBIDDEN', '该能力未在这个 Agent Profile 中开启。'],
|
|
80
|
+
['AGENT_CAPABILITY_UNAVAILABLE', '该能力当前不可用。'],
|
|
81
|
+
['AGENT_WRITE_FORBIDDEN', '该 Agent Profile 不允许写操作。'],
|
|
82
|
+
['AGENT_EXECUTION_BUSY', '上一次执行尚未结束,请稍后再试。'],
|
|
83
|
+
['AGENT_EXECUTION_NOT_FOUND', '未找到对应的执行上下文。'],
|
|
84
|
+
['AGENT_EXECUTION_UNAVAILABLE', '执行上下文当前不可用。'],
|
|
85
|
+
['PLATFORM_IDENTITY_UNAVAILABLE', '平台身份信息不可用,请重新授权。'],
|
|
86
|
+
['PLAN_REQUIRED', '该操作需要先提交计划。'],
|
|
87
|
+
['DELIVERY_GATE_REQUIRED', '该操作需要先通过交付检查。'],
|
|
88
|
+
['DELIVERY_ARTIFACT_REQUIRED', '该操作需要先准备交付产物。'],
|
|
89
|
+
['TOOL_EXECUTION_FAILED', '工具执行失败,请稍后重试。']
|
|
90
|
+
]);
|
|
47
91
|
const message = (structuredContent, isError) => ({ structuredContent, isError,
|
|
48
92
|
content: [{ type: 'text', text: JSON.stringify(structuredContent) }] });
|
|
49
93
|
const error = (code, description, requestId) => message({ error: { code, ...(description && { message: description }) },
|
|
@@ -142,21 +186,29 @@ export class PlatformClient {
|
|
|
142
186
|
#grantStore;
|
|
143
187
|
#scope;
|
|
144
188
|
#envToken;
|
|
145
|
-
#
|
|
189
|
+
#platform;
|
|
146
190
|
#lastStart = 0;
|
|
147
191
|
#sequence = 0;
|
|
148
192
|
#stop = new AbortController();
|
|
149
193
|
#closed = false;
|
|
194
|
+
#serverTools;
|
|
150
195
|
|
|
151
|
-
constructor(urls, { fetcher = fetch, login
|
|
152
|
-
grantStore = persistentGrantStore, scope = urls.mcp.href, envToken } = {}) {
|
|
196
|
+
constructor(urls, { fetcher = fetch, login, startAuth, log = (text) => console.error(text),
|
|
197
|
+
grantStore = persistentGrantStore, scope = urls.mcp.href, envToken, platform } = {}) {
|
|
153
198
|
this.urls = urls;
|
|
154
199
|
this.fetcher = fetcher;
|
|
155
|
-
this.login = login;
|
|
156
200
|
this.log = log;
|
|
157
201
|
this.#grantStore = grantStore;
|
|
158
202
|
this.#scope = scope;
|
|
159
203
|
this.#envToken = envToken;
|
|
204
|
+
this.#platform = platform;
|
|
205
|
+
// 授权有两种实现:测试注入的进程内登录(login,等结果),以及生产用的独立助手进程(startAuth,不等结果)
|
|
206
|
+
this.startAuth = startAuth ?? (login
|
|
207
|
+
? async (options) => {
|
|
208
|
+
const grant = await login(this.urls, { fetcher: this.fetcher, signal: this.#stop.signal, ...options });
|
|
209
|
+
if (!this.#closed) { this.#grant = grant; this.#grantStore.save(grant, this.#scope); }
|
|
210
|
+
}
|
|
211
|
+
: (options) => launchAuthHelper(options));
|
|
160
212
|
// 配置里的令牌有效时直接采用,并完全忽略本机缓存文件里的旧令牌
|
|
161
213
|
this.#grant = envToken?.token
|
|
162
214
|
? { token: envToken.token, expiresAt: Number.POSITIVE_INFINITY }
|
|
@@ -205,16 +257,45 @@ export class PlatformClient {
|
|
|
205
257
|
await this.revokeCurrent();
|
|
206
258
|
// 重置频控,保证刚清完授权就能重新打开浏览器
|
|
207
259
|
this.#lastStart = 0;
|
|
208
|
-
|
|
260
|
+
const started = this.#startAuthorization();
|
|
209
261
|
return message({
|
|
210
262
|
reauthorized: true,
|
|
211
263
|
revoked,
|
|
212
|
-
loginPending:
|
|
264
|
+
loginPending: started,
|
|
213
265
|
platformUrl: this.urls.consent.origin,
|
|
214
266
|
hint: '已在浏览器打开授权页。请用中台账号登录并批准授权,完成后重新调用目标工具。'
|
|
215
267
|
}, false);
|
|
216
268
|
}
|
|
217
269
|
|
|
270
|
+
// 读取服务端真正提供的工具清单。控制器只对 tools/call 校验令牌,tools/list 是公开的,
|
|
271
|
+
// 因此这里不带 Authorization,避免为了探测清单反而触发一次浏览器授权。
|
|
272
|
+
// 返回 undefined 表示探测失败,调用方按"不过滤"处理,避免网络抖动把工具全藏起来。
|
|
273
|
+
async serverToolNames() {
|
|
274
|
+
if (this.#closed) return undefined;
|
|
275
|
+
const cached = this.#serverTools;
|
|
276
|
+
if (cached && cached.expiresAt > Date.now()) return cached.names;
|
|
277
|
+
const id = `probe-${++this.#sequence}`;
|
|
278
|
+
try {
|
|
279
|
+
const response = await this.fetcher(this.urls.mcp, {
|
|
280
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(15_000), this.#stop.signal]),
|
|
281
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'MCP-Protocol-Version': '2025-06-18' },
|
|
282
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/list', params: {} })
|
|
283
|
+
});
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
void response.body?.cancel().catch(() => {});
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
const envelope = await readJson(response, 1_000_000);
|
|
289
|
+
const list = envelope?.result?.tools;
|
|
290
|
+
if (!Array.isArray(list)) return undefined;
|
|
291
|
+
const names = new Set(list.map((tool) => tool?.name).filter((name) => typeof name === 'string'));
|
|
292
|
+
this.#serverTools = { names, expiresAt: Date.now() + 60_000 };
|
|
293
|
+
return names;
|
|
294
|
+
} catch {
|
|
295
|
+
return undefined;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
218
299
|
#needLogin() {
|
|
219
300
|
if (this.#closed) return error('BI_SERVICE_UNAVAILABLE');
|
|
220
301
|
// 配置令牌模式下永不打开浏览器:空值/非法值都直接给出可操作的错误
|
|
@@ -222,23 +303,47 @@ export class PlatformClient {
|
|
|
222
303
|
return error('AUTH_REQUIRED', this.#envToken.error
|
|
223
304
|
?? '连接配置里的 MBI_ACCESS_TOKEN 已失效或已被撤销,请在 WorkBuddy 连接设置中更新后重连。');
|
|
224
305
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
306
|
+
const started = this.#startAuthorization();
|
|
307
|
+
return error('AUTH_REQUIRED', started
|
|
308
|
+
? '已在本机浏览器打开中台授权页:请登录并批准授权,完成后重新调用刚才的工具;不要自动轮询。'
|
|
309
|
+
: '中台授权窗口正在等待浏览器确认,完成后重新调用刚才的工具。');
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// 拉起独立的授权助手进程,本进程立即返回:宿主在工具调用结束后会回收 MCP 进程,
|
|
313
|
+
// 只有独立进程才能一直占用回调端口等到用户点完浏览器。
|
|
314
|
+
#startAuthorization() {
|
|
315
|
+
if (Date.now() - this.#lastStart < 10_000) return false;
|
|
316
|
+
this.#lastStart = Date.now();
|
|
317
|
+
const options = {
|
|
318
|
+
platformUrl: this.#platform?.platformUrl,
|
|
319
|
+
apiBasePath: this.#platform?.apiBasePath,
|
|
320
|
+
scope: this.#scope
|
|
321
|
+
};
|
|
322
|
+
void Promise.resolve()
|
|
323
|
+
.then(() => this.startAuth(options))
|
|
324
|
+
.catch((failure) => this.log(`[mbi-senseX-mcp] 中台授权未完成:${failure?.message ?? failure}`));
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// 授权可能由另一个进程(助手)完成,所以每次调用都回落读一次本地缓存
|
|
329
|
+
#currentGrant() {
|
|
330
|
+
// 配置令牌的有效期由平台决定,本地不做本地过期推断
|
|
331
|
+
if (this.#envToken?.token) return { token: this.#envToken.token, expiresAt: Number.POSITIVE_INFINITY };
|
|
332
|
+
const cached = this.#grant ?? this.#grantStore.load(this.#scope);
|
|
333
|
+
if (cached && Number.isInteger(cached.expiresAt) && cached.expiresAt > Date.now()) {
|
|
334
|
+
this.#grant = cached;
|
|
335
|
+
return cached;
|
|
231
336
|
}
|
|
232
|
-
|
|
233
|
-
|
|
337
|
+
this.#grant = undefined;
|
|
338
|
+
return undefined;
|
|
234
339
|
}
|
|
235
340
|
|
|
236
341
|
async call(name, args = {}) {
|
|
237
342
|
const validator = validators.get(name);
|
|
238
343
|
if (!validator || !validator(args)) return error('INVALID_ARGUMENT', describeInvalidArguments(name, validator));
|
|
239
344
|
if (this.#closed) return error('BI_SERVICE_UNAVAILABLE');
|
|
240
|
-
const grant = this.#
|
|
241
|
-
if (!grant
|
|
345
|
+
const grant = this.#currentGrant();
|
|
346
|
+
if (!grant) return this.#needLogin();
|
|
242
347
|
const id = ++this.#sequence;
|
|
243
348
|
try {
|
|
244
349
|
const response = await this.fetcher(this.urls.mcp, {
|
|
@@ -257,13 +362,29 @@ export class PlatformClient {
|
|
|
257
362
|
if (this.#grant === grant) { this.#grant = undefined; this.#grantStore.clear(); }
|
|
258
363
|
return error('AUTH_REQUIRED', '中台授权已失效;下次调用将重新打开登录。');
|
|
259
364
|
}
|
|
260
|
-
|
|
365
|
+
if (response.status === 429) return error('RATE_LIMITED', toolHints.get('RATE_LIMITED'));
|
|
366
|
+
return error('BI_SERVICE_UNAVAILABLE', `数据中台返回 HTTP ${response.status},请确认门户地址与网关路由可用。`);
|
|
261
367
|
}
|
|
262
368
|
const envelope = await readJson(response, 4_000_000);
|
|
263
|
-
|
|
369
|
+
if (envelope?.jsonrpc !== '2.0' || envelope.id !== id) {
|
|
370
|
+
return error('BI_SERVICE_UNAVAILABLE', '数据中台返回了无法识别的响应,请确认 MBI_PLATFORM_URL 指向平台门户而不是其它服务。');
|
|
371
|
+
}
|
|
372
|
+
// 协议级错误在 JSON-RPC 的 error 成员里(例如 Unknown tool / AUTH_REQUIRED),
|
|
373
|
+
// 这里只按已知错误码翻译成本地文案,绝不透传远端原文,避免把敏感信息带进模型上下文。
|
|
374
|
+
const rpcError = envelope.error;
|
|
375
|
+
if (rpcError) {
|
|
376
|
+
const remote = typeof rpcError.message === 'string' ? rpcError.message.trim() : '';
|
|
377
|
+
if (remote === 'Unknown tool') {
|
|
378
|
+
return error('TOOL_NOT_SUPPORTED',
|
|
379
|
+
'当前数据中台版本未启用该工具;请升级服务端,或改用 get_analysis_config、get_business_ontology、query_metrics。');
|
|
380
|
+
}
|
|
381
|
+
if (allowedErrors.has(remote)) return error(remote, toolHints.get(remote), rpcError.data?.requestId);
|
|
382
|
+
return error('BI_SERVICE_UNAVAILABLE', `数据中台返回协议错误(code=${rpcError.code ?? 'unknown'}),请稍后重试。`);
|
|
383
|
+
}
|
|
384
|
+
const result = envelope.result;
|
|
264
385
|
const data = result?.structuredContent;
|
|
265
|
-
if (
|
|
266
|
-
return error('BI_SERVICE_UNAVAILABLE');
|
|
386
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
387
|
+
return error('BI_SERVICE_UNAVAILABLE', '数据中台返回了空结果,请稍后重试。');
|
|
267
388
|
}
|
|
268
389
|
if (result.isError === true) {
|
|
269
390
|
const code = data.error?.code;
|
|
@@ -273,12 +394,15 @@ export class PlatformClient {
|
|
|
273
394
|
} else if (code !== 'AUTH_UNAVAILABLE') {
|
|
274
395
|
this.#extend(grant);
|
|
275
396
|
}
|
|
276
|
-
|
|
397
|
+
// 服务端工具错误只有错误码(ExternalBiMcpController.toolError 不带 message),
|
|
398
|
+
// 因此这里必须补一句可读原因,否则用户只看到 isError 而不知道该怎么办。
|
|
399
|
+
return error(allowedErrors.has(code) ? code : 'BI_SERVICE_UNAVAILABLE',
|
|
400
|
+
allowedErrors.has(code) ? toolHints.get(code) : '数据中台返回了未识别的错误,请稍后重试。', data.requestId);
|
|
277
401
|
}
|
|
278
|
-
if (result.isError !== false) return error('BI_SERVICE_UNAVAILABLE');
|
|
402
|
+
if (result.isError !== false) return error('BI_SERVICE_UNAVAILABLE', '数据中台返回了不完整的结果,请稍后重试。');
|
|
279
403
|
this.#extend(grant);
|
|
280
404
|
return message(data, false);
|
|
281
|
-
} catch { return error('BI_SERVICE_UNAVAILABLE'); }
|
|
405
|
+
} catch { return error('BI_SERVICE_UNAVAILABLE', '调用数据中台失败(网络或超时),请稍后重试。'); }
|
|
282
406
|
}
|
|
283
407
|
|
|
284
408
|
#extend(grant) {
|
|
@@ -301,7 +425,7 @@ export class PlatformSession {
|
|
|
301
425
|
|
|
302
426
|
constructor(env, { platformStore = persistentPlatformStore,
|
|
303
427
|
clientFactory = (urls, config, envToken) => new PlatformClient(urls,
|
|
304
|
-
{ scope: `${config.platformUrl}\n${config.apiBasePath}`, envToken }) } = {}) {
|
|
428
|
+
{ scope: `${config.platformUrl}\n${config.apiBasePath}`, envToken, platform: config }) } = {}) {
|
|
305
429
|
this.#env = env;
|
|
306
430
|
this.#envToken = resolveEnvToken(env);
|
|
307
431
|
this.#platformStore = platformStore;
|
|
@@ -348,6 +472,15 @@ export class PlatformSession {
|
|
|
348
472
|
return this.#client.call(name, args);
|
|
349
473
|
}
|
|
350
474
|
|
|
475
|
+
// 对外只宣称服务端真正支持的清单工具:线上服务端可能还是旧版本(例如只有 3 个工具),
|
|
476
|
+
// 若把清单里的工具全列出来,模型会去调用注定返回 Unknown tool 的工具。
|
|
477
|
+
async advertisedTools() {
|
|
478
|
+
if (!this.#client) return tools;
|
|
479
|
+
const names = await this.#client.serverToolNames();
|
|
480
|
+
if (!names) return tools;
|
|
481
|
+
return tools.filter((tool) => bridgeTools.has(tool.name) || names.has(tool.name));
|
|
482
|
+
}
|
|
483
|
+
|
|
351
484
|
async #configure(args) {
|
|
352
485
|
if (!args || typeof args.url !== 'string' || args.url.trim().length < 8 || args.url.length > 2048
|
|
353
486
|
|| args.apiBasePath !== undefined
|
package/src/index.js
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
3
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
4
|
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
-
import { PlatformSession
|
|
5
|
+
import { PlatformSession } from './client.js';
|
|
6
6
|
|
|
7
7
|
async function main() {
|
|
8
8
|
const session = new PlatformSession(process.env);
|
|
9
|
-
const server = new Server({ name: 'mbi-senseX', version: '0.2.
|
|
10
|
-
|
|
9
|
+
const server = new Server({ name: 'mbi-senseX', version: '0.2.7' }, { capabilities: { tools: {} } });
|
|
10
|
+
// 工具清单按服务端实际能力过滤,避免旧版服务端下模型调用注定失败的工具
|
|
11
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await session.advertisedTools() }));
|
|
11
12
|
server.setRequestHandler(CallToolRequestSchema, ({ params }) => session.call(params.name, params.arguments));
|
|
12
13
|
server.onerror = () => console.error('[mbi-senseX-mcp] MCP protocol error.');
|
|
13
14
|
server.onclose = () => session.close();
|
package/src/tool-manifest.json
CHANGED
|
@@ -271,7 +271,7 @@
|
|
|
271
271
|
},
|
|
272
272
|
{
|
|
273
273
|
"name": "call_agent_tool",
|
|
274
|
-
"description": "Execute an Agent Profile capability or an actual connector tool returned by get_agent_tools. Every call rechecks the current platform roles, Profile ACL and Profile capability allowlist. Reuse executionId for multi-step dashboard, delivery and plan state.",
|
|
274
|
+
"description": "Execute an Agent Profile capability or an actual connector tool returned by get_agent_tools. Every call rechecks the current platform roles, Profile ACL and Profile capability allowlist. Reuse executionId for multi-step dashboard, delivery and plan state. For mashup_board, follow contract -> validate -> prepare -> preflight -> verify -> publish; publish consumes the artifact_id returned by prepare and never accepts a fresh spec.",
|
|
275
275
|
"inputSchema": {
|
|
276
276
|
"type": "object",
|
|
277
277
|
"additionalProperties": false,
|