@miaocedata/mbi-bi-mcp 0.2.6 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miaocedata/mbi-bi-mcp",
3
- "version": "0.2.6",
3
+ "version": "0.2.8",
4
4
  "description": "Read-only stdio MCP adapter for authorized data platform deployments",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -0,0 +1,185 @@
1
+ #!/usr/bin/env node
2
+ // 授权助手:MCP 主进程缺少授权时把它拉起来,由它长期占用回调端口等待浏览器回调。
3
+ // 职责:固定端口接收回调 → 换取令牌 → 原子写入 grant.json → 退出。
4
+ // 之所以独立成进程:WorkBuddy 每次工具调用结束就回收沙箱会话并结束 MCP 进程,
5
+ // 授权若在 MCP 进程内等待,浏览器回调只会得到 ERR_CONNECTION_REFUSED。
6
+ // Windows 上优先交给任务计划程序启动:任务进程由系统服务派生,不在宿主的沙箱作业里,
7
+ // 宿主回收会话时不会连带结束它(detached 子进程仍会留在沙箱作业里被杀)。
8
+ import { appendFileSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
9
+ import { spawn, spawnSync } from 'node:child_process';
10
+ import { createServer } from 'node:http';
11
+ import { dirname, join } from 'node:path';
12
+ import { homedir } from 'node:os';
13
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
+ import { authorize, openBrowser, platformUrls } from './auth.js';
15
+
16
+ // 固定端口便于在浏览器里一眼看出是本机授权回调;端口被占用即视为已有助手在等回调
17
+ export const AUTH_HELPER_PORT = Number(process.env.MBI_AUTH_PORT ?? 18765);
18
+
19
+ const TASK_NAME = 'MBI-BI-Auth';
20
+ const STORE_DIR = join(homedir(), '.mbi-bi');
21
+ const GRANT_FILE = join(STORE_DIR, 'grant.json');
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');
25
+ const LOG_FILE = join(STORE_DIR, 'auth-helper.log');
26
+ // 与本进程等待窗口一致:超过这个时间没有回调,视为本轮授权失败
27
+ const TIMEOUT_MS = Number(process.env.MBI_AUTH_TIMEOUT_MS ?? 180_000);
28
+
29
+ function log(text) {
30
+ try {
31
+ mkdirSync(STORE_DIR, { recursive: true });
32
+ appendFileSync(LOG_FILE, `${new Date().toISOString()} [${process.pid}] ${text}\n`);
33
+ } catch {}
34
+ }
35
+
36
+ // 原子落盘:先写同目录临时文件再改名,避免读到只写了一半的 JSON
37
+ function writeAtomically(file, content) {
38
+ mkdirSync(dirname(file), { recursive: true });
39
+ const temp = `${file}.${process.pid}.tmp`;
40
+ writeFileSync(temp, content, { mode: 0o600 });
41
+ renameSync(temp, file);
42
+ }
43
+
44
+ // 锁文件表示「已有助手在等回调」,避免每次工具调用都新开一个授权窗口
45
+ function readLock() {
46
+ try {
47
+ const data = JSON.parse(readFileSync(LOCK_FILE, 'utf8'));
48
+ if (Number.isInteger(data?.pid) && Number.isInteger(data?.startedAt)
49
+ && Date.now() - data.startedAt < TIMEOUT_MS + 60_000) return data;
50
+ } catch {}
51
+ return undefined;
52
+ }
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
+
85
+ // 由 MCP 进程调用:已有助手在等就直接返回 pending,不再重复开浏览器
86
+ export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
87
+ const lock = readLock();
88
+ if (lock) return { started: false, pending: true, pid: lock.pid };
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], {
100
+ detached: true,
101
+ stdio: 'ignore',
102
+ windowsHide: true,
103
+ env: {
104
+ ...env,
105
+ ...(platformUrl ? { MBI_PLATFORM_URL: platformUrl } : {}),
106
+ ...(apiBasePath ? { MBI_API_BASE_PATH: apiBasePath } : {}),
107
+ ...(scope ? { MBI_GRANT_SCOPE: scope } : {}),
108
+ MBI_AUTH_PORT: String(AUTH_HELPER_PORT)
109
+ }
110
+ });
111
+ child.unref();
112
+ return { started: true, via: 'spawn', pid: child.pid };
113
+ }
114
+
115
+ // 先自己试绑一次固定端口:失败说明已有助手在跑,本进程直接退出,不碰对方的锁文件
116
+ async function ensurePortFree() {
117
+ const probe = createServer();
118
+ try {
119
+ await new Promise((resolve, reject) => {
120
+ probe.once('error', reject);
121
+ probe.listen(AUTH_HELPER_PORT, '127.0.0.1', resolve);
122
+ });
123
+ } finally {
124
+ await new Promise((resolve) => probe.close(resolve));
125
+ }
126
+ }
127
+
128
+ // 只有本进程真正写过锁文件,退出时才回收它,避免误删另一个助手的锁
129
+ let lockOwned = false;
130
+
131
+ async function main() {
132
+ const request = readRequest();
133
+ const scope = request?.scope ?? process.env.MBI_GRANT_SCOPE;
134
+ if (!scope) throw new Error('缺少 MBI_GRANT_SCOPE');
135
+ const urls = platformUrls(request
136
+ ? { MBI_PLATFORM_URL: request.platformUrl, MBI_API_BASE_PATH: request.apiBasePath }
137
+ : process.env);
138
+ await ensurePortFree();
139
+ writeAtomically(LOCK_FILE, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
140
+ lockOwned = true;
141
+ log(`start port=${AUTH_HELPER_PORT} consent=${urls.consent.href}`);
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
+ }
161
+ }
162
+
163
+ async function run() {
164
+ const grant = await main();
165
+ log(`grant saved expiresAt=${new Date(grant.expiresAt).toISOString()}`);
166
+ }
167
+
168
+ // 只有被直接执行时才运行助手逻辑;被 import 时仅导出 launchAuthHelper
169
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
170
+ run()
171
+ .catch((error) => {
172
+ if (error?.code === 'EADDRINUSE') {
173
+ log(`port ${AUTH_HELPER_PORT} 已被占用,已有助手在监听`);
174
+ } else {
175
+ log(`failed: ${error?.message ?? error}`);
176
+ process.exitCode = 1;
177
+ }
178
+ })
179
+ .finally(() => {
180
+ if (!lockOwned) return;
181
+ try {
182
+ rmSync(LOCK_FILE, { force: true });
183
+ } catch {}
184
+ });
185
+ }
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
- export async function authorize(urls, { launch = openBrowser, fetcher = fetch, timeoutMs = 300_000, signal } = {}) {
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, authorize, platformUrls, readJson } from './auth.js';
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
- #pending;
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 = authorize, log = (text) => console.error(text),
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
- void this.#needLogin();
260
+ const started = this.#startAuthorization();
253
261
  return message({
254
262
  reauthorized: true,
255
263
  revoked,
256
- loginPending: Boolean(this.#pending),
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
- if (!this.#pending && Date.now() - this.#lastStart >= 10_000) {
299
- this.#lastStart = Date.now();
300
- this.#pending = Promise.resolve().then(() => this.login(this.urls, { fetcher: this.fetcher, signal: this.#stop.signal }))
301
- .then((grant) => { if (!this.#closed) { this.#grant = grant; this.#grantStore.save(grant, this.#scope); } })
302
- .catch(() => { if (!this.#closed) this.log('[mbi-senseX-mcp] 中台授权未完成;请确认可打开系统浏览器,再重试工具。'); })
303
- .finally(() => { this.#pending = undefined; });
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
- return error('AUTH_REQUIRED', this.#pending ? '请在本机浏览器登录中台并批准授权,完成后由用户重试;不要自动轮询。'
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.#grant;
314
- if (!grant || Date.now() >= grant.expiresAt) return this.#needLogin();
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.6' }, { capabilities: { tools: {} } });
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));