@miaocedata/mbi-bi-mcp 0.2.7 → 0.2.9

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.7",
3
+ "version": "0.2.9",
4
4
  "description": "Read-only stdio MCP adapter for authorized data platform deployments",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -1,10 +1,12 @@
1
1
  #!/usr/bin/env node
2
- // 授权助手:MCP 主进程缺少授权时用 detached 方式拉起本文件,本进程独立于宿主会话存活。
3
- // 职责:固定端口接收浏览器回调 → 换取令牌 → 原子写入 grant.json → 退出。
4
- // 独立成进程的原因:WorkBuddy 每次工具调用结束就回收沙箱会话并结束 MCP 进程,
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,14 @@ 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');
25
+ // 最近一次授权链接:浏览器没自动打开时,工具返回里可以直接给用户点
26
+ const AUTH_URL_FILE = join(STORE_DIR, 'auth-url.txt');
20
27
  const LOG_FILE = join(STORE_DIR, 'auth-helper.log');
21
28
  // 与本进程等待窗口一致:超过这个时间没有回调,视为本轮授权失败
22
29
  const TIMEOUT_MS = Number(process.env.MBI_AUTH_TIMEOUT_MS ?? 180_000);
@@ -28,7 +35,7 @@ function log(text) {
28
35
  } catch {}
29
36
  }
30
37
 
31
- // 原子落盘:先写同目录临时文件再改名,避免宿主读到只写了一半的 JSON
38
+ // 原子落盘:先写同目录临时文件再改名,避免读到只写了一半的 JSON
32
39
  function writeAtomically(file, content) {
33
40
  mkdirSync(dirname(file), { recursive: true });
34
41
  const temp = `${file}.${process.pid}.tmp`;
@@ -46,11 +53,81 @@ function readLock() {
46
53
  return undefined;
47
54
  }
48
55
 
56
+ // 计划任务拿不到主进程的环境变量,本轮参数(平台地址、scope)走请求文件传递
57
+ function readRequest() {
58
+ try {
59
+ const data = JSON.parse(readFileSync(REQUEST_FILE, 'utf8'));
60
+ if (typeof data?.platformUrl === 'string' && typeof data?.scope === 'string') return data;
61
+ } catch {}
62
+ return undefined;
63
+ }
64
+
65
+ function runSchTasks(args, timeoutMs = 10_000) {
66
+ // 异步执行并带超时:schtasks 一旦卡住(沙箱拦截、RPC 无响应),
67
+ // 同步等待会把工具调用一起拖死,用户会看到「点了半天没反应」。
68
+ return new Promise((resolve) => {
69
+ let child;
70
+ try {
71
+ child = spawn('schtasks', args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
72
+ } catch (failure) {
73
+ resolve({ status: null, stdout: '', stderr: String(failure?.message ?? failure) });
74
+ return;
75
+ }
76
+ let stdout = '';
77
+ let stderr = '';
78
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
79
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
80
+ const timer = setTimeout(() => {
81
+ child.kill();
82
+ resolve({ status: null, stdout, stderr: `${stderr} timeout`.trim() });
83
+ }, timeoutMs);
84
+ child.once('error', (failure) => {
85
+ clearTimeout(timer);
86
+ resolve({ status: null, stdout, stderr: String(failure?.message ?? failure) });
87
+ });
88
+ child.once('close', (code) => {
89
+ clearTimeout(timer);
90
+ resolve({ status: code, stdout, stderr });
91
+ });
92
+ });
93
+ }
94
+
95
+ // 任务总是以绝对路径指向当前这份助手脚本;版本升级后路径变化会自动重建任务。
96
+ // schtasks 的输出会把长路径折行,所以用自己记录的任务路径判断,而不是匹配输出文本。
97
+ async function ensureTask(helperPath) {
98
+ let recorded;
99
+ try {
100
+ recorded = JSON.parse(readFileSync(TASK_FILE, 'utf8'))?.helperPath;
101
+ } catch {}
102
+ if (recorded === helperPath) {
103
+ const query = await runSchTasks(['/query', '/tn', TASK_NAME]);
104
+ if (query.status === 0) return true;
105
+ }
106
+ const action = `"${process.execPath}" "${helperPath}"`;
107
+ const create = await runSchTasks(['/create', '/tn', TASK_NAME, '/tr', action, '/sc', 'once', '/st', '00:00', '/f']);
108
+ if (create.status !== 0) {
109
+ log(`create task failed: ${String(create.stderr || create.stdout).trim()}`);
110
+ return false;
111
+ }
112
+ writeAtomically(TASK_FILE, JSON.stringify({ helperPath }));
113
+ return true;
114
+ }
115
+
49
116
  // 由 MCP 进程调用:已有助手在等就直接返回 pending,不再重复开浏览器
50
- export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
117
+ export async function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
51
118
  const lock = readLock();
52
119
  if (lock) return { started: false, pending: true, pid: lock.pid };
53
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
120
+ const helperPath = fileURLToPath(import.meta.url);
121
+ if (process.platform === 'win32' && platformUrl && scope) {
122
+ writeAtomically(REQUEST_FILE, JSON.stringify({ platformUrl, apiBasePath, scope }));
123
+ if (await ensureTask(helperPath)) {
124
+ const run = await runSchTasks(['/run', '/tn', TASK_NAME]);
125
+ if (run.status === 0) return { started: true, via: 'task' };
126
+ log(`run task failed: ${String(run.stderr || run.stdout).trim()}`);
127
+ }
128
+ }
129
+ // 任务计划程序不可用时回退到 detached 子进程(在无沙箱的环境里同样可用)
130
+ const child = spawn(process.execPath, [helperPath], {
54
131
  detached: true,
55
132
  stdio: 'ignore',
56
133
  windowsHide: true,
@@ -63,7 +140,7 @@ export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = proces
63
140
  }
64
141
  });
65
142
  child.unref();
66
- return { started: true, pid: child.pid };
143
+ return { started: true, via: 'spawn', pid: child.pid };
67
144
  }
