@miaocedata/mbi-bi-mcp 0.2.6 → 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/package.json +1 -1
- package/src/auth-helper.js +129 -0
- package/src/auth.js +4 -2
- package/src/client.js +50 -18
- package/src/index.js +1 -1
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',
|
|
@@ -185,22 +186,29 @@ export class PlatformClient {
|
|
|
185
186
|
#grantStore;
|
|
186
187
|
#scope;
|
|
187
188
|
#envToken;
|
|
188
|
-
#
|
|
189
|
+
#platform;
|
|
189
190
|
#lastStart = 0;
|
|
190
191
|
#sequence = 0;
|
|
191
192
|
#stop = new AbortController();
|
|
192
193
|
#closed = false;
|
|
193
194
|
#serverTools;
|
|
194
195
|
|
|
195
|
-
constructor(urls, { fetcher = fetch, login
|
|
196
|
-
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 } = {}) {
|
|
197
198
|
this.urls = urls;
|
|
198
199
|
this.fetcher = fetcher;
|
|
199
|
-
this.login = login;
|
|
200
200
|
this.log = log;
|
|
201
201
|
this.#grantStore = grantStore;
|
|
202
202
|
this.#scope = scope;
|
|
203
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));
|
|
204
212
|
// 配置里的令牌有效时直接采用,并完全忽略本机缓存文件里的旧令牌
|
|
205
213
|
this.#grant = envToken?.token
|
|
206
214
|
? { token: envToken.token, expiresAt: Number.POSITIVE_INFINITY }
|
|
@@ -249,11 +257,11 @@ export class PlatformClient {
|
|
|
249
257
|
await this.revokeCurrent();
|
|
250
258
|
// 重置频控,保证刚清完授权就能重新打开浏览器
|
|
251
259
|
this.#lastStart = 0;
|
|
252
|
-
|
|
260
|
+
const started = this.#startAuthorization();
|
|
253
261
|
return message({
|
|
254
262
|
reauthorized: true,
|
|
255
263
|
revoked,
|
|
256
|
-
loginPending:
|
|
264
|
+
loginPending: started,
|
|
257
265
|
platformUrl: this.urls.consent.origin,
|
|
258
266
|
hint: '已在浏览器打开授权页。请用中台账号登录并批准授权,完成后重新调用目标工具。'
|
|
259
267
|
}, false);
|
|
@@ -295,23 +303,47 @@ export class PlatformClient {
|
|
|
295
303
|
return error('AUTH_REQUIRED', this.#envToken.error
|
|
296
304
|
?? '连接配置里的 MBI_ACCESS_TOKEN 已失效或已被撤销,请在 WorkBuddy 连接设置中更新后重连。');
|
|
297
305
|
}
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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;
|
|
304
336
|
}
|
|
305
|
-
|
|
306
|
-
|
|
337
|
+
this.#grant = undefined;
|
|
338
|
+
return undefined;
|
|
307
339
|
}
|
|
308
340
|
|
|
309
341
|
async call(name, args = {}) {
|
|
310
342
|
const validator = validators.get(name);
|
|
311
343
|
if (!validator || !validator(args)) return error('INVALID_ARGUMENT', describeInvalidArguments(name, validator));
|
|
312
344
|
if (this.#closed) return error('BI_SERVICE_UNAVAILABLE');
|
|
313
|
-
const grant = this.#
|
|
314
|
-
if (!grant
|
|
345
|
+
const grant = this.#currentGrant();
|
|
346
|
+
if (!grant) return this.#needLogin();
|
|
315
347
|
const id = ++this.#sequence;
|
|
316
348
|
try {
|
|
317
349
|
const response = await this.fetcher(this.urls.mcp, {
|
|
@@ -393,7 +425,7 @@ export class PlatformSession {
|
|
|
393
425
|
|
|
394
426
|
constructor(env, { platformStore = persistentPlatformStore,
|
|
395
427
|
clientFactory = (urls, config, envToken) => new PlatformClient(urls,
|
|
396
|
-
{ scope: `${config.platformUrl}\n${config.apiBasePath}`, envToken }) } = {}) {
|
|
428
|
+
{ scope: `${config.platformUrl}\n${config.apiBasePath}`, envToken, platform: config }) } = {}) {
|
|
397
429
|
this.#env = env;
|
|
398
430
|
this.#envToken = resolveEnvToken(env);
|
|
399
431
|
this.#platformStore = platformStore;
|
package/src/index.js
CHANGED
|
@@ -6,7 +6,7 @@ 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.
|
|
9
|
+
const server = new Server({ name: 'mbi-senseX', version: '0.2.7' }, { capabilities: { tools: {} } });
|
|
10
10
|
// 工具清单按服务端实际能力过滤,避免旧版服务端下模型调用注定失败的工具
|
|
11
11
|
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await session.advertisedTools() }));
|
|
12
12
|
server.setRequestHandler(CallToolRequestSchema, ({ params }) => session.call(params.name, params.arguments));
|