@miaocedata/mbi-bi-mcp 0.0.0-stage → 0.1.0
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/README.md +72 -3
- package/package.json +25 -6
- package/src/auth.js +245 -0
- package/src/client.js +292 -0
- package/src/index.js +25 -0
- package/src/magic-data-mark.png +0 -0
- package/src/tool-manifest.json +224 -0
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# 数据中台 BI MCP · 本地连接器
|
|
2
|
+
|
|
3
|
+
这是 Node.js 22+ 的 **stdio** MCP。它不会连接 Qlik,也不运行 Sense X Agent。它向客户数据中台发起 HTTPS 请求,提供 `configure_platform`(设置/切换地址)、`get_analysis_config`(分析配置)、`get_business_ontology`(已发布本体)和 `query_metrics`(已登记指标查询)。客户须部署中台、持有有效 License,由中台管理员启用该租户的「外部问数」,再使用有资源权限的中台账号授权。无需单独签发 WorkBuddy License。
|
|
4
|
+
|
|
5
|
+
## 本地联调(无需 npm 发布)
|
|
6
|
+
|
|
7
|
+
在本包目录运行 `npm ci`、`npm test`。在宿主 MCP 配置中加入以下服务(路径替换成实际绝对路径;`node` 需在宿主的 PATH 中):
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"mcpServers": {
|
|
12
|
+
"mbi-senseX": {
|
|
13
|
+
"command": "node",
|
|
14
|
+
"args": ["D:/path/to/mbi-external-bi-mcp/src/index.js"],
|
|
15
|
+
"env": {
|
|
16
|
+
"MBI_PLATFORM_URL": "https://bi.example.com"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- **WorkBuddy**:先用本地 stdio 配置联调。`connector/mcp.json` 是 npm 包发布后的提审配置示例,不是已确认的市场包格式;应在提审前用 WorkBuddy 的实际版本验证配置、首次授权和重试行为。
|
|
24
|
+
- **Claude Code**:同形状 JSON 可配置到项目 `.mcp.json`;不要把客户实际地址提交到公开仓库。也可使用本机用户级 MCP 配置。
|
|
25
|
+
- **Codex**:本地 `config.toml` 使用下列配置。云端运行环境不在本次支持范围内。
|
|
26
|
+
|
|
27
|
+
```toml
|
|
28
|
+
[mcp_servers.mbi-senseX]
|
|
29
|
+
command = "node"
|
|
30
|
+
args = ["D:/path/to/mbi-external-bi-mcp/src/index.js"]
|
|
31
|
+
|
|
32
|
+
[mcp_servers.mbi-senseX.env]
|
|
33
|
+
MBI_PLATFORM_URL = "https://bi.example.com"
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**标准部署只填 `MBI_PLATFORM_URL`。** 它是门户 HTTPS 地址(可含门户路径),`MBI_API_BASE_PATH` 是同源 API 前缀(默认 `/prod-api`,网关直接挂在同源根路径时设为空字符串)。浏览器须与连接器运行在同一台主机,且两者均可通过客户网络访问门户;不要关闭 TLS 校验。
|
|
37
|
+
|
|
38
|
+
**也可以完全通过会话配置地址。** 用户明确说出门户地址后,Agent 调用 `configure_platform`;地址保存在本机 `~/.mbi-senseX/platform.json`,之后无需编辑宿主 `mcp.json`。示例:
|
|
39
|
+
|
|
40
|
+
```text
|
|
41
|
+
把数据中台地址配置为 https://bi.example.com
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
非标准网关前缀可在同一次配置中传 `apiBasePath`。切换地址会关闭旧地址的本地连接、尽力撤销旧 access token,并清除旧授权;新地址仍需重新登录授权。`MBI_PLATFORM_URL` 和 `MBI_API_BASE_PATH` 现在只作为首次启动时的默认值,已通过会话保存的地址优先。
|
|
45
|
+
|
|
46
|
+
如果本机验收环境暂时没有 HTTPS,可以显式设置 `MBI_ALLOW_INSECURE_LOCALHOST=true`,并只把 `MBI_PLATFORM_URL` 指向 `localhost`、`127.0.0.1` 或 `::1`。服务端 `mbi-auth` 的 `dev` profile 对应启用 `mbi.auth.bi.allow-insecure-localhost=true`;该开关不会允许局域网 IP 或其他主机,仅用于同一台电脑上的开发联调。客户正式环境仍必须使用 HTTPS。
|
|
47
|
+
|
|
48
|
+
```json
|
|
49
|
+
{
|
|
50
|
+
"env": {
|
|
51
|
+
"MBI_PLATFORM_URL": "http://127.0.0.1:8080",
|
|
52
|
+
"MBI_ALLOW_INSECURE_LOCALHOST": "true",
|
|
53
|
+
"MBI_API_BASE_PATH": "/prod-api"
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
首次调用工具会打开浏览器。用中台账号登录,确认租户并点击批准,看到成功提示后在宿主重试同一工具。连接器把令牌缓存到本机用户目录 `~/.mbi-bi/grant.json`(POSIX 上以 0600 权限创建;Windows 位于当前用户配置文件目录下),令牌初始有效期为 7 天,并在每次成功使用时自动重新计算 7 天;进程重启后自动从该文件恢复未过期令牌。只有连续 7 天未使用或服务端判定失效(401)时才重新授权并要求批准。用户可以在门户 `/external-bi/connections` 撤销当前账号在当前租户下的全部 BI MCP 连接;撤销后本地缓存会在下一次请求被服务端拒绝时清除。连接器不要求提供 Qlik 凭证、中台密码或 Web token。
|
|
59
|
+
|
|
60
|
+
## 查询语义和版本
|
|
61
|
+
|
|
62
|
+
1. 用 `get_analysis_config` 查业务 ID 和 `semanticVersion`;如要应用本体,用 `get_business_ontology` 查该 App 的生产 ACTIVE 发布,复制其中的 `ontologyVersion`(即 `releaseId`)。读跨 App 本体需要所有依赖 App 的权限,不能据此做跨 App 聚合或 JOIN。
|
|
63
|
+
2. `query_metrics` 每次只查询一个 App。要限定日期,例如传 `dateRange: { "dimensionId": "205", "from": "2026-10-01", "toExclusive": "2026-11-01" }`。起日包含,止日不包含,最多 366 天。用配置中 `dateRangeSupported` 的真实日历维度;有多个时明确指定,不能用字段名或表达式。
|
|
64
|
+
3. 中台校验实际日期选择和指定版本的本体规则。不能安全应用筛选、版本无权访问或存在未支持的约束时,工具返回错误;不要移除用户要求的约束重试。旧服务端不支持这些新参数,本地连接器和中台各服务应按 [部署与验收](../mbi-agent-service/docs/50-external-bi-mcp-deployment.md) 配套升级。
|
|
65
|
+
|
|
66
|
+
## 打包与上架
|
|
67
|
+
|
|
68
|
+
运行 `npm pack --dry-run` 检查文件,再运行 `npm publish --access public` 发布到 `@miaocedata/mbi-bi-mcp@0.1.0`(发布前需在 npmjs.com 拥有 `miaocedata` 组织,否则会报 `404 Scope not found`),市场包用 `connector/mcp.json` 里固定的版本号启动。后续每次升级必须先递增 `package.json` 的版本号再发布,并同步修改 `connector/mcp.json` 与 `connector/connector-meta.json` 里的版本号;只向 WorkBuddy 提交所需连接器材料,不把中台服务、Python connector、客户地址或任何凭证打进市场包。
|
|
69
|
+
|
|
70
|
+
> **提审前须知(本地定制)**:当前 `src/client.js` 将滑动 7 天令牌持久化到本机用户目录(`~/.mbi-bi/grant.json`),目的是避免宿主关闭或每轮对话重启进程后反复授权。令牌文件不在本包目录内,不会随 `npm pack` 进入市场包;但长期凭据落盘属于安全敏感行为,正式提审前须重新评估是否接受。若需恢复短时令牌设计,用同目录的 `src/client.js.bak` 覆盖 `src/client.js`,并把上面的有效期说明同步改回。
|
|
71
|
+
|
|
72
|
+
说明文档见 `../mbi-agent-service/docs/50-external-bi-mcp-deployment.md`。涉及客户数据外发时,要同时检查宿主模型的使用与留存策略:中台数据不经 Sense X Agent,但经授权返回给外部宿主后,由宿主处理。
|
package/package.json
CHANGED
|
@@ -1,6 +1,25 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@miaocedata/mbi-bi-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@miaocedata/mbi-bi-mcp",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Read-only stdio MCP adapter for authorized data platform deployments",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"engines": {
|
|
7
|
+
"node": ">=22"
|
|
8
|
+
},
|
|
9
|
+
"bin": {
|
|
10
|
+
"mbi-bi-mcp": "src/index.js"
|
|
11
|
+
},
|
|
12
|
+
"scripts": {
|
|
13
|
+
"test": "node --test"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"src/*.js",
|
|
17
|
+
"src/tool-manifest.json",
|
|
18
|
+
"src/magic-data-mark.png",
|
|
19
|
+
"README.md"
|
|
20
|
+
],
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
23
|
+
"ajv": "8.18.0"
|
|
24
|
+
}
|
|
25
|
+
}
|
package/src/auth.js
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { readFileSync } from 'node:fs';
|
|
4
|
+
import { createServer } from 'node:http';
|
|
5
|
+
|
|
6
|
+
export const CLIENT_ID = 'mbi-bi-desktop';
|
|
7
|
+
export const SCOPE = 'bi.semantic.read bi.ontology.read bi.query.execute';
|
|
8
|
+
export const ACCESS_TOKEN_SECONDS = 7 * 24 * 60 * 60;
|
|
9
|
+
const CALLBACK = '/mbi-bi/callback';
|
|
10
|
+
const SECRET = /^[A-Za-z0-9_-]{43}$/;
|
|
11
|
+
const TOKEN = /^bimcp_[A-Za-z0-9_-]{43}$/;
|
|
12
|
+
const MAGIC_DATA_MARK = readFileSync(new URL('./magic-data-mark.png', import.meta.url)).toString('base64');
|
|
13
|
+
const random = () => randomBytes(32).toString('base64url');
|
|
14
|
+
const digest = (value) => createHash('sha256').update(value, 'ascii').digest('base64url');
|
|
15
|
+
const callbackStates = {
|
|
16
|
+
success: {
|
|
17
|
+
eyebrow: 'AUTHORIZATION COMPLETE',
|
|
18
|
+
title: '授权已完成',
|
|
19
|
+
message: '中台已安全地把授权结果发送给本机 Agent。',
|
|
20
|
+
tone: 'success',
|
|
21
|
+
badge: '✓'
|
|
22
|
+
},
|
|
23
|
+
cancelled: {
|
|
24
|
+
eyebrow: 'AUTHORIZATION CANCELLED',
|
|
25
|
+
title: '已取消授权',
|
|
26
|
+
message: '本次请求没有授予任何数据访问权限。',
|
|
27
|
+
tone: 'cancelled',
|
|
28
|
+
badge: '!'
|
|
29
|
+
},
|
|
30
|
+
invalid: {
|
|
31
|
+
eyebrow: 'AUTHORIZATION EXPIRED',
|
|
32
|
+
title: '授权链接无效或已过期',
|
|
33
|
+
message: '请返回 Agent,重新发起一次授权请求。',
|
|
34
|
+
tone: 'invalid',
|
|
35
|
+
badge: '!'
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
export function callbackPage(kind = 'success', nonce = '') {
|
|
40
|
+
const state = callbackStates[kind] ?? callbackStates.invalid;
|
|
41
|
+
const success = state.tone === 'success';
|
|
42
|
+
const scrub = /^[A-Za-z0-9_-]{43}$/.test(nonce)
|
|
43
|
+
? `<script nonce="${nonce}">history.replaceState(null, '', '/mbi-bi/callback');</script>`
|
|
44
|
+
: '';
|
|
45
|
+
return `<!doctype html>
|
|
46
|
+
<html lang="zh-CN">
|
|
47
|
+
<head>
|
|
48
|
+
<meta charset="utf-8">
|
|
49
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
50
|
+
<title>${state.title} · 秒策数据中台</title>
|
|
51
|
+
<style>
|
|
52
|
+
:root{color-scheme:light;--ink:#17312e;--muted:#657a77;--line:#e8efed;--green:#0f766e;--mint:#e9f8f5}
|
|
53
|
+
*{box-sizing:border-box}
|
|
54
|
+
body{margin:0;min-height:100vh;padding:24px;color:var(--ink);background:radial-gradient(circle at 15% 10%,#dff8f1 0,transparent 32rem),radial-gradient(circle at 90% 92%,#e7efff 0,transparent 34rem),linear-gradient(145deg,#f3fbf8,#f8fafc 55%,#eef7f5);font-family:"PingFang SC","Microsoft YaHei",system-ui,sans-serif}
|
|
55
|
+
body::before{position:fixed;inset:0;content:"";pointer-events:none;opacity:.3;background-image:linear-gradient(rgba(15,118,110,.08) 1px,transparent 1px),linear-gradient(90deg,rgba(15,118,110,.08) 1px,transparent 1px);background-size:42px 42px;mask-image:linear-gradient(to bottom,#000,transparent 78%)}
|
|
56
|
+
.shell{position:relative;display:grid;min-height:calc(100vh - 48px);place-items:center}
|
|
57
|
+
.card{width:min(100%,620px);padding:28px 34px 30px;background:rgba(255,255,255,.9);border:1px solid rgba(255,255,255,.95);border-radius:28px;box-shadow:0 32px 90px rgba(25,73,66,.14),0 0 0 1px rgba(15,118,110,.05);backdrop-filter:blur(18px)}
|
|
58
|
+
.head{display:flex;align-items:center;justify-content:space-between;padding-bottom:22px;border-bottom:1px solid var(--line)}
|
|
59
|
+
.brand{display:flex;gap:10px;align-items:center;color:#164e48;font-size:14px;font-weight:750;letter-spacing:.04em}
|
|
60
|
+
.brand .brand-mark{display:block;width:38px;height:38px;overflow:hidden;border-radius:50%;box-shadow:0 10px 24px rgba(15,118,110,.18)}
|
|
61
|
+
.brand img{display:block;width:100%;height:100%;object-fit:contain}
|
|
62
|
+
.safe{padding:7px 11px;color:#687c79;border:1px solid #dfe9e7;border-radius:999px;font-size:11px;font-weight:650}
|
|
63
|
+
.hero{display:grid;justify-items:center;padding:42px 0 28px;text-align:center}
|
|
64
|
+
.mark{position:relative;display:grid;width:88px;height:88px;place-items:center;margin-bottom:22px;border-radius:50%}
|
|
65
|
+
.mark img{display:block;width:82px;height:82px;object-fit:contain;filter:drop-shadow(0 16px 24px rgba(15,118,110,.2))}
|
|
66
|
+
.mark::after{position:absolute;right:-1px;bottom:2px;display:grid;width:25px;height:25px;place-items:center;content:attr(data-badge);color:#fff;background:#10a67a;border:4px solid #fff;border-radius:50%;box-shadow:0 7px 16px rgba(15,118,110,.2);font-size:12px;font-weight:900;line-height:1}
|
|
67
|
+
.mark.cancelled::after{background:#d7a52d}
|
|
68
|
+
.mark.invalid::after{background:#d85a50}
|
|
69
|
+
.eyebrow{margin:0 0 8px;color:var(--green);font-size:11px;font-weight:800;letter-spacing:.16em}
|
|
70
|
+
h1{margin:0;font-size:clamp(30px,5vw,40px);letter-spacing:-.04em;line-height:1.2}
|
|
71
|
+
.lead{max-width:420px;margin:13px 0 0;color:var(--muted);font-size:15px;line-height:1.8}
|
|
72
|
+
.steps{display:grid;gap:10px;margin:6px 0 0;padding:0;list-style:none}
|
|
73
|
+
.steps li{display:grid;grid-template-columns:28px 1fr;gap:12px;align-items:center;padding:13px 15px;background:#f7fbfa;border:1px solid #edf2f1;border-radius:14px;color:#4d6662;font-size:13px;line-height:1.55}
|
|
74
|
+
.steps b{display:grid;width:28px;height:28px;place-items:center;color:#0f766e;background:#e2f6f1;border-radius:9px;font-size:11px}
|
|
75
|
+
.note{display:grid;gap:5px;margin-top:16px;padding:15px 17px;color:#5a716d;background:#eef9f6;border:1px solid #dcefe9;border-radius:14px;font-size:12px;line-height:1.7}
|
|
76
|
+
.note strong{color:#31534e;font-size:12px}
|
|
77
|
+
.foot{display:flex;gap:9px;align-items:center;margin:20px 0 0;padding-top:18px;color:#8a9996;border-top:1px solid var(--line);font-size:12px;line-height:1.6}
|
|
78
|
+
.foot::before{width:7px;height:7px;content:"";flex:0 0 auto;background:#18b48f;border-radius:50%;box-shadow:0 0 0 4px rgba(24,180,143,.11)}
|
|
79
|
+
.card.cancelled .foot::before{background:#d7a52d;box-shadow:0 0 0 4px rgba(215,165,45,.13)}
|
|
80
|
+
.card.invalid .foot::before{background:#d85a50;box-shadow:0 0 0 4px rgba(216,90,80,.12)}
|
|
81
|
+
@media(max-width:560px){body{padding:12px}.card{padding:22px 19px 24px;border-radius:22px}.safe{display:none}.hero{padding:34px 0 24px}.mark{width:66px;height:66px;border-radius:21px}.steps li{padding:12px}.foot{align-items:flex-start}}
|
|
82
|
+
</style>
|
|
83
|
+
</head>
|
|
84
|
+
<body>
|
|
85
|
+
<main class="shell">
|
|
86
|
+
<section class="card ${state.tone}">
|
|
87
|
+
<header class="head">
|
|
88
|
+
<div class="brand"><span class="brand-mark"><img src="data:image/png;base64,${MAGIC_DATA_MARK}" alt=""></span><span>秒策数据中台</span></div>
|
|
89
|
+
<span class="safe">安全授权回调</span>
|
|
90
|
+
</header>
|
|
91
|
+
<div class="hero">
|
|
92
|
+
<div class="mark ${state.tone}" data-badge="${state.badge}"><img src="data:image/png;base64,${MAGIC_DATA_MARK}" alt=""></div>
|
|
93
|
+
<p class="eyebrow">${state.eyebrow}</p>
|
|
94
|
+
<h1>${state.title}</h1>
|
|
95
|
+
<p class="lead">${state.message}</p>
|
|
96
|
+
</div>
|
|
97
|
+
${
|
|
98
|
+
success
|
|
99
|
+
? `<ol class="steps">
|
|
100
|
+
<li><b>1</b><span>返回 WorkBuddy 或当前 Agent 会话</span></li>
|
|
101
|
+
<li><b>2</b><span>请返回 Agent 并重新调用刚才的工具</span></li>
|
|
102
|
+
<li><b>3</b><span>每次成功使用会自动续期;连续 7 天未使用才需要重新授权</span></li>
|
|
103
|
+
</ol>
|
|
104
|
+
<div class="note"><strong>安全提示</strong><span>授权码只通过本机临时回调传递,不会显示在页面中,也不会写入浏览器存储。</span></div>`
|
|
105
|
+
: `<div class="note"><strong>下一步</strong><span>请返回 Agent 重新发起授权。不要复制或重复使用当前地址。</span></div>`
|
|
106
|
+
}
|
|
107
|
+
<p class="foot">现在可以关闭此页面,返回发起请求的应用继续操作。</p>
|
|
108
|
+
</section>
|
|
109
|
+
</main>
|
|
110
|
+
${scrub}
|
|
111
|
+
</body>
|
|
112
|
+
</html>`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function platformUrls(env) {
|
|
116
|
+
const raw = env.MBI_PLATFORM_URL;
|
|
117
|
+
const insecureHttp = /^http:\/\//i.test(raw ?? '');
|
|
118
|
+
if (!raw || (!/^https:\/\//i.test(raw) && !insecureHttp) || /[\\\s?#]/.test(raw)) throw new Error('Invalid MBI_PLATFORM_URL');
|
|
119
|
+
const base = new URL(raw);
|
|
120
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]', '::1'].includes(base.hostname);
|
|
121
|
+
if (insecureHttp && (env.MBI_ALLOW_INSECURE_LOCALHOST !== 'true' || !loopback)) {
|
|
122
|
+
throw new Error('Insecure HTTP is only allowed for localhost development');
|
|
123
|
+
}
|
|
124
|
+
if (base.username || base.password || !/^\/(?:[A-Za-z0-9_-]+\/)*[A-Za-z0-9_-]*$/.test(base.pathname)) throw new Error('Invalid MBI_PLATFORM_URL');
|
|
125
|
+
const prefix = env.MBI_API_BASE_PATH ?? '/prod-api';
|
|
126
|
+
if (prefix && !/^(?:\/[A-Za-z0-9_-]+)+$/.test(prefix)) throw new Error('Invalid MBI_API_BASE_PATH');
|
|
127
|
+
const api = (path) => new URL(`${prefix}${path}`, base.origin);
|
|
128
|
+
return {
|
|
129
|
+
consent: new URL(`${base.pathname.replace(/\/$/, '')}/external-bi/authorize`, base.origin),
|
|
130
|
+
token: api('/auth/bi-oauth/token'), revoke: api('/auth/bi-oauth/revoke'), mcp: api('/mbi-agent/mcp/bi')
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export async function readJson(response, maxBytes) {
|
|
135
|
+
if (!response.body || !/^application\/json(?:;|$)/i.test(response.headers.get('content-type') ?? '')) throw new Error('Expected JSON');
|
|
136
|
+
const reader = response.body.getReader();
|
|
137
|
+
const chunks = [];
|
|
138
|
+
let size = 0;
|
|
139
|
+
try {
|
|
140
|
+
for (;;) {
|
|
141
|
+
const { done, value } = await reader.read();
|
|
142
|
+
if (done) break;
|
|
143
|
+
size += value.byteLength;
|
|
144
|
+
if (size > maxBytes) throw new Error('Response too large');
|
|
145
|
+
chunks.push(value);
|
|
146
|
+
}
|
|
147
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
148
|
+
} finally {
|
|
149
|
+
void reader.cancel().catch(() => {});
|
|
150
|
+
reader.releaseLock();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function openBrowser(url) {
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
// Windows passes the HTTPS URL as a quoted PowerShell literal, not a cmd.exe command.
|
|
157
|
+
const command = `Start-Process -FilePath '${url.href.replaceAll("'", "''")}'`;
|
|
158
|
+
const [exe, args] = process.platform === 'win32'
|
|
159
|
+
? ['powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(command, 'utf16le').toString('base64')]]
|
|
160
|
+
: [process.platform === 'darwin' ? 'open' : 'xdg-open', [url.href]];
|
|
161
|
+
const proc = spawn(exe, args, { stdio: 'ignore', windowsHide: true });
|
|
162
|
+
const timer = setTimeout(() => { proc.kill(); reject(new Error('Browser launch timed out')); }, 8000);
|
|
163
|
+
timer.unref();
|
|
164
|
+
proc.once('error', () => { clearTimeout(timer); reject(new Error('Browser launch failed')); });
|
|
165
|
+
proc.once('exit', (code) => {
|
|
166
|
+
clearTimeout(timer);
|
|
167
|
+
if (code === 0) resolve(); else reject(new Error('Browser launch failed'));
|
|
168
|
+
});
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function authorize(urls, { launch = openBrowser, fetcher = fetch, timeoutMs = 180_000, signal } = {}) {
|
|
173
|
+
const state = random();
|
|
174
|
+
const verifier = random();
|
|
175
|
+
let accept;
|
|
176
|
+
let fail;
|
|
177
|
+
const callback = new Promise((resolve, reject) => { accept = resolve; fail = reject; });
|
|
178
|
+
// The callback can expire or fail before the browser launcher finishes.
|
|
179
|
+
void callback.catch(() => {});
|
|
180
|
+
let consumed = false;
|
|
181
|
+
let authority;
|
|
182
|
+
const pageNonce = random();
|
|
183
|
+
const listener = createServer({ requestTimeout: 5000, headersTimeout: 5000, maxHeaderSize: 4096 }, (req, res) => {
|
|
184
|
+
res.setHeader('Content-Type', 'text/html; charset=utf-8');
|
|
185
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
186
|
+
res.setHeader('Content-Security-Policy', `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${pageNonce}'; img-src data:; base-uri 'none'; form-action 'none'`);
|
|
187
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
188
|
+
res.setHeader('Connection', 'close');
|
|
189
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
190
|
+
const page = (kind, status = 200) => { res.statusCode = status; res.end(callbackPage(kind, pageNonce)); };
|
|
191
|
+
const bad = () => page('invalid', 400);
|
|
192
|
+
if (consumed || req.method !== 'GET' || req.headers.host !== authority || !req.url?.startsWith(`${CALLBACK}?`)) return bad();
|
|
193
|
+
const redirect = new URL(`http://${authority}${req.url}`);
|
|
194
|
+
const s = redirect.searchParams;
|
|
195
|
+
const proposedState = s.get('state') ?? '';
|
|
196
|
+
if (s.getAll('state').length !== 1 || !SECRET.test(proposedState) || !timingSafeEqual(Buffer.from(proposedState), Buffer.from(state))) return bad();
|
|
197
|
+
if (s.size === 2 && s.get('error') === 'access_denied') {
|
|
198
|
+
consumed = true;
|
|
199
|
+
page('cancelled');
|
|
200
|
+
fail(new Error('Authorization declined'));
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const code = s.get('code') ?? '';
|
|
204
|
+
if (s.size !== 2 || s.getAll('code').length !== 1 || !SECRET.test(code)) return bad();
|
|
205
|
+
consumed = true;
|
|
206
|
+
page('success');
|
|
207
|
+
accept(code);
|
|
208
|
+
});
|
|
209
|
+
listener.maxConnections = 8;
|
|
210
|
+
const abort = () => fail(new Error('Authorization canceled'));
|
|
211
|
+
const timer = setTimeout(() => fail(new Error('Authorization timed out')), timeoutMs);
|
|
212
|
+
try {
|
|
213
|
+
signal?.throwIfAborted();
|
|
214
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
215
|
+
await new Promise((resolve, reject) => {
|
|
216
|
+
listener.once('error', reject);
|
|
217
|
+
listener.listen(0, '127.0.0.1', resolve);
|
|
218
|
+
});
|
|
219
|
+
listener.on('error', fail);
|
|
220
|
+
authority = `127.0.0.1:${listener.address().port}`;
|
|
221
|
+
const uri = `http://${authority}${CALLBACK}`;
|
|
222
|
+
const consent = new URL(urls.consent);
|
|
223
|
+
consent.hash = new URLSearchParams({ client_id: CLIENT_ID, response_type: 'code', redirect_uri: uri, scope: SCOPE,
|
|
224
|
+
state, code_challenge: digest(verifier), code_challenge_method: 'S256' });
|
|
225
|
+
const [, code] = await Promise.all([launch(consent), callback]);
|
|
226
|
+
const response = await fetcher(urls.token, {
|
|
227
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(12_000), ...(signal ? [signal] : [])]),
|
|
228
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
229
|
+
body: new URLSearchParams({ grant_type: 'authorization_code', client_id: CLIENT_ID, code, redirect_uri: uri, code_verifier: verifier })
|
|
230
|
+
});
|
|
231
|
+
if (!response.ok) { void response.body?.cancel().catch(() => {}); throw new Error('Token exchange declined'); }
|
|
232
|
+
const data = await readJson(response, 12_000);
|
|
233
|
+
if (data?.token_type !== 'Bearer' || !TOKEN.test(data.access_token ?? '') || data.scope !== SCOPE
|
|
234
|
+
|| !Number.isInteger(data.expires_in) || data.expires_in < 1 || data.expires_in > ACCESS_TOKEN_SECONDS) {
|
|
235
|
+
throw new Error('Invalid token response');
|
|
236
|
+
}
|
|
237
|
+
return { token: data.access_token, expiresAt: Date.now() + data.expires_in * 1000 };
|
|
238
|
+
} finally {
|
|
239
|
+
clearTimeout(timer);
|
|
240
|
+
signal?.removeEventListener('abort', abort);
|
|
241
|
+
// Ended callbacks flush their response before closing; abort unfinished requests.
|
|
242
|
+
listener.close();
|
|
243
|
+
if (!consumed) listener.closeAllConnections();
|
|
244
|
+
}
|
|
245
|
+
}
|
package/src/client.js
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import Ajv from 'ajv';
|
|
5
|
+
import { ACCESS_TOKEN_SECONDS, CLIENT_ID, authorize, platformUrls, readJson } from './auth.js';
|
|
6
|
+
|
|
7
|
+
export const configurationTool = {
|
|
8
|
+
name: 'configure_platform',
|
|
9
|
+
description: 'Set or change the data platform portal address only when the user explicitly supplies it. ' +
|
|
10
|
+
'The URL must be the HTTPS portal base, not an MCP endpoint. Switching disconnects the previous authorization.',
|
|
11
|
+
inputSchema: {
|
|
12
|
+
type: 'object',
|
|
13
|
+
additionalProperties: false,
|
|
14
|
+
properties: {
|
|
15
|
+
url: { type: 'string', minLength: 8, maxLength: 2048 },
|
|
16
|
+
apiBasePath: { type: 'string', minLength: 0, maxLength: 256 }
|
|
17
|
+
},
|
|
18
|
+
required: ['url']
|
|
19
|
+
},
|
|
20
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }
|
|
21
|
+
};
|
|
22
|
+
const jvmTools = JSON.parse(readFileSync(new URL('./tool-manifest.json', import.meta.url), 'utf8'));
|
|
23
|
+
export const tools = [configurationTool, ...jvmTools];
|
|
24
|
+
const ajv = new Ajv({ strict: true });
|
|
25
|
+
const validators = new Map(tools.map(({ name, inputSchema }) => [name, ajv.compile(inputSchema)]));
|
|
26
|
+
const allowedErrors = new Set(['AUTH_REQUIRED', 'AUTH_UNAVAILABLE', 'SCOPE_DENIED', 'LICENSE_REQUIRED', 'BI_MCP_NOT_ENABLED',
|
|
27
|
+
'RESOURCE_FORBIDDEN', 'RATE_LIMITED', 'INVALID_ARGUMENT', 'SEMANTIC_VERSION_MISMATCH', 'UNSUPPORTED_QUERY_CONSTRAINT',
|
|
28
|
+
'DATE_DIMENSION_REQUIRED', 'DATE_DIMENSION_UNAVAILABLE', 'DATE_RANGE_NO_SELECTION', 'DATE_MEASURE_UNSUPPORTED',
|
|
29
|
+
'DATE_RANGE_UNVERIFIED', 'ONTOLOGY_VERSION_UNAVAILABLE', 'ONTOLOGY_QUERY_NOT_ALLOWED', 'ONTOLOGY_CONSTRAINT_UNSUPPORTED',
|
|
30
|
+
'QLIK_IDENTITY_NOT_CONFIGURED', 'QLIK_QUERY_FAILED', 'CONFIG_TOO_LARGE', 'BI_SERVICE_UNAVAILABLE', 'ONTOLOGY_UNAVAILABLE']);
|
|
31
|
+
const message = (structuredContent, isError) => ({ structuredContent, isError,
|
|
32
|
+
content: [{ type: 'text', text: JSON.stringify(structuredContent) }] });
|
|
33
|
+
const error = (code, description, requestId) => message({ error: { code, ...(description && { message: description }) },
|
|
34
|
+
...(typeof requestId === 'string' && /^[0-9a-f-]{36}$/i.test(requestId) && { requestId }) }, true);
|
|
35
|
+
|
|
36
|
+
const GRANT_FILE = join(homedir(), '.mbi-bi', 'grant.json');
|
|
37
|
+
const PLATFORM_CONFIG_FILE = join(homedir(), '.mbi-senseX', 'platform.json');
|
|
38
|
+
const GRANT_TOKEN = /^bimcp_[A-Za-z0-9_-]{43}$/;
|
|
39
|
+
|
|
40
|
+
function loadGrant(scope) {
|
|
41
|
+
try {
|
|
42
|
+
const data = JSON.parse(readFileSync(GRANT_FILE, 'utf8'));
|
|
43
|
+
if (data?.platformScope === scope && GRANT_TOKEN.test(data?.token)
|
|
44
|
+
&& Number.isInteger(data.expiresAt) && data.expiresAt > Date.now()) {
|
|
45
|
+
return { token: data.token, expiresAt: data.expiresAt };
|
|
46
|
+
}
|
|
47
|
+
} catch {}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function saveGrant(grant, scope) {
|
|
52
|
+
try {
|
|
53
|
+
mkdirSync(dirname(GRANT_FILE), { recursive: true });
|
|
54
|
+
writeFileSync(GRANT_FILE, JSON.stringify({ ...grant, platformScope: scope }), { mode: 0o600 });
|
|
55
|
+
} catch {}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function clearGrant() {
|
|
59
|
+
try { unlinkSync(GRANT_FILE); } catch {}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const persistentGrantStore = { load: loadGrant, save: saveGrant, clear: clearGrant };
|
|
63
|
+
|
|
64
|
+
function loadPlatformConfig() {
|
|
65
|
+
try {
|
|
66
|
+
const data = JSON.parse(readFileSync(PLATFORM_CONFIG_FILE, 'utf8'));
|
|
67
|
+
if (typeof data?.platformUrl === 'string' && data.platformUrl.length > 0 && data.platformUrl.length <= 2048
|
|
68
|
+
&& (data.apiBasePath === undefined
|
|
69
|
+
|| typeof data.apiBasePath === 'string' && data.apiBasePath.length <= 256)) {
|
|
70
|
+
return data;
|
|
71
|
+
}
|
|
72
|
+
} catch {}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function savePlatformConfig(config) {
|
|
77
|
+
mkdirSync(dirname(PLATFORM_CONFIG_FILE), { recursive: true });
|
|
78
|
+
writeFileSync(PLATFORM_CONFIG_FILE, JSON.stringify(config), { mode: 0o600 });
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const persistentPlatformStore = { load: loadPlatformConfig, save: savePlatformConfig };
|
|
82
|
+
|
|
83
|
+
function resolvePlatformConfig(env, platformUrl, apiBasePath) {
|
|
84
|
+
const raw = platformUrl == null ? '' : String(platformUrl).trim();
|
|
85
|
+
if (!raw) return undefined;
|
|
86
|
+
const effective = { ...env, MBI_PLATFORM_URL: raw };
|
|
87
|
+
if (apiBasePath !== undefined) effective.MBI_API_BASE_PATH = String(apiBasePath).trim();
|
|
88
|
+
const urls = platformUrls(effective);
|
|
89
|
+
return {
|
|
90
|
+
platformUrl: raw,
|
|
91
|
+
apiBasePath: effective.MBI_API_BASE_PATH ?? '/prod-api',
|
|
92
|
+
urls
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class PlatformClient {
|
|
97
|
+
#grant;
|
|
98
|
+
#grantStore;
|
|
99
|
+
#scope;
|
|
100
|
+
#pending;
|
|
101
|
+
#lastStart = 0;
|
|
102
|
+
#sequence = 0;
|
|
103
|
+
#stop = new AbortController();
|
|
104
|
+
#closed = false;
|
|
105
|
+
|
|
106
|
+
constructor(urls, { fetcher = fetch, login = authorize, log = (text) => console.error(text),
|
|
107
|
+
grantStore = persistentGrantStore, scope = urls.mcp.href } = {}) {
|
|
108
|
+
this.urls = urls;
|
|
109
|
+
this.fetcher = fetcher;
|
|
110
|
+
this.login = login;
|
|
111
|
+
this.log = log;
|
|
112
|
+
this.#grantStore = grantStore;
|
|
113
|
+
this.#scope = scope;
|
|
114
|
+
this.#grant = grantStore.load(scope);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
close() {
|
|
118
|
+
this.#closed = true;
|
|
119
|
+
this.#grant = undefined;
|
|
120
|
+
this.#stop.abort();
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
forgetGrant() {
|
|
124
|
+
this.#grant = undefined;
|
|
125
|
+
this.#grantStore.clear();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async revokeCurrent() {
|
|
129
|
+
const grant = this.#grant;
|
|
130
|
+
this.forgetGrant();
|
|
131
|
+
if (!grant || !this.urls.revoke) return;
|
|
132
|
+
try {
|
|
133
|
+
const response = await this.fetcher(this.urls.revoke, {
|
|
134
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
135
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
136
|
+
body: new URLSearchParams({ client_id: CLIENT_ID, token: grant.token })
|
|
137
|
+
});
|
|
138
|
+
void response.body?.cancel().catch(() => {});
|
|
139
|
+
} catch {}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
#needLogin() {
|
|
143
|
+
if (this.#closed) return error('BI_SERVICE_UNAVAILABLE');
|
|
144
|
+
if (!this.#pending && Date.now() - this.#lastStart >= 10_000) {
|
|
145
|
+
this.#lastStart = Date.now();
|
|
146
|
+
this.#pending = Promise.resolve().then(() => this.login(this.urls, { fetcher: this.fetcher, signal: this.#stop.signal }))
|
|
147
|
+
.then((grant) => { if (!this.#closed) { this.#grant = grant; this.#grantStore.save(grant, this.#scope); } })
|
|
148
|
+
.catch(() => { if (!this.#closed) this.log('[mbi-senseX-mcp] 中台授权未完成;请确认可打开系统浏览器,再重试工具。'); })
|
|
149
|
+
.finally(() => { this.#pending = undefined; });
|
|
150
|
+
}
|
|
151
|
+
return error('AUTH_REQUIRED', this.#pending ? '请在本机浏览器登录中台并批准授权,完成后由用户重试;不要自动轮询。'
|
|
152
|
+
: '授权暂未完成,请稍后由用户重试。');
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
async call(name, args = {}) {
|
|
156
|
+
const validator = validators.get(name);
|
|
157
|
+
if (!validator || !validator(args)) return error('INVALID_ARGUMENT');
|
|
158
|
+
if (this.#closed) return error('BI_SERVICE_UNAVAILABLE');
|
|
159
|
+
const grant = this.#grant;
|
|
160
|
+
if (!grant || Date.now() >= grant.expiresAt) return this.#needLogin();
|
|
161
|
+
const id = ++this.#sequence;
|
|
162
|
+
try {
|
|
163
|
+
const response = await this.fetcher(this.urls.mcp, {
|
|
164
|
+
method: 'POST', redirect: 'error', signal: AbortSignal.any([AbortSignal.timeout(42_000), this.#stop.signal]),
|
|
165
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream',
|
|
166
|
+
'MCP-Protocol-Version': '2025-06-18', Authorization: `Bearer ${grant.token}` },
|
|
167
|
+
body: JSON.stringify({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } })
|
|
168
|
+
});
|
|
169
|
+
if (!response.ok) {
|
|
170
|
+
void response.body?.cancel().catch(() => {});
|
|
171
|
+
if (response.status === 401) {
|
|
172
|
+
if (this.#grant === grant) { this.#grant = undefined; this.#grantStore.clear(); }
|
|
173
|
+
return error('AUTH_REQUIRED', '中台授权已失效;下次调用将重新打开登录。');
|
|
174
|
+
}
|
|
175
|
+
return error(response.status === 429 ? 'RATE_LIMITED' : 'BI_SERVICE_UNAVAILABLE');
|
|
176
|
+
}
|
|
177
|
+
const envelope = await readJson(response, 4_000_000);
|
|
178
|
+
const result = envelope?.result;
|
|
179
|
+
const data = result?.structuredContent;
|
|
180
|
+
if (envelope?.jsonrpc !== '2.0' || envelope.id !== id || !data || typeof data !== 'object' || Array.isArray(data)) {
|
|
181
|
+
return error('BI_SERVICE_UNAVAILABLE');
|
|
182
|
+
}
|
|
183
|
+
if (result.isError === true) {
|
|
184
|
+
const code = data.error?.code;
|
|
185
|
+
if (code === 'AUTH_REQUIRED' && this.#grant === grant) {
|
|
186
|
+
this.#grant = undefined;
|
|
187
|
+
this.#grantStore.clear();
|
|
188
|
+
} else if (code !== 'AUTH_UNAVAILABLE') {
|
|
189
|
+
this.#extend(grant);
|
|
190
|
+
}
|
|
191
|
+
return error(allowedErrors.has(code) ? code : 'BI_SERVICE_UNAVAILABLE', null, data.requestId);
|
|
192
|
+
}
|
|
193
|
+
if (result.isError !== false) return error('BI_SERVICE_UNAVAILABLE');
|
|
194
|
+
this.#extend(grant);
|
|
195
|
+
return message(data, false);
|
|
196
|
+
} catch { return error('BI_SERVICE_UNAVAILABLE'); }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#extend(grant) {
|
|
200
|
+
if (this.#closed || this.#grant !== grant) return;
|
|
201
|
+
const renewed = { token: grant.token, expiresAt: Date.now() + ACCESS_TOKEN_SECONDS * 1000 };
|
|
202
|
+
this.#grant = renewed;
|
|
203
|
+
this.#grantStore.save(renewed, this.#scope);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export class PlatformSession {
|
|
208
|
+
#env;
|
|
209
|
+
#platformStore;
|
|
210
|
+
#clientFactory;
|
|
211
|
+
#client;
|
|
212
|
+
#config;
|
|
213
|
+
|
|
214
|
+
constructor(env, { platformStore = persistentPlatformStore,
|
|
215
|
+
clientFactory = (urls, config) => new PlatformClient(urls,
|
|
216
|
+
{ scope: `${config.platformUrl}\n${config.apiBasePath}` }) } = {}) {
|
|
217
|
+
this.#env = env;
|
|
218
|
+
this.#platformStore = platformStore;
|
|
219
|
+
this.#clientFactory = clientFactory;
|
|
220
|
+
this.#reload();
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
#reload() {
|
|
224
|
+
const saved = this.#platformStore.load();
|
|
225
|
+
try {
|
|
226
|
+
this.#config = resolvePlatformConfig(
|
|
227
|
+
this.#env,
|
|
228
|
+
saved?.platformUrl ?? this.#env.MBI_PLATFORM_URL,
|
|
229
|
+
saved?.apiBasePath ?? (saved ? undefined : this.#env.MBI_API_BASE_PATH)
|
|
230
|
+
);
|
|
231
|
+
this.#client = this.#config ? this.#clientFactory(this.#config.urls, this.#config) : undefined;
|
|
232
|
+
} catch {
|
|
233
|
+
this.#config = undefined;
|
|
234
|
+
this.#client = undefined;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async call(name, args = {}) {
|
|
239
|
+
if (name === configurationTool.name) return this.#configure(args);
|
|
240
|
+
if (!this.#client) {
|
|
241
|
+
return error('PLATFORM_URL_REQUIRED',
|
|
242
|
+
'尚未配置数据中台地址。请让用户明确提供门户地址,再调用 configure_platform。');
|
|
243
|
+
}
|
|
244
|
+
return this.#client.call(name, args);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async #configure(args) {
|
|
248
|
+
if (!args || typeof args.url !== 'string' || args.url.trim().length < 8 || args.url.length > 2048
|
|
249
|
+
|| args.apiBasePath !== undefined
|
|
250
|
+
&& (typeof args.apiBasePath !== 'string' || args.apiBasePath.length > 256)) {
|
|
251
|
+
return error('INVALID_ARGUMENT', '请提供明确的数据中台门户地址。');
|
|
252
|
+
}
|
|
253
|
+
let next;
|
|
254
|
+
try {
|
|
255
|
+
const rawUrl = args.url.trim();
|
|
256
|
+
let defaultBasePath = '/prod-api';
|
|
257
|
+
try {
|
|
258
|
+
const host = new URL(rawUrl).hostname;
|
|
259
|
+
if (['localhost', '127.0.0.1', '[::1]', '::1'].includes(host)) {
|
|
260
|
+
defaultBasePath = this.#env.MBI_API_BASE_PATH ?? '/prod-api';
|
|
261
|
+
}
|
|
262
|
+
} catch {}
|
|
263
|
+
next = resolvePlatformConfig(this.#env, rawUrl,
|
|
264
|
+
args.apiBasePath === undefined ? defaultBasePath : args.apiBasePath);
|
|
265
|
+
} catch {
|
|
266
|
+
next = undefined;
|
|
267
|
+
}
|
|
268
|
+
if (!next) return error('INVALID_ARGUMENT', '数据中台地址无效;正式环境必须是 HTTPS 门户地址。');
|
|
269
|
+
|
|
270
|
+
if (this.#config && this.#client
|
|
271
|
+
&& this.#config.platformUrl === next.platformUrl && this.#config.apiBasePath === next.apiBasePath) {
|
|
272
|
+
return message({ configured: true, changed: false, platformUrl: next.platformUrl,
|
|
273
|
+
apiBasePath: next.apiBasePath }, false);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (this.#client) {
|
|
277
|
+
await this.#client.revokeCurrent();
|
|
278
|
+
this.#client.close();
|
|
279
|
+
}
|
|
280
|
+
const client = this.#clientFactory(next.urls, next);
|
|
281
|
+
this.#config = next;
|
|
282
|
+
this.#client = client;
|
|
283
|
+
this.#platformStore.save({ platformUrl: next.platformUrl, apiBasePath: next.apiBasePath });
|
|
284
|
+
return message({ configured: true, changed: true, platformUrl: next.platformUrl,
|
|
285
|
+
apiBasePath: next.apiBasePath }, false);
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
close() {
|
|
289
|
+
this.#client?.close();
|
|
290
|
+
this.#client = undefined;
|
|
291
|
+
}
|
|
292
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
3
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
4
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { PlatformSession, tools } from './client.js';
|
|
6
|
+
|
|
7
|
+
async function main() {
|
|
8
|
+
const session = new PlatformSession(process.env);
|
|
9
|
+
const server = new Server({ name: 'mbi-senseX', version: '0.1.0' }, { capabilities: { tools: {} } });
|
|
10
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));
|
|
11
|
+
server.setRequestHandler(CallToolRequestSchema, ({ params }) => session.call(params.name, params.arguments));
|
|
12
|
+
server.onerror = () => console.error('[mbi-senseX-mcp] MCP protocol error.');
|
|
13
|
+
server.onclose = () => session.close();
|
|
14
|
+
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
|
|
15
|
+
session.close();
|
|
16
|
+
void server.close().finally(() => process.exit(0));
|
|
17
|
+
});
|
|
18
|
+
process.stdin.once('end', () => session.close());
|
|
19
|
+
await server.connect(new StdioServerTransport());
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
main().catch(() => {
|
|
23
|
+
console.error('[mbi-senseX-mcp] 启动失败。正式环境检查 MBI_PLATFORM_URL(HTTPS);本机开发可启用 MBI_ALLOW_INSECURE_LOCALHOST;同时检查 MBI_API_BASE_PATH。');
|
|
24
|
+
process.exitCode = 1;
|
|
25
|
+
});
|
|
Binary file
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
[
|
|
2
|
+
{
|
|
3
|
+
"name": "get_analysis_config",
|
|
4
|
+
"description": "Read the authorized analysis catalog. Omit appId to list Apps; pass appId for enabled business metric/dimension IDs, version and supported daily date dimensions.",
|
|
5
|
+
"inputSchema": {
|
|
6
|
+
"type": "object",
|
|
7
|
+
"additionalProperties": false,
|
|
8
|
+
"properties": {
|
|
9
|
+
"appId": {
|
|
10
|
+
"type": "string",
|
|
11
|
+
"minLength": 1,
|
|
12
|
+
"maxLength": 128,
|
|
13
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
14
|
+
},
|
|
15
|
+
"limit": {
|
|
16
|
+
"type": "integer",
|
|
17
|
+
"minimum": 1,
|
|
18
|
+
"maximum": 100
|
|
19
|
+
},
|
|
20
|
+
"cursor": {
|
|
21
|
+
"type": "string",
|
|
22
|
+
"minLength": 1,
|
|
23
|
+
"maxLength": 96
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
"annotations": {
|
|
28
|
+
"readOnlyHint": true,
|
|
29
|
+
"openWorldHint": false
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"name": "get_business_ontology",
|
|
34
|
+
"description": "Read active published production business ontology for an App, including cross-App metadata only if all source Apps are authorized. Use ontologyVersion from an item to constrain query_metrics; queries still execute in one App.",
|
|
35
|
+
"inputSchema": {
|
|
36
|
+
"type": "object",
|
|
37
|
+
"additionalProperties": false,
|
|
38
|
+
"properties": {
|
|
39
|
+
"appId": {
|
|
40
|
+
"type": "string",
|
|
41
|
+
"minLength": 1,
|
|
42
|
+
"maxLength": 128,
|
|
43
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
44
|
+
},
|
|
45
|
+
"ontologyId": {
|
|
46
|
+
"type": "string",
|
|
47
|
+
"minLength": 1,
|
|
48
|
+
"maxLength": 128
|
|
49
|
+
},
|
|
50
|
+
"limit": {
|
|
51
|
+
"type": "integer",
|
|
52
|
+
"minimum": 1,
|
|
53
|
+
"maximum": 10
|
|
54
|
+
},
|
|
55
|
+
"cursor": {
|
|
56
|
+
"type": "string",
|
|
57
|
+
"minLength": 1,
|
|
58
|
+
"maxLength": 96
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"required": [
|
|
62
|
+
"appId"
|
|
63
|
+
]
|
|
64
|
+
},
|
|
65
|
+
"annotations": {
|
|
66
|
+
"readOnlyHint": true,
|
|
67
|
+
"openWorldHint": false
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
"name": "query_metrics",
|
|
72
|
+
"description": "Query registered metrics as the current user in one App. Use business IDs from get_analysis_config. Pass dateRange for a configured daily calendar window (inclusive from, exclusive toExclusive); do not retry without a requested constraint. Optionally pin an active ontologyVersion returned by get_business_ontology. Never accepts raw expressions or SQL.",
|
|
73
|
+
"inputSchema": {
|
|
74
|
+
"type": "object",
|
|
75
|
+
"additionalProperties": false,
|
|
76
|
+
"properties": {
|
|
77
|
+
"appId": {
|
|
78
|
+
"type": "string",
|
|
79
|
+
"minLength": 1,
|
|
80
|
+
"maxLength": 128,
|
|
81
|
+
"pattern": "^[A-Za-z0-9_-]+$"
|
|
82
|
+
},
|
|
83
|
+
"metricIds": {
|
|
84
|
+
"type": "array",
|
|
85
|
+
"minItems": 1,
|
|
86
|
+
"maxItems": 10,
|
|
87
|
+
"items": {
|
|
88
|
+
"type": "string",
|
|
89
|
+
"minLength": 1,
|
|
90
|
+
"maxLength": 19,
|
|
91
|
+
"pattern": "^[1-9][0-9]*$"
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
"dimensionIds": {
|
|
95
|
+
"type": "array",
|
|
96
|
+
"minItems": 0,
|
|
97
|
+
"maxItems": 5,
|
|
98
|
+
"items": {
|
|
99
|
+
"type": "string",
|
|
100
|
+
"minLength": 1,
|
|
101
|
+
"maxLength": 19,
|
|
102
|
+
"pattern": "^[1-9][0-9]*$"
|
|
103
|
+
}
|
|
104
|
+
},
|
|
105
|
+
"filters": {
|
|
106
|
+
"type": "array",
|
|
107
|
+
"minItems": 0,
|
|
108
|
+
"maxItems": 5,
|
|
109
|
+
"items": {
|
|
110
|
+
"oneOf": [
|
|
111
|
+
{
|
|
112
|
+
"type": "object",
|
|
113
|
+
"additionalProperties": false,
|
|
114
|
+
"properties": {
|
|
115
|
+
"dimensionId": {
|
|
116
|
+
"type": "string",
|
|
117
|
+
"minLength": 1,
|
|
118
|
+
"maxLength": 19,
|
|
119
|
+
"pattern": "^[1-9][0-9]*$"
|
|
120
|
+
},
|
|
121
|
+
"op": {
|
|
122
|
+
"const": "eq",
|
|
123
|
+
"type": "string"
|
|
124
|
+
},
|
|
125
|
+
"value": {
|
|
126
|
+
"type": "string",
|
|
127
|
+
"minLength": 1,
|
|
128
|
+
"maxLength": 128
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
"required": [
|
|
132
|
+
"dimensionId",
|
|
133
|
+
"op",
|
|
134
|
+
"value"
|
|
135
|
+
]
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"type": "object",
|
|
139
|
+
"additionalProperties": false,
|
|
140
|
+
"properties": {
|
|
141
|
+
"dimensionId": {
|
|
142
|
+
"type": "string",
|
|
143
|
+
"minLength": 1,
|
|
144
|
+
"maxLength": 19,
|
|
145
|
+
"pattern": "^[1-9][0-9]*$"
|
|
146
|
+
},
|
|
147
|
+
"op": {
|
|
148
|
+
"const": "in",
|
|
149
|
+
"type": "string"
|
|
150
|
+
},
|
|
151
|
+
"values": {
|
|
152
|
+
"type": "array",
|
|
153
|
+
"minItems": 1,
|
|
154
|
+
"maxItems": 20,
|
|
155
|
+
"items": {
|
|
156
|
+
"type": "string",
|
|
157
|
+
"minLength": 1,
|
|
158
|
+
"maxLength": 128
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
"required": [
|
|
163
|
+
"dimensionId",
|
|
164
|
+
"op",
|
|
165
|
+
"values"
|
|
166
|
+
]
|
|
167
|
+
}
|
|
168
|
+
]
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
"limit": {
|
|
172
|
+
"type": "integer",
|
|
173
|
+
"minimum": 1,
|
|
174
|
+
"maximum": 500
|
|
175
|
+
},
|
|
176
|
+
"semanticVersion": {
|
|
177
|
+
"type": "string",
|
|
178
|
+
"minLength": 1,
|
|
179
|
+
"maxLength": 96
|
|
180
|
+
},
|
|
181
|
+
"dateRange": {
|
|
182
|
+
"type": "object",
|
|
183
|
+
"additionalProperties": false,
|
|
184
|
+
"properties": {
|
|
185
|
+
"from": {
|
|
186
|
+
"type": "string",
|
|
187
|
+
"pattern": "^[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}$"
|
|
188
|
+
},
|
|
189
|
+
"toExclusive": {
|
|
190
|
+
"type": "string",
|
|
191
|
+
"pattern": "^[1-9][0-9]{3}-[0-9]{2}-[0-9]{2}$"
|
|
192
|
+
},
|
|
193
|
+
"dimensionId": {
|
|
194
|
+
"type": "string",
|
|
195
|
+
"minLength": 1,
|
|
196
|
+
"maxLength": 19,
|
|
197
|
+
"pattern": "^[1-9][0-9]*$",
|
|
198
|
+
"description": "Registered daily time dimension. Required when the App has more than one eligible dimension."
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
"required": [
|
|
202
|
+
"from",
|
|
203
|
+
"toExclusive"
|
|
204
|
+
]
|
|
205
|
+
},
|
|
206
|
+
"ontologyVersion": {
|
|
207
|
+
"type": "string",
|
|
208
|
+
"minLength": 1,
|
|
209
|
+
"maxLength": 128,
|
|
210
|
+
"pattern": "^[A-Za-z0-9_-]+$",
|
|
211
|
+
"description": "Exact active production release ID from get_business_ontology; not a label or release number."
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
"required": [
|
|
215
|
+
"appId",
|
|
216
|
+
"metricIds"
|
|
217
|
+
]
|
|
218
|
+
},
|
|
219
|
+
"annotations": {
|
|
220
|
+
"readOnlyHint": true,
|
|
221
|
+
"openWorldHint": false
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
]
|