mcp-server-bugzilla4 0.0.0-stage → 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mcp-server-bugzilla4 contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,165 @@
1
- # Temporary Holding Version
1
+ # mcp-server-bugzilla4
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 面向 **Bugzilla 4.x** 的 MCP 服务器,通过 WebService 的 JSON-RPC(`jsonrpc.cgi`)或 XML-RPC(`xmlrpc.cgi`)调用 Bugzilla,不依赖 5.0 才有的 REST 接口和 API Key。
4
+
5
+ 功能与 `mcp-server-bugzilla`(5.0 版)保持一致:查询 Bug 状态、按版本拉取 Bug 列表、计算版本 Bug 权重数,以及评论、更新、创建 Bug。
6
+
7
+ - 免安装:任何机器上 `npx -y mcp-server-bugzilla4@latest` 即可运行
8
+ - 零第三方依赖:XML-RPC 编解码、Cookie 会话都用 Node.js 内置能力实现
9
+ - 需要 Node.js 18.17 及以上,Windows / macOS / Linux 通用
10
+ - 适用 Bugzilla 4.0 ~ 4.4;5.0 及以上请用 `mcp-server-bugzilla`
11
+
12
+ ## 🚀 快速开始
13
+
14
+ ```bash
15
+ npx -y mcp-server-bugzilla4@latest install
16
+ ```
17
+
18
+ 交互式输入 Bugzilla 地址、账号、密码、协议和权重表,登录校验通过后写入本机检测到的 MCP 客户端(Kiro、Cursor、Claude Desktop、Windsurf、VS Code)。参数与 5.0 版相同:`--client`、`--yes`、`--dry-run`、`--skip-verify`。
19
+
20
+ 校验连接:
21
+
22
+ ```bash
23
+ BUGZILLA_PASSWORD=xxx npx -y mcp-server-bugzilla4@latest verify --url https://bugzilla.example.com --login me@example.com
24
+ ```
25
+
26
+ ## 标准配置
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "bugzilla": {
32
+ "command": "npx",
33
+ "args": ["-y", "mcp-server-bugzilla4@latest"],
34
+ "env": {
35
+ "BUGZILLA_URL": "https://bugzilla.example.com",
36
+ "BUGZILLA_LOGIN": "me@example.com",
37
+ "BUGZILLA_PASSWORD": "your-password",
38
+ "BUGZILLA_PROTOCOL": "auto",
39
+ "BUGZILLA_PRIORITY_WEIGHTS": "P0=5,P1=3,P2=1,P3=0.2"
40
+ }
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ 各客户端的配置文件位置、Claude Code 命令、VS Code `inputs` 写法与 5.0 版 README 相同,只需把包名换成 `mcp-server-bugzilla4`、凭证换成账号密码。
47
+
48
+ ### 选择协议
49
+
50
+ | 协议 | 接口 | 适用情况 |
51
+ | :--- | :--- | :--- |
52
+ | `auto`(默认) | 先 `jsonrpc.cgi`,必要时 `xmlrpc.cgi` | JSON-RPC 返回 Perl 运行时错误(如 `Not a HASH reference at Bugzilla/WebService/User.pm line 53`)或 HTML 页面时,自动切换到 XML-RPC 并重新登录,之后一直使用 XML-RPC |
53
+ | `jsonrpc` | `POST /jsonrpc.cgi` | 服务器装了与 4.0 兼容的 Perl 模块 `JSON::RPC` |
54
+ | `xmlrpc` | `POST /xmlrpc.cgi` | 4.0 默认可用,兼容性最好 |
55
+
56
+ `Not a HASH reference at Bugzilla/WebService/User.pm line 53` 出现在 `User.login` 读取参数时,通常是服务器上的 `JSON::RPC` 模块升级到了 1.x,与 Bugzilla 4.0 的 JSON-RPC 实现不兼容(4.0 依赖 0.9x 的旧接口)。XML-RPC 不经过这个模块,因此 `auto` 模式能绕过。`verify_auth` 的 `protocol_in_use` 和 `protocol_fallback_reason` 会显示实际使用的协议和切换原因。如果两种协议都失败,说明 WebService 在服务端不可用,需要管理员检查 `JSON::RPC`、`SOAP::Lite` 等依赖。
57
+
58
+ 在浏览器里打开 `https://你的bugzilla/jsonrpc.cgi`,看到 JSON 格式的报错说明 JSON-RPC 可用;看到 500 或依赖缺失的报错就用 xmlrpc。
59
+
60
+ ### 认证方式
61
+
62
+ | `BUGZILLA_AUTH_TYPE` | 原理 |
63
+ | :--- | :--- |
64
+ | `cookie`(默认) | 先调用 `User.login`,保存返回的 `Bugzilla_login` / `Bugzilla_logincookie` Cookie,后续请求带上 Cookie。会话失效(错误码 410 / 32000)时自动重新登录一次 |
65
+ | `params` | 每次调用都在参数里带 `Bugzilla_login` / `Bugzilla_password`,不保存会话。反向代理过滤 Set-Cookie 时使用 |
66
+ | `none` | 匿名访问,只能读公开 Bug |
67
+
68
+ 账号密码只放在 POST 请求体里,不出现在 URL 和服务器访问日志中。4.2.7 / 4.4.3 之后的版本登录会返回 token,工具会自动带上 `Bugzilla_token`。
69
+
70
+ ## 🛠️ 工具列表
71
+
72
+ | 工具 | 底层方法 | 说明 |
73
+ | :--- | :--- | :--- |
74
+ | `get_bug_status` | `Bug.get` | 批量查状态、解决结果、优先级、处理人,列出未找到的 ID |
75
+ | `get_bug` | `Bug.get` / `Bug.comments` | 完整信息(含 `cf_*`),可附带描述 |
76
+ | `search_bugs` | `Bug.search` | 按产品 / 组件 / 版本 / 里程碑 / 状态 / 优先级 / 严重程度 / 人员 / 标题子串 / 时间搜索,支持分页和 `fetch_all` |
77
+ | `list_version_bugs` | `Bug.search` | 某产品某(些)版本的 Bug 列表与分组统计 |
78
+ | `get_version_bug_weight` | `Bug.search` | 版本 Bug 权重数,可传 `kloc` 得到千行权重 Bug 率 |
79
+ | `get_bug_history` | `Bug.history` | 字段变更历史与 Reopen 次数 |
80
+ | `get_bug_comments` | `Bug.comments` | 评论列表 |
81
+ | `list_attachments` | `Bug.attachments` | 附件元数据(不下载内容) |
82
+ | `list_products` | `Product.get` / `Bug.legal_values` | 产品及其版本、里程碑、组件 |
83
+ | `get_field_values` | `Bug.fields` / `Bug.legal_values` | 字段合法取值,用于核对权重表 |
84
+ | `search_users` | `User.get` | 按登录名 / 姓名查用户 |
85
+ | `verify_auth` | `Bugzilla.version` / `User.get` | 校验连接、协议和登录 |
86
+ | `add_comment` | `Bug.add_comment` | 添加评论,支持 `dry_run` |
87
+ | `update_bug` | `Bug.update` | 修改状态 / 处理人 / 优先级 / 版本 / 关键字 / CC / 依赖等,支持 `dry_run` |
88
+ | `create_bug` | `Bug.create` | 创建 Bug,支持 `dry_run` |
89
+
90
+ 修改类工具受 `BUGZILLA_READ_ONLY` 约束。
91
+
92
+ ## 与 5.0 版的差异
93
+
94
+ Bugzilla 4.0 的 `Bug.search` 只支持简单字段匹配和"时间 >=",以下条件改在本地对结果过滤,结果的 `warnings` 中会写明服务端返回多少条、本地过滤后剩多少条:
95
+
96
+ - `created_before` / `changed_before`(时间上限)
97
+ - `status_scope=open/closed`(按 `is_open`)
98
+ - `exclude_resolutions`(统计权重时默认排除 INVALID / DUPLICATE / WORKSFORME)
99
+ - `keywords`、`custom_fields`,以及 `BUGZILLA_VERSION_FIELD` 设为 `cf_*` 自定义字段时的版本匹配
100
+
101
+ 不再支持的能力:`quicksearch`、高级条件 `f1/o1/v1`。
102
+
103
+ 其他兼容处理:
104
+ - 4.0 的 `Product.get` 不返回版本 / 组件 / 里程碑,`list_products` 会用 `Bug.legal_values` 补齐
105
+ - 4.0 的 `Bug.search` 不保证排序稳定,分页结果按 ID 去重;如果服务端不支持 `offset`,会停止翻页并提示设置 `BUGZILLA_PAGE_SIZE=0` 一次性拉取
106
+ - `search_bugs` 至少需要一个服务端可用的条件(如 `product`),避免全库扫描
107
+
108
+ ## ⚖️ 版本 Bug 权重
109
+
110
+ 默认权重 `P0=5, P1=3, P2=1, P3=0.2`,设置方式与 5.0 版相同:单次调用传 `weights`,或用 `BUGZILLA_PRIORITY_WEIGHTS` / `--weights` 全局设置。
111
+
112
+ Bugzilla 自带的优先级取值通常不是 `P0`~`P3`(常见为 `P1`~`P5` 或 `Highest`~`Lowest`,各站点可能改过)。权重表里没有的取值会按 `default_weight`(默认 0)计入,并在 `unmatched` 和 `warnings` 中列出。建议先调用 `get_field_values(field="priority")` 查实际取值,再按实际名称配置权重表。
113
+
114
+ ## 🔐 配置项
115
+
116
+ | 环境变量 | 命令行参数 | 说明 |
117
+ | :--- | :--- | :--- |
118
+ | `BUGZILLA_URL` | `--url` | 必填,Bugzilla 根地址(不带 `xmlrpc.cgi`),默认只允许 HTTPS |
119
+ | `BUGZILLA_PROTOCOL` | `--protocol` | `auto`(默认)/ `jsonrpc` / `xmlrpc` |
120
+ | `BUGZILLA_RPC_PATH` | `--rpc-path` | 接口路径,默认 `jsonrpc.cgi` / `xmlrpc.cgi` |
121
+ | `BUGZILLA_AUTH_TYPE` | `--auth-type` | `cookie`(默认)/ `params` / `none` |
122
+ | `BUGZILLA_LOGIN` | `--login` | 登录账号(通常是邮箱) |
123
+ | `BUGZILLA_PASSWORD` / `BUGZILLA_PASSWORD_FILE` | `--password-file` | 密码;不支持明文命令行参数 |
124
+ | `BUGZILLA_READ_ONLY` | `--read-only` | 禁止修改类工具(`dry_run` 仍可用) |
125
+ | `BUGZILLA_PRIORITY_WEIGHTS` | `--weights` | 权重表,默认 `P0=5,P1=3,P2=1,P3=0.2` |
126
+ | `BUGZILLA_WEIGHT_FIELD` | `--weight-field` | 计权字段,默认 `priority` |
127
+ | `BUGZILLA_DEFAULT_WEIGHT` | `--default-weight` | 权重表未覆盖取值的权重,默认 `0` |
128
+ | `BUGZILLA_VERSION_FIELD` | `--version-field` | "版本"对应字段,默认 `version` |
129
+ | `BUGZILLA_EXCLUDE_RESOLUTIONS` | `--exclude-resolutions` | 统计时排除的解决结果,传空表示不排除 |
130
+ | `BUGZILLA_DEFAULT_PRODUCT` | `--default-product` | 未传 product 时使用的产品 |
131
+ | `BUGZILLA_TIMEOUT_MS` | `--timeout` | 请求超时,默认 `60000` |
132
+ | `BUGZILLA_CONCURRENCY` | `--concurrency` | 并发数,默认 `2` |
133
+ | `BUGZILLA_PAGE_SIZE` | `--page-size` | `Bug.search` 分页大小,默认 `500`;`0` 表示不分页 |
134
+ | `BUGZILLA_MAX_RESULTS` | `--max-results` | 单次统计最多拉取的 Bug 数,默认 `10000` |
135
+ | `BUGZILLA_MAX_RETRIES` | — | 只读方法在网络错误 / 429 / 5xx 时的重试次数,默认 `2` |
136
+ | `BUGZILLA_ALLOW_INSECURE_HTTP` | `--allow-insecure-http` | 允许 `http://`。密码会明文传输,仅限可信内网 |
137
+ | `NODE_EXTRA_CA_CERTS` | — | 企业自签 CA 时指向 CA 证书 |
138
+
139
+ ## 📦 发布
140
+
141
+ ```bash
142
+ npm login
143
+ npm test
144
+ npm publish --access public
145
+ ```
146
+
147
+ 也可推送 `v*` Tag,由 `.github/workflows/publish.yml` 自动测试并发布。内网 registry 用法见 5.0 版 README。
148
+
149
+ ## 目录结构
150
+
151
+ ```
152
+ src/
153
+ index.js CLI 入口(serve / install / verify / --help)
154
+ serve.js 启动 MCP Server
155
+ install.js 写入各客户端配置
156
+ cli-args.js 命令行参数 → 环境变量
157
+ mcp/server.js MCP stdio 协议实现
158
+ lib/rpc-client.js JSON-RPC / XML-RPC 客户端(Cookie 会话、自动重登、错误码翻译)
159
+ lib/xmlrpc.js XML-RPC 编解码
160
+ lib/search.js 服务端条件与本地过滤拆分
161
+ lib/weights.js 权重解析与计算
162
+ lib/config.js 环境变量配置
163
+ tools/ 各 Tool 定义
164
+ test/ node:test 单元测试
165
+ ```
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "mcp-server-bugzilla4",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "面向 Bugzilla 4.x 的 MCP Server(JSON-RPC / XML-RPC):Bug 状态 / 版本 Bug 列表 / 版本 Bug 权重 / 历史 / 评论 / 更新 / 创建。npx 免安装使用",
5
+ "keywords": [
6
+ "mcp",
7
+ "mcp-server",
8
+ "model-context-protocol",
9
+ "bugzilla",
10
+ "bugzilla-4",
11
+ "xmlrpc",
12
+ "jsonrpc",
13
+ "defect-density"
14
+ ],
15
+ "type": "module",
16
+ "main": "src/index.js",
17
+ "bin": {
18
+ "mcp-server-bugzilla4": "src/index.js"
19
+ },
20
+ "files": [
21
+ "src",
22
+ "README.md",
23
+ "LICENSE"
24
+ ],
25
+ "scripts": {
26
+ "start": "node src/index.js",
27
+ "test": "node --test test/lib.test.js test/tools.test.js test/cli.test.js",
28
+ "prepublishOnly": "npm test"
29
+ },
30
+ "engines": {
31
+ "node": ">=18.17"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "license": "MIT"
37
+ }
@@ -0,0 +1,57 @@
1
+ import { parseArgs } from 'node:util';
2
+
3
+ /**
4
+ * 命令行参数 → 环境变量映射,命令行优先。
5
+ * 密码不接受明文命令行参数(会进入进程列表和 shell 历史),只能用环境变量或 --password-file。
6
+ */
7
+ export const OPTION_ENV_MAP = {
8
+ url: 'BUGZILLA_URL',
9
+ protocol: 'BUGZILLA_PROTOCOL',
10
+ 'rpc-path': 'BUGZILLA_RPC_PATH',
11
+ 'auth-type': 'BUGZILLA_AUTH_TYPE',
12
+ login: 'BUGZILLA_LOGIN',
13
+ 'password-file': 'BUGZILLA_PASSWORD_FILE',
14
+ weights: 'BUGZILLA_PRIORITY_WEIGHTS',
15
+ 'weight-field': 'BUGZILLA_WEIGHT_FIELD',
16
+ 'default-weight': 'BUGZILLA_DEFAULT_WEIGHT',
17
+ 'version-field': 'BUGZILLA_VERSION_FIELD',
18
+ 'exclude-resolutions': 'BUGZILLA_EXCLUDE_RESOLUTIONS',
19
+ 'default-product': 'BUGZILLA_DEFAULT_PRODUCT',
20
+ timeout: 'BUGZILLA_TIMEOUT_MS',
21
+ concurrency: 'BUGZILLA_CONCURRENCY',
22
+ 'page-size': 'BUGZILLA_PAGE_SIZE',
23
+ 'max-results': 'BUGZILLA_MAX_RESULTS',
24
+ };
25
+
26
+ const BOOLEAN_ENV_MAP = {
27
+ 'read-only': 'BUGZILLA_READ_ONLY',
28
+ 'allow-insecure-http': 'BUGZILLA_ALLOW_INSECURE_HTTP',
29
+ };
30
+
31
+ export function parseCli(argv) {
32
+ const options = {
33
+ help: { type: 'boolean', short: 'h' },
34
+ version: { type: 'boolean', short: 'v' },
35
+ client: { type: 'string', multiple: true },
36
+ yes: { type: 'boolean', short: 'y' },
37
+ 'skip-verify': { type: 'boolean' },
38
+ 'dry-run': { type: 'boolean' },
39
+ name: { type: 'string' },
40
+ password: { type: 'string' },
41
+ };
42
+ for (const key of Object.keys(OPTION_ENV_MAP)) options[key] = { type: 'string' };
43
+ for (const key of Object.keys(BOOLEAN_ENV_MAP)) options[key] = { type: 'boolean' };
44
+
45
+ const { values, positionals } = parseArgs({ args: argv, options, allowPositionals: true, strict: true });
46
+ if (values.password !== undefined) {
47
+ throw new Error('出于安全考虑不支持 --password 明文参数,请改用环境变量 BUGZILLA_PASSWORD 或 --password-file');
48
+ }
49
+ return { command: positionals[0] || 'serve', positionals, values };
50
+ }
51
+
52
+ export function buildEnv(values, baseEnv = process.env) {
53
+ const env = { ...baseEnv };
54
+ for (const [flag, name] of Object.entries(OPTION_ENV_MAP)) if (values[flag] !== undefined) env[name] = values[flag];
55
+ for (const [flag, name] of Object.entries(BOOLEAN_ENV_MAP)) if (values[flag]) env[name] = 'true';
56
+ return env;
57
+ }
package/src/index.js ADDED
@@ -0,0 +1,103 @@
1
+ #!/usr/bin/env node
2
+ import { buildEnv, parseCli } from './cli-args.js';
3
+ import { describeConfig, loadConfig } from './lib/config.js';
4
+ import { BugzillaRpcClient } from './lib/rpc-client.js';
5
+ import { PACKAGE } from './package-info.js';
6
+
7
+ const HELP = `${PACKAGE.name} v${PACKAGE.version} —— 面向 Bugzilla 4.x 的 MCP Server(JSON-RPC / XML-RPC)
8
+
9
+ 用法:
10
+ npx -y ${PACKAGE.name}@latest [选项] 以 stdio 方式启动 MCP Server(供 MCP 客户端调用)
11
+ npx -y ${PACKAGE.name}@latest install [选项] 交互式写入 Kiro / Cursor / Claude Desktop / Windsurf / VS Code 配置
12
+ npx -y ${PACKAGE.name}@latest verify [选项] 校验 Bugzilla 地址、协议与登录
13
+
14
+ 连接选项(也可用括号内的环境变量配置,命令行优先):
15
+ --url <url> Bugzilla 根地址,必须 HTTPS(BUGZILLA_URL)
16
+ --protocol <p> auto | jsonrpc | xmlrpc,默认 auto(JSON-RPC 出错时自动切到 XML-RPC)(BUGZILLA_PROTOCOL)
17
+ --rpc-path <path> 接口路径,默认 jsonrpc.cgi / xmlrpc.cgi(BUGZILLA_RPC_PATH)
18
+ --auth-type <type> cookie | params | none,默认有账号时 cookie(BUGZILLA_AUTH_TYPE)
19
+ --login <email> 登录账号(BUGZILLA_LOGIN)
20
+ --password-file <path> 密码文件(BUGZILLA_PASSWORD_FILE);或直接设置 BUGZILLA_PASSWORD
21
+ --read-only 禁止 add_comment / update_bug / create_bug(BUGZILLA_READ_ONLY)
22
+ --timeout <ms> 请求超时,默认 60000(BUGZILLA_TIMEOUT_MS)
23
+ --concurrency <n> 并发数,默认 2(BUGZILLA_CONCURRENCY)
24
+ --page-size <n> Bug.search 分页大小,默认 500,0 表示不分页(BUGZILLA_PAGE_SIZE)
25
+ --max-results <n> 单次统计最多拉取的 Bug 数,默认 10000(BUGZILLA_MAX_RESULTS)
26
+ --allow-insecure-http 允许 http:// 地址,仅限内网(BUGZILLA_ALLOW_INSECURE_HTTP)
27
+
28
+ 权重与版本选项:
29
+ --weights <P0=5,P1=3,...> 优先级权重表,默认 P0=5,P1=3,P2=1,P3=0.2(BUGZILLA_PRIORITY_WEIGHTS)
30
+ --weight-field <field> 按哪个字段计权,默认 priority(BUGZILLA_WEIGHT_FIELD)
31
+ --default-weight <n> 权重表未覆盖的取值使用的权重,默认 0(BUGZILLA_DEFAULT_WEIGHT)
32
+ --version-field <field> "版本"对应的字段,默认 version(BUGZILLA_VERSION_FIELD)
33
+ --exclude-resolutions <A,B> 统计时排除的解决结果,默认 INVALID,DUPLICATE,WORKSFORME(BUGZILLA_EXCLUDE_RESOLUTIONS)
34
+ --default-product <name> 默认产品(BUGZILLA_DEFAULT_PRODUCT)
35
+
36
+ install 选项:
37
+ --client <id> kiro | cursor | claude-desktop | windsurf | vscode | claude-code | all
38
+ --name <name> 写入配置的服务名,默认 bugzilla
39
+ -y, --yes 不询问,写入所有检测到的客户端(密码需通过环境变量 / 文件提供)
40
+ --skip-verify 写入前不校验登录
41
+ --dry-run 只打印将要写入的内容
42
+
43
+ 其他:
44
+ -h, --help 显示帮助
45
+ -v, --version 显示版本
46
+
47
+ 出于安全考虑,密码不支持以明文命令行参数传入。`;
48
+
49
+ async function main() {
50
+ let parsed;
51
+ try {
52
+ parsed = parseCli(process.argv.slice(2));
53
+ } catch (e) {
54
+ process.stderr.write(`${e.message}\n\n运行 npx -y ${PACKAGE.name}@latest --help 查看用法\n`);
55
+ process.exit(2);
56
+ }
57
+ const { command, values } = parsed;
58
+ if (values.help || command === 'help') {
59
+ process.stdout.write(`${HELP}\n`);
60
+ return;
61
+ }
62
+ if (values.version) {
63
+ process.stdout.write(`${PACKAGE.version}\n`);
64
+ return;
65
+ }
66
+
67
+ const env = buildEnv(values);
68
+ switch (command) {
69
+ case 'serve': {
70
+ const { serve } = await import('./serve.js');
71
+ await serve(env);
72
+ return;
73
+ }
74
+ case 'install': {
75
+ const { runInstall } = await import('./install.js');
76
+ await runInstall(values, env);
77
+ return;
78
+ }
79
+ case 'verify': {
80
+ const config = loadConfig(env);
81
+ process.stderr.write(`配置:${JSON.stringify(describeConfig(config))}\n`);
82
+ const client = new BugzillaRpcClient(config);
83
+ client.onProtocolSwitch = (e) => process.stderr.write(`JSON-RPC 服务端出错,已自动切换到 XML-RPC:${e.message}\n`);
84
+ const version = await client.version().then((r) => r?.version);
85
+ process.stderr.write(`Bugzilla 版本:${version}\n`);
86
+ if (config.authType === 'none') {
87
+ process.stderr.write('匿名模式,跳过登录校验\n');
88
+ return;
89
+ }
90
+ const me = await client.whoami();
91
+ process.stderr.write(`✔ 登录有效:${me?.real_name || ''} <${me?.name || me?.id}>\n`);
92
+ return;
93
+ }
94
+ default:
95
+ process.stderr.write(`未知命令:${command}\n\n${HELP}\n`);
96
+ process.exit(2);
97
+ }
98
+ }
99
+
100
+ main().catch((e) => {
101
+ process.stderr.write(`✘ ${e.message}\n`);
102
+ process.exit(1);
103
+ });
package/src/install.js ADDED
@@ -0,0 +1,244 @@
1
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import { createInterface } from 'node:readline/promises';
5
+ import { loadConfig } from './lib/config.js';
6
+ import { BugzillaRpcClient } from './lib/rpc-client.js';
7
+ import { PACKAGE } from './package-info.js';
8
+
9
+ /** 写入客户端配置时保留的环境变量(只写用户实际提供的) */
10
+ const PERSISTED_ENV = [
11
+ 'BUGZILLA_URL',
12
+ 'BUGZILLA_PROTOCOL',
13
+ 'BUGZILLA_RPC_PATH',
14
+ 'BUGZILLA_AUTH_TYPE',
15
+ 'BUGZILLA_LOGIN',
16
+ 'BUGZILLA_PASSWORD',
17
+ 'BUGZILLA_PASSWORD_FILE',
18
+ 'BUGZILLA_READ_ONLY',
19
+ 'BUGZILLA_PRIORITY_WEIGHTS',
20
+ 'BUGZILLA_WEIGHT_FIELD',
21
+ 'BUGZILLA_DEFAULT_WEIGHT',
22
+ 'BUGZILLA_VERSION_FIELD',
23
+ 'BUGZILLA_EXCLUDE_RESOLUTIONS',
24
+ 'BUGZILLA_DEFAULT_PRODUCT',
25
+ 'BUGZILLA_TIMEOUT_MS',
26
+ 'BUGZILLA_CONCURRENCY',
27
+ 'BUGZILLA_MAX_RESULTS',
28
+ 'BUGZILLA_ALLOW_INSECURE_HTTP',
29
+ ];
30
+ const PLAINTEXT_SECRETS = ['BUGZILLA_PASSWORD'];
31
+ /**
32
+ * 支持自动写入配置的 MCP 客户端。
33
+ * rootKey:配置文件中存放 MCP Server 的字段;detect:存在即认为本机安装了该客户端。
34
+ */
35
+ export function getClients({ home = homedir(), platform = process.platform, env = process.env } = {}) {
36
+ const appData = env.APPDATA || join(home, 'AppData', 'Roaming');
37
+ const userConfigDir =
38
+ platform === 'win32' ? appData : platform === 'darwin' ? join(home, 'Library', 'Application Support') : env.XDG_CONFIG_HOME || join(home, '.config');
39
+
40
+ return [
41
+ { id: 'kiro', label: 'Kiro', path: join(home, '.kiro', 'settings', 'mcp.json'), rootKey: 'mcpServers', detect: join(home, '.kiro') },
42
+ { id: 'cursor', label: 'Cursor', path: join(home, '.cursor', 'mcp.json'), rootKey: 'mcpServers', detect: join(home, '.cursor') },
43
+ {
44
+ id: 'claude-desktop',
45
+ label: 'Claude Desktop',
46
+ path: join(userConfigDir, 'Claude', 'claude_desktop_config.json'),
47
+ rootKey: 'mcpServers',
48
+ detect: join(userConfigDir, 'Claude'),
49
+ },
50
+ {
51
+ id: 'windsurf',
52
+ label: 'Windsurf',
53
+ path: join(home, '.codeium', 'windsurf', 'mcp_config.json'),
54
+ rootKey: 'mcpServers',
55
+ detect: join(home, '.codeium', 'windsurf'),
56
+ },
57
+ {
58
+ id: 'vscode',
59
+ label: 'VS Code(用户级 mcp.json)',
60
+ path: join(userConfigDir, 'Code', 'User', 'mcp.json'),
61
+ rootKey: 'servers',
62
+ detect: join(userConfigDir, 'Code', 'User'),
63
+ stdioType: true,
64
+ },
65
+ ];
66
+ }
67
+
68
+ export function buildServerEntry(env, { stdioType = false } = {}) {
69
+ const persisted = {};
70
+ for (const key of PERSISTED_ENV) {
71
+ if (env[key]) persisted[key] = env[key];
72
+ }
73
+ const entry = { command: 'npx', args: ['-y', `${PACKAGE.name}@latest`], env: persisted };
74
+ return stdioType ? { type: 'stdio', ...entry } : entry;
75
+ }
76
+
77
+ /** 合并写入客户端配置;原文件先备份为 .bak。JSON 解析失败(如带注释)时不覆盖 */
78
+ export function writeClientConfig(client, serverName, entry, { dryRun = false } = {}) {
79
+ let data = {};
80
+ if (existsSync(client.path)) {
81
+ const raw = readFileSync(client.path, 'utf8');
82
+ if (raw.trim()) {
83
+ try {
84
+ data = JSON.parse(raw);
85
+ } catch (e) {
86
+ throw new Error(`${client.path} 不是标准 JSON(可能含注释),为避免破坏原配置已跳过,请手动添加:${e.message}`);
87
+ }
88
+ }
89
+ }
90
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error(`${client.path} 顶层不是对象,已跳过`);
91
+
92
+ const existed = Boolean(data[client.rootKey]?.[serverName]);
93
+ data[client.rootKey] = { ...(data[client.rootKey] || {}), [serverName]: entry };
94
+ if (dryRun) return { path: client.path, existed, content: data };
95
+
96
+ mkdirSync(dirname(client.path), { recursive: true });
97
+ if (existsSync(client.path)) copyFileSync(client.path, `${client.path}.bak`);
98
+ writeFileSync(client.path, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
99
+ return { path: client.path, existed };
100
+ }
101
+
102
+ export function claudeCodeCommand(serverName, entry) {
103
+ const envArgs = Object.entries(entry.env).map(([k, v]) => `--env ${k}=${quoteShell(v)}`);
104
+ return ['claude mcp add', serverName, '--scope user', ...envArgs, '--', 'npx -y', `${PACKAGE.name}@latest`].join(' ');
105
+ }
106
+
107
+ function quoteShell(v) {
108
+ return /^[\w@%+=:,./-]+$/.test(v) ? v : `"${String(v).replace(/(["\\$`])/g, '\\$1')}"`;
109
+ }
110
+
111
+ /**
112
+ * install 子命令:交互式收集连接信息 → 校验凭证 → 写入检测到的 MCP 客户端配置。
113
+ * @param {object} values 命令行参数
114
+ * @param {object} env 合并命令行参数后的环境变量
115
+ */
116
+ export async function runInstall(values, env, deps = {}) {
117
+ const out = deps.out || ((s) => process.stderr.write(`${s}\n`));
118
+ const interactive = deps.interactive ?? (process.stdin.isTTY && !values.yes);
119
+ const prompter = interactive ? deps.prompter || createPrompter() : null;
120
+ const clients = getClients(deps);
121
+ const serverName = values.name || 'bugzilla';
122
+
123
+ try {
124
+ const finalEnv = { ...env };
125
+ if (!finalEnv.BUGZILLA_URL) {
126
+ if (!prompter) throw new Error('缺少 Bugzilla 地址:请传 --url 或设置 BUGZILLA_URL');
127
+ finalEnv.BUGZILLA_URL = (await prompter.ask('Bugzilla 地址(如 https://bugzilla.example.com):')).trim();
128
+ }
129
+ if (finalEnv.BUGZILLA_AUTH_TYPE !== 'none') {
130
+ if (!finalEnv.BUGZILLA_LOGIN) {
131
+ if (!prompter) throw new Error('缺少登录账号:请传 --login 或设置 BUGZILLA_LOGIN');
132
+ finalEnv.BUGZILLA_LOGIN = (await prompter.ask('Bugzilla 登录账号(通常是邮箱):')).trim();
133
+ }
134
+ if (!finalEnv.BUGZILLA_PASSWORD && !finalEnv.BUGZILLA_PASSWORD_FILE) {
135
+ if (!prompter) throw new Error('缺少凭证:请设置 BUGZILLA_PASSWORD 环境变量或传 --password-file');
136
+ finalEnv.BUGZILLA_PASSWORD = (await prompter.askHidden('Bugzilla 密码(输入不回显):')).trim();
137
+ }
138
+ }
139
+ if (!finalEnv.BUGZILLA_PROTOCOL && prompter) {
140
+ const p = (await prompter.ask('调用协议 jsonrpc / xmlrpc(回车使用 jsonrpc):')).trim().toLowerCase();
141
+ if (p) finalEnv.BUGZILLA_PROTOCOL = p;
142
+ }
143
+ if (!finalEnv.BUGZILLA_PRIORITY_WEIGHTS && prompter) {
144
+ const w = (await prompter.ask('优先级权重(回车使用默认 P0=5,P1=3,P2=1,P3=0.2):')).trim();
145
+ if (w) finalEnv.BUGZILLA_PRIORITY_WEIGHTS = w;
146
+ }
147
+ const config = loadConfig(finalEnv);
148
+ if (!values['skip-verify'] && config.authType !== 'none') {
149
+ const self = await (deps.verify || defaultVerify)(config);
150
+ out(`✔ 凭证校验通过:${self?.name || self?.id}`);
151
+ }
152
+
153
+ // 选择客户端
154
+ let selected;
155
+ if (values.client?.length) {
156
+ const ids = values.client.flatMap((c) => c.split(',')).map((c) => c.trim());
157
+ if (ids.includes('all')) selected = clients;
158
+ else {
159
+ const unknown = ids.filter((id) => id !== 'claude-code' && !clients.some((c) => c.id === id));
160
+ if (unknown.length) throw new Error(`未知客户端:${unknown.join(', ')},可选 ${clients.map((c) => c.id).join(' / ')} / claude-code / all`);
161
+ selected = clients.filter((c) => ids.includes(c.id));
162
+ }
163
+ } else {
164
+ const detected = clients.filter((c) => existsSync(c.detect));
165
+ if (!detected.length) {
166
+ out('未检测到已安装的 MCP 客户端,可用 --client 指定,或参考下方配置手动添加。');
167
+ selected = [];
168
+ } else if (prompter) {
169
+ selected = [];
170
+ for (const c of detected) {
171
+ const answer = (await prompter.ask(`写入 ${c.label} 配置(${c.path})?[Y/n] `)).trim().toLowerCase();
172
+ if (answer === '' || answer === 'y' || answer === 'yes') selected.push(c);
173
+ }
174
+ } else {
175
+ selected = detected;
176
+ }
177
+ }
178
+
179
+ const results = [];
180
+ for (const c of selected) {
181
+ try {
182
+ const r = writeClientConfig(c, serverName, buildServerEntry(finalEnv, c), { dryRun: values['dry-run'] });
183
+ results.push(r);
184
+ out(`${values['dry-run'] ? '[dry-run] 将写入' : r.existed ? '✔ 已更新' : '✔ 已添加'} ${c.label}:${r.path}`);
185
+ // 只展示本服务的条目并遮盖凭证,避免把配置文件里其他服务的密钥打印到终端
186
+ if (values['dry-run']) out(JSON.stringify({ [c.rootKey]: { [serverName]: maskEntry(r.content[c.rootKey][serverName]) } }, null, 2));
187
+ } catch (e) {
188
+ out(`✘ ${c.label}:${e.message}`);
189
+ }
190
+ }
191
+
192
+ const entry = buildServerEntry(finalEnv);
193
+ if (values.client?.includes('claude-code') || !selected.length) {
194
+ out('\nClaude Code 请执行:');
195
+ out(` ${claudeCodeCommand(serverName, entry)}`);
196
+ }
197
+ if (!selected.length) {
198
+ out('\n通用配置(mcpServers 字段):');
199
+ out(JSON.stringify({ mcpServers: { [serverName]: entry } }, null, 2));
200
+ }
201
+ if (PLAINTEXT_SECRETS.some((k) => entry.env[k]) && (results.length || !selected.length)) {
202
+ out('\n⚠ 凭证以明文写入了客户端配置文件,请勿把该文件提交到代码仓库;更安全的做法是改用 --password-file 指向仅自己可读的文件。');
203
+ }
204
+ if (results.length) out('\n重启(或在 MCP 面板中重连)对应客户端后生效。');
205
+ return results;
206
+ } finally {
207
+ prompter?.close();
208
+ }
209
+ }
210
+
211
+ function maskEntry(entry) {
212
+ const env = { ...entry.env };
213
+ for (const key of PLAINTEXT_SECRETS) if (env[key]) env[key] = '******';
214
+ return { ...entry, env };
215
+ }
216
+
217
+ async function defaultVerify(config) {
218
+ return new BugzillaRpcClient(config).whoami();
219
+ }
220
+
221
+ function createPrompter() {
222
+ const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
223
+ let muted = false;
224
+ const originalWrite = rl._writeToOutput?.bind(rl);
225
+ if (originalWrite) {
226
+ rl._writeToOutput = (s) => {
227
+ if (!muted) originalWrite(s);
228
+ };
229
+ }
230
+ return {
231
+ ask: (q) => rl.question(q),
232
+ async askHidden(q) {
233
+ process.stderr.write(q);
234
+ muted = true;
235
+ try {
236
+ return await rl.question('');
237
+ } finally {
238
+ muted = false;
239
+ process.stderr.write('\n');
240
+ }
241
+ },
242
+ close: () => rl.close(),
243
+ };
244
+ }