@miaocedata/mbi-bi-mcp 0.2.8 → 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.8",
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",
@@ -22,6 +22,8 @@ const GRANT_FILE = join(STORE_DIR, 'grant.json');
22
22
  const LOCK_FILE = join(STORE_DIR, 'auth-helper.lock');
23
23
  const REQUEST_FILE = join(STORE_DIR, 'auth-request.json');
24
24
  const TASK_FILE = join(STORE_DIR, 'auth-task.json');
25
+ // 最近一次授权链接:浏览器没自动打开时,工具返回里可以直接给用户点
26
+ const AUTH_URL_FILE = join(STORE_DIR, 'auth-url.txt');
25
27
  const LOG_FILE = join(STORE_DIR, 'auth-helper.log');
26
28
  // 与本进程等待窗口一致:超过这个时间没有回调,视为本轮授权失败
27
29
  const TIMEOUT_MS = Number(process.env.MBI_AUTH_TIMEOUT_MS ?? 180_000);
@@ -60,20 +62,49 @@ function readRequest() {
60
62
  return undefined;
61
63
  }
62
64
 
63
- function runSchTasks(args) {
64
- return spawnSync('schtasks', args, { windowsHide: true, encoding: 'utf8' });
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
+ });
65
93
  }
66
94
 
67
95
  // 任务总是以绝对路径指向当前这份助手脚本;版本升级后路径变化会自动重建任务。
68
96
  // schtasks 的输出会把长路径折行,所以用自己记录的任务路径判断,而不是匹配输出文本。
69
- function ensureTask(helperPath) {
97
+ async function ensureTask(helperPath) {
70
98
  let recorded;
71
99
  try {
72
100
  recorded = JSON.parse(readFileSync(TASK_FILE, 'utf8'))?.helperPath;
73
101
  } catch {}
74
- if (recorded === helperPath && runSchTasks(['/query', '/tn', TASK_NAME]).status === 0) return true;
102
+ if (recorded === helperPath) {
103
+ const query = await runSchTasks(['/query', '/tn', TASK_NAME]);
104
+ if (query.status === 0) return true;
105
+ }
75
106
  const action = `"${process.execPath}" "${helperPath}"`;
76
- const create = runSchTasks(['/create', '/tn', TASK_NAME, '/tr', action, '/sc', 'once', '/st', '00:00', '/f']);
107
+ const create = await runSchTasks(['/create', '/tn', TASK_NAME, '/tr', action, '/sc', 'once', '/st', '00:00', '/f']);
77
108
  if (create.status !== 0) {
78
109
  log(`create task failed: ${String(create.stderr || create.stdout).trim()}`);
79
110
  return false;
@@ -83,14 +114,14 @@ function ensureTask(helperPath) {
83
114
  }
84
115
 
85
116
  // 由 MCP 进程调用:已有助手在等就直接返回 pending,不再重复开浏览器
86
- export function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
117
+ export async function launchAuthHelper({ platformUrl, apiBasePath, scope, env = process.env } = {}) {
87
118
  const lock = readLock();
88
119
  if (lock) return { started: false, pending: true, pid: lock.pid };
89
120
  const helperPath = fileURLToPath(import.meta.url);
90
121
  if (process.platform === 'win32' && platformUrl && scope) {
91
122
  writeAtomically(REQUEST_FILE, JSON.stringify({ platformUrl, apiBasePath, scope }));
92
- if (ensureTask(helperPath)) {
93
- const run = runSchTasks(['/run', '/tn', TASK_NAME]);
123
+ if (await ensureTask(helperPath)) {
124
+ const run = await runSchTasks(['/run', '/tn', TASK_NAME]);
94
125
  if (run.status === 0) return { started: true, via: 'task' };
95
126
  log(`run task failed: ${String(run.stderr || run.stdout).trim()}`);
96
127
  }
@@ -140,12 +171,13 @@ async function main() {
140
171
  lockOwned = true;
141
172
  log(`start port=${AUTH_HELPER_PORT} consent=${urls.consent.href}`);
142
173
  // 心跳用于判断助手是否被宿主提前结束:日志里有没有后续 waiting 一看就知道
143
- const heartbeat = setInterval(() => log('waiting for browser callback'), 10_000);
174
+ const heartbeat = setInterval(() => log('waiting for browser callback'), 5_000);
144
175
  heartbeat.unref();
145
176
  try {
146
- // 浏览器打不开不是致命错误:授权地址同时写进日志,用户可手工打开
177
+ // 浏览器打不开不是致命错误:授权地址同时写进日志和 auth-url.txt,用户可手工打开
147
178
  const launch = async (uri) => {
148
179
  log(`authorize url: ${uri.href}`);
180
+ writeAtomically(AUTH_URL_FILE, JSON.stringify({ url: uri.href, at: Date.now() }));
149
181
  try {
150
182
  await openBrowser(uri);
151
183
  } catch (error) {
@@ -165,8 +197,26 @@ async function run() {
165
197
  log(`grant saved expiresAt=${new Date(grant.expiresAt).toISOString()}`);
166
198
  }
167
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
+
168
210
  // 只有被直接执行时才运行助手逻辑;被 import 时仅导出 launchAuthHelper
169
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
+ }
170
220
  run()
171
221
  .catch((error) => {
172
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.8' }, { 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
  });