@miaocedata/mbi-bi-mcp 0.2.7 → 0.2.8
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 +77 -21
- package/src/index.js +1 -1
package/package.json
CHANGED
package/src/auth-helper.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// 授权助手:MCP
|
|
3
|
-
//
|
|
4
|
-
//
|
|
2
|
+
// 授权助手:MCP 主进程缺少授权时把它拉起来,由它长期占用回调端口等待浏览器回调。
|
|
3
|
+
// 职责:固定端口接收回调 → 换取令牌 → 原子写入 grant.json → 退出。
|
|
4
|
+
// 之所以独立成进程:WorkBuddy 每次工具调用结束就回收沙箱会话并结束 MCP 进程,
|
|
5
5
|
// 授权若在 MCP 进程内等待,浏览器回调只会得到 ERR_CONNECTION_REFUSED。
|
|
6
|
+
// Windows 上优先交给任务计划程序启动:任务进程由系统服务派生,不在宿主的沙箱作业里,
|
|
7
|
+
// 宿主回收会话时不会连带结束它(detached 子进程仍会留在沙箱作业里被杀)。
|
|
6
8
|
import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
-
import { spawn } from 'node:child_process';
|
|
9
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
8
10
|
import { createServer } from 'node:http';
|
|
9
11
|
import { dirname, join } from 'node:path';
|
|
10
12
|
import { homedir } from 'node:os';
|
|
@@ -14,9 +16,12 @@ import { authorize, openBrowser, platformUrls } from './auth.js';
|
|
|
14
16
|
// 固定端口便于在浏览器里一眼看出是本机授权回调;端口被占用即视为已有助手在等回调
|
|
15
17
|
export const AUTH_HELPER_PORT = Number(process.env.MBI_AUTH_PORT ?? 18765);
|
|
16
18
|
|
|
19
|
+
const TASK_NAME = 'MBI-BI-Auth';
|
|
17
20
|
const STORE_DIR = join(homedir(), '.mbi-bi');
|
|
18
21
|
const GRANT_FILE = join(STORE_DIR, 'grant.json');
|
|
19
22
|
const LOCK_FILE = join(STORE_DIR, 'auth-helper.lock');
|
|
23
|
+
const REQUEST_FILE = join(STORE_DIR, 'auth-request.json');
|
|
24
|
+
const TASK_FILE = join(STORE_DIR, 'auth-task.json');
|
|
20
25
|
const LOG_FILE = join(STORE_DIR, 'auth-helper.log');
|
|
21
26
|
// 与本进程等待窗口一致:超过这个时间没有回调,视为本轮授权失败
|
|
22
27
|
const TIMEOUT_MS = Number(process.env.MBI_AUTH_TIMEOUT_MS ?? 180_000);
|
|
@@ -28,7 +33,7 @@ function log(text) {
|
|
|
28
33
|
} catch {}
|
|
29
34
|
}
|
|
30
35
|
|
|
31
|
-
//
|
|
36
|
+
// 原子落盘:先写同目录临时文件再改名,避免读到只写了一半的 JSON
|
|
32
37
|
function writeAtomically(file, content) {
|
|
33
38
|
mkdirSync(dirname(file), { recursive: true });
|
|
34
39
|
const temp = `${file}.${process.pid}.tmp`;
|
|
@@ -46,11 +51,52 @@ function readLock() {
|
|
|
46
51
|
return undefined;
|
|
47
52
|
}
|
|
48
53
|
|
|
54
|
+
// 计划任务拿不到主进程的环境变量,本轮参数(平台地址、scope)走请求文件传递
|
|
55
|
+
function readRequest() {
|
|
56
|
+
try {
|
|
57
|
+
const data = JSON.parse(readFileSync(REQUEST_FILE, 'utf8'));
|
|
58
|
+
if (typeof data?.platformUrl === 'string' && typeof data?.scope === 'string') return data;
|
|
59
|
+
} catch {}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function runSchTasks(args) {
|
|
64
|
+
return spawnSync('schtasks', args, { windowsHide: true, encoding: 'utf8' });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// 任务总是以绝对路径指向当前这份助手脚本;版本升级后路径变化会自动重建任务。
|
|
68
|
+
// schtasks 的输出会把长路径折行,所以用自己记录的任务路径判断,而不是匹配输出文本。
|
|
69
|
+
function ensureTask(helperPath) {
|
|
70
|
+
let recorded;
|
|
71
|
+
try {
|
|
72
|
+
recorded = JSON.parse(readFileSync(TASK_FILE, 'utf8'))?.helperPath;
|
|
73
|
+
} catch {}
|
|
74
|
+
if (recorded === helperPath && runSchTasks(['/query', '/tn', TASK_NAME]).status === 0) return true;
|
|
75
|
+
const action = `"${process.execPath}" "${helperPath}"`;
|
|
76
|
+
const create = runSchTasks(['/create', '/tn', TASK_NAME, '/tr', action, '/sc', 'once', '/st', '00:00', '/f']);
|
|
77
|
+
if (create.status !== 0) {
|
|
78
|
+
log(`create task failed: ${String(create.stderr || create.stdout).trim()}`);
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
writeAtomically(TASK_FILE, JSON.stringify({ helperPath }));
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
|
|
49
85
|
// 由 MCP 进程调用:已有助手在等就直接返回 pending,不再重复开浏览器
|
|
50
86
|
export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
|
|
51
87
|
const lock = readLock();
|
|
52
88
|
if (lock) return { started: false, pending: true, pid: lock.pid };
|
|
53
|
-
const
|
|
89
|
+
const helperPath = fileURLToPath(import.meta.url);
|
|
90
|
+
if (process.platform === 'win32' && platformUrl && scope) {
|
|
91
|
+
writeAtomically(REQUEST_FILE, JSON.stringify({ platformUrl, apiBasePath, scope }));
|
|
92
|
+
if (ensureTask(helperPath)) {
|
|
93
|
+
const run = runSchTasks(['/run', '/tn', TASK_NAME]);
|
|
94
|
+
if (run.status === 0) return { started: true, via: 'task' };
|
|
95
|
+
log(`run task failed: ${String(run.stderr || run.stdout).trim()}`);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
// 任务计划程序不可用时回退到 detached 子进程(在无沙箱的环境里同样可用)
|
|
99
|
+
const child = spawn(process.execPath, [helperPath], {
|
|
54
100
|
detached: true,
|
|
55
101
|
stdio: 'ignore',
|
|
56
102
|
windowsHide: true,
|
|
@@ -63,7 +109,7 @@ export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = proces
|
|
|
63
109
|
}
|
|
64
110
|
});
|
|
65
111
|
child.unref();
|
|
66
|
-
return { started: true, pid: child.pid };
|
|
112
|
+
return { started: true, via: 'spawn', pid: child.pid };
|
|
67
113
|
}
|
|
68
114
|
|
|
69
115
|
// 先自己试绑一次固定端口:失败说明已有助手在跑,本进程直接退出,不碰对方的锁文件
|
|
@@ -83,25 +129,35 @@ async function ensurePortFree() {
|
|
|
83
129
|
let lockOwned = false;
|
|
84
130
|
|
|
85
131
|
async function main() {
|
|
86
|
-
const
|
|
132
|
+
const request = readRequest();
|
|
133
|
+
const scope = request?.scope ?? process.env.MBI_GRANT_SCOPE;
|
|
87
134
|
if (!scope) throw new Error('缺少 MBI_GRANT_SCOPE');
|
|
88
|
-
const urls = platformUrls(
|
|
135
|
+
const urls = platformUrls(request
|
|
136
|
+
? { MBI_PLATFORM_URL: request.platformUrl, MBI_API_BASE_PATH: request.apiBasePath }
|
|
137
|
+
: process.env);
|
|
89
138
|
await ensurePortFree();
|
|
90
139
|
writeAtomically(LOCK_FILE, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
|
|
91
140
|
lockOwned = true;
|
|
92
141
|
log(`start port=${AUTH_HELPER_PORT} consent=${urls.consent.href}`);
|
|
93
|
-
//
|
|
94
|
-
const
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
log(`
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
142
|
+
// 心跳用于判断助手是否被宿主提前结束:日志里有没有后续 waiting 一看就知道
|
|
143
|
+
const heartbeat = setInterval(() => log('waiting for browser callback'), 10_000);
|
|
144
|
+
heartbeat.unref();
|
|
145
|
+
try {
|
|
146
|
+
// 浏览器打不开不是致命错误:授权地址同时写进日志,用户可手工打开
|
|
147
|
+
const launch = async (uri) => {
|
|
148
|
+
log(`authorize url: ${uri.href}`);
|
|
149
|
+
try {
|
|
150
|
+
await openBrowser(uri);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
log(`open browser failed: ${error?.message ?? error}`);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const grant = await authorize(urls, { port: AUTH_HELPER_PORT, timeoutMs: TIMEOUT_MS, launch });
|
|
156
|
+
writeAtomically(GRANT_FILE, JSON.stringify({ ...grant, platformScope: scope }));
|
|
157
|
+
return grant;
|
|
158
|
+
} finally {
|
|
159
|
+
clearInterval(heartbeat);
|
|
160
|
+
}
|
|
105
161
|
}
|
|
106
162
|
|
|
107
163
|
async function run() {
|
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.8' }, { 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));
|