68
145
 
69
146
  // 先自己试绑一次固定端口:失败说明已有助手在跑,本进程直接退出,不碰对方的锁文件
@@ -83,25 +160,36 @@ async function ensurePortFree() {
83
160
  let lockOwned = false;
84
161
 
85
162
  async function main() {
86
- const scope = process.env.MBI_GRANT_SCOPE;
163
+ const request = readRequest();
164
+ const scope = request?.scope ?? process.env.MBI_GRANT_SCOPE;
87
165
  if (!scope) throw new Error('缺少 MBI_GRANT_SCOPE');
88
- const urls = platformUrls(process.env);
166
+ const urls = platformUrls(request
167
+ ? { MBI_PLATFORM_URL: request.platformUrl, MBI_API_BASE_PATH: request.apiBasePath }
168
+ : process.env);
89
169
  await ensurePortFree();
90
170
  writeAtomically(LOCK_FILE, JSON.stringify({ pid: process.pid, startedAt: Date.now() }));
91
171
  lockOwned = true;
92
172
  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;
173
+ // 心跳用于判断助手是否被宿主提前结束:日志里有没有后续 waiting 一看就知道
174
+ const heartbeat = setInterval(() => log('waiting for browser callback'), 5_000);
175
+ heartbeat.unref();
176
+ try {
177
+ // 浏览器打不开不是致命错误:授权地址同时写进日志和 auth-url.txt,用户可手工打开
178
+ const launch = async (uri) => {
179
+ log(`authorize url: ${uri.href}`);
180
+ writeAtomically(AUTH_URL_FILE, JSON.stringify({ url: uri.href, at: Date.now() }));
181
+ try {
182
+ await openBrowser(uri);
183
+ } catch (error) {
184
+ log(`open browser failed: ${error?.message ?? error}`);
185
+ }
186
+ };
187
+ const grant = await authorize(urls, { port: AUTH_HELPER_PORT, timeoutMs: TIMEOUT_MS, launch });
188
+ writeAtomically(GRANT_FILE, JSON.stringify({ ...grant, platformScope: scope }));
189
+ return grant;
190
+ } finally {
191
+ clearInterval(heartbeat);
192
+ }
105
193
  }
106
194
 
107
195
  async function run() {
@@ -109,8 +197,26 @@ async function run() {
109
197
  log(`grant saved expiresAt=${new Date(grant.expiresAt).toISOString()}`);
110
198
  }
111
199
 
200
+ // 读取最近一次授权链接:浏览器没自动打开时,MCP 在提示里带上它让用户手工点开
201
+ export function readLastAuthorizeUrl() {
202
+ try {
203
+ const data = JSON.parse(readFileSync(AUTH_URL_FILE, 'utf8'));
204
+ const fresh = Number.isInteger(data?.at) && Date.now() - data.at < 600_000;
205
+ if (typeof data?.url === 'string' && fresh) return data.url;
206
+ } catch {}
207
+ return undefined;
208
+ }
209
+
112
210
  // 只有被直接执行时才运行助手逻辑;被 import 时仅导出 launchAuthHelper
113
211
  if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
212
+ // 被强制结束(宿主杀进程、控制台关闭、注销)时留下最后一行,便于事后分辨死法
213
+ process.once('exit', (code) => log(`exit code=${code}`));
214
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK']) {
215
+ process.on(signal, () => {
216
+ log(`signal ${signal}`);
217
+ process.exit(130);
218
+ });
219
+ }
114
220
  run()
115
221
  .catch((error) => {
116
222
  if (error?.code === 'EADDRINUSE') {
package/src/client.js CHANGED
@@ -3,7 +3,7 @@ import { dirname, join } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import Ajv from 'ajv';
5
5
  import { ACCESS_TOKEN_SECONDS, CLIENT_ID, platformUrls, readJson } from './auth.js';
6
- import { launchAuthHelper } from './auth-helper.js';
6
+ import { launchAuthHelper, readLastAuthorizeUrl } from './auth-helper.js';
7
7
 
8
8
  export const configurationTool = {
9
9
  name: 'configure_platform',
@@ -35,6 +35,12 @@ export const reauthorizeTool = {
35
35
  const jvmTools = JSON.parse(readFileSync(new URL('./tool-manifest.json', import.meta.url), 'utf8'));
36
36
  export const tools = [configurationTool, reauthorizeTool, ...jvmTools];
37
37
  // 本地桥接器自带的两个工具,与服务端清单无关,始终对模型可见
38
+ // 浏览器可能没被自动拉起:把最近一次授权链接附在提示后面,用户可以直接点开
39
+ function readLastAuthorizeUrlSuffix() {
40
+ const url = readLastAuthorizeUrl();
41
+ return url ? `\n若浏览器未自动打开,请手动访问:${url}` : '';
42
+ }
43
+
38
44
  const bridgeTools = new Set([configurationTool.name, reauthorizeTool.name]);
39
45
  const ajv = new Ajv({ strict: true });
40
46
  const validators = new Map(tools.map(({ name, inputSchema }) => [name, ajv.compile(inputSchema)]));
@@ -305,7 +311,7 @@ export class PlatformClient {
305
311
  }
306
312
  const started = this.#startAuthorization();
307
313
  return error('AUTH_REQUIRED', started
308
- ? '已在本机浏览器打开中台授权页:请登录并批准授权,完成后重新调用刚才的工具;不要自动轮询。'
314
+ ? `已在本机浏览器打开中台授权页:请登录并批准授权,完成后重新调用刚才的工具;不要自动轮询。${readLastAuthorizeUrlSuffix()}`
309
315
  : '中台授权窗口正在等待浏览器确认,完成后重新调用刚才的工具。');
310
316
  }
311
317
 
package/src/index.js CHANGED
@@ -1,4 +1,4 @@
1
- #!/usr/bin/env node
1
+ #!/usr/bin/env node
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';
@@ -6,8 +6,8 @@ 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.7' }, { capabilities: { tools: {} } });
10
- // 工具清单按服务端实际能力过滤,避免旧版服务端下模型调用注定失败的工具
9
+ const server = new Server({ name: 'mbi-senseX', version: '0.2.9' }, { capabilities: { tools: {} } });
10
+ // 宸ュ叿娓呭崟鎸夋湇鍔$瀹為檯鑳藉姏杩囨护锛岄伩鍏嶆棫鐗堟湇鍔$涓嬫ā鍨嬭皟鐢ㄦ敞瀹氬け璐ョ殑宸ュ叿
11
11
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await session.advertisedTools() }));
12
12
  server.setRequestHandler(CallToolRequestSchema, ({ params }) => session.call(params.name, params.arguments));
13
13
  server.onerror = () => console.error('[mbi-senseX-mcp] MCP protocol error.');
@@ -21,6 +21,6 @@ async function main() {
21
21
  }
22
22
 
23
23
  main().catch(() => {
24
- console.error('[mbi-senseX-mcp] 启动失败。请检查 MBI_PLATFORM_URL(http 或 https 门户地址)、MBI_API_BASE_PATH,并确认地址里没有空格、问号或井号。');
24
+ console.error('[mbi-senseX-mcp] 鍚姩澶辫触銆傝妫€鏌?MBI_PLATFORM_URL锛坔ttp 鎴?https 闂ㄦ埛鍦板潃锛夈€丮BI_API_BASE_PATH锛屽苟纭鍦板潃閲屾病鏈夌┖鏍笺€侀棶鍙锋垨浜曞彿銆?);
25
25
  process.exitCode = 1;
26
26
  });