mcp-server-bugzilla4 0.0.0-stage → 1.0.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.
@@ -0,0 +1,111 @@
1
+ import { round } from './util.js';
2
+
3
+ /**
4
+ * 解析权重配置,支持两种写法:
5
+ * "P0=5,P1=3,P2=1,P3=0.2" 或 '{"P0":5,"P1":3}'
6
+ * 键不区分大小写(内部统一转大写比较),值必须是非负数。
7
+ */
8
+ export function parseWeights(input, source = 'weights') {
9
+ let obj;
10
+ if (input && typeof input === 'object') {
11
+ obj = input;
12
+ } else {
13
+ const text = String(input || '').trim();
14
+ if (!text) throw new Error(`${source} 不能为空`);
15
+ if (text.startsWith('{')) {
16
+ try {
17
+ obj = JSON.parse(text);
18
+ } catch (e) {
19
+ throw new Error(`${source} 不是合法 JSON:${e.message}`);
20
+ }
21
+ } else {
22
+ obj = {};
23
+ for (const pair of text.split(/[,;\n]/).map((s) => s.trim()).filter(Boolean)) {
24
+ const m = /^([^=:]+)[=:]\s*(.+)$/.exec(pair);
25
+ if (!m) throw new Error(`${source} 格式错误:"${pair}",应为 P0=5,P1=3`);
26
+ obj[m[1].trim()] = m[2].trim();
27
+ }
28
+ }
29
+ }
30
+
31
+ const weights = {};
32
+ for (const [key, value] of Object.entries(obj)) {
33
+ const name = String(key).trim();
34
+ const n = Number(value);
35
+ if (!name) throw new Error(`${source} 存在空的优先级名称`);
36
+ if (!Number.isFinite(n) || n < 0) throw new Error(`${source} 中 ${name} 的权重必须是非负数,当前值:${value}`);
37
+ weights[name] = n;
38
+ }
39
+ if (!Object.keys(weights).length) throw new Error(`${source} 至少需要一项`);
40
+ return weights;
41
+ }
42
+
43
+ /** 构造不区分大小写的查找函数 */
44
+ function buildLookup(weights) {
45
+ const map = new Map(Object.entries(weights).map(([k, v]) => [k.toUpperCase(), { key: k, weight: v }]));
46
+ return (value) => map.get(String(value ?? '').trim().toUpperCase());
47
+ }
48
+
49
+ /**
50
+ * 计算 Bug 权重。
51
+ * @param {object[]} bugs Bugzilla Bug 对象
52
+ * @param {object} opts
53
+ * @param {Record<string, number>} opts.weights 权重表
54
+ * @param {string} opts.field 按哪个字段取权重(priority / severity / 自定义字段)
55
+ * @param {number} opts.defaultWeight 未在权重表中的取值使用的权重
56
+ * @param {string} [opts.groupBy] 额外分组字段(component / status / assigned_to ...)
57
+ */
58
+ export function computeWeight(bugs, { weights, field, defaultWeight = 0, groupBy } = {}) {
59
+ const lookup = buildLookup(weights);
60
+ const byLevel = {};
61
+ for (const key of Object.keys(weights)) byLevel[key] = { weight: weights[key], count: 0, subtotal: 0, bug_ids: [] };
62
+ const unmatched = {};
63
+ const groups = {};
64
+ let total = 0;
65
+
66
+ for (const bug of bugs) {
67
+ const raw = fieldValue(bug, field);
68
+ const hit = lookup(raw);
69
+ const w = hit ? hit.weight : defaultWeight;
70
+ total += w;
71
+ if (hit) {
72
+ const slot = byLevel[hit.key];
73
+ slot.count += 1;
74
+ slot.subtotal += w;
75
+ slot.bug_ids.push(bug.id);
76
+ } else {
77
+ const label = raw === undefined || raw === null || raw === '' ? '(空)' : String(raw);
78
+ const slot = (unmatched[label] ||= { weight: defaultWeight, count: 0, subtotal: 0, bug_ids: [] });
79
+ slot.count += 1;
80
+ slot.subtotal += w;
81
+ slot.bug_ids.push(bug.id);
82
+ }
83
+ if (groupBy) {
84
+ const g = String(fieldValue(bug, groupBy) ?? '(空)');
85
+ const slot = (groups[g] ||= { count: 0, weight: 0 });
86
+ slot.count += 1;
87
+ slot.weight += w;
88
+ }
89
+ }
90
+
91
+ for (const slot of [...Object.values(byLevel), ...Object.values(unmatched)]) slot.subtotal = round(slot.subtotal, 4);
92
+ for (const slot of Object.values(groups)) slot.weight = round(slot.weight, 4);
93
+
94
+ return {
95
+ total_weight: round(total, 4),
96
+ bug_count: bugs.length,
97
+ by_level: byLevel,
98
+ unmatched: Object.keys(unmatched).length ? unmatched : undefined,
99
+ groups: groupBy ? sortGroups(groups) : undefined,
100
+ };
101
+ }
102
+
103
+ function fieldValue(bug, field) {
104
+ const v = bug?.[field];
105
+ if (v && typeof v === 'object' && !Array.isArray(v)) return v.name ?? v.real_name ?? v.email;
106
+ return v;
107
+ }
108
+
109
+ function sortGroups(groups) {
110
+ return Object.fromEntries(Object.entries(groups).sort((a, b) => b[1].weight - a[1].weight));
111
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * 零依赖的 XML-RPC 编解码,覆盖 Bugzilla 4.0 WebService 用到的类型:
3
+ * string / int / i4 / i8 / double / boolean / dateTime.iso8601 / base64 / struct / array / nil
4
+ */
5
+
6
+ /** 日期参数包装:JSON-RPC 输出 "YYYY-MM-DDTHH:MM:SSZ",XML-RPC 输出 dateTime.iso8601 */
7
+ export class RpcDateTime {
8
+ constructor(date) {
9
+ this.date = date instanceof Date ? date : new Date(date);
10
+ if (Number.isNaN(this.date.getTime())) throw new Error(`无效时间:${date}`);
11
+ }
12
+
13
+ toJSON() {
14
+ return this.date.toISOString().replace(/\.\d{3}Z$/, 'Z');
15
+ }
16
+
17
+ toXmlRpc() {
18
+ return this.toJSON().replace(/-/g, '').replace(/Z$/, '');
19
+ }
20
+ }
21
+
22
+ export function encodeCall(method, params) {
23
+ return `<?xml version="1.0" encoding="UTF-8"?>\n<methodCall><methodName>${escapeXml(method)}</methodName><params><param>${encodeValue(params)}</param></params></methodCall>`;
24
+ }
25
+
26
+ export function encodeValue(v) {
27
+ if (v instanceof RpcDateTime) return `<value><dateTime.iso8601>${v.toXmlRpc()}</dateTime.iso8601></value>`;
28
+ if (v === null || v === undefined) return '<value><nil/></value>';
29
+ if (typeof v === 'boolean') return `<value><boolean>${v ? 1 : 0}</boolean></value>`;
30
+ if (typeof v === 'number') {
31
+ if (!Number.isFinite(v)) throw new Error(`无法编码数字:${v}`);
32
+ return Number.isInteger(v) ? `<value><int>${v}</int></value>` : `<value><double>${v}</double></value>`;
33
+ }
34
+ if (typeof v === 'string') return `<value><string>${escapeXml(v)}</string></value>`;
35
+ if (Array.isArray(v)) return `<value><array><data>${v.map(encodeValue).join('')}</data></array></value>`;
36
+ if (typeof v === 'object') {
37
+ const members = Object.entries(v)
38
+ .filter(([, val]) => val !== undefined)
39
+ .map(([k, val]) => `<member><name>${escapeXml(k)}</name>${encodeValue(val)}</member>`)
40
+ .join('');
41
+ return `<value><struct>${members}</struct></value>`;
42
+ }
43
+ throw new Error(`无法编码类型:${typeof v}`);
44
+ }
45
+
46
+ export class XmlRpcFault extends Error {
47
+ constructor(code, message) {
48
+ super(message);
49
+ this.code = code;
50
+ }
51
+ }
52
+
53
+ /** 解析 methodResponse:成功返回值,fault 抛出 XmlRpcFault */
54
+ export function decodeResponse(xml) {
55
+ const root = parseXml(xml);
56
+ const response = find(root, 'methodResponse');
57
+ if (!response) throw new Error('不是合法的 XML-RPC 响应');
58
+ const fault = find(response, 'fault');
59
+ if (fault) {
60
+ const v = decodeValue(find(fault, 'value'));
61
+ throw new XmlRpcFault(v?.faultCode, String(v?.faultString ?? 'XML-RPC fault'));
62
+ }
63
+ const param = find(find(response, 'params'), 'param');
64
+ return param ? decodeValue(find(param, 'value')) : null;
65
+ }
66
+
67
+ function decodeValue(node) {
68
+ if (!node) return null;
69
+ const typed = node.children.find((c) => typeof c !== 'string');
70
+ if (!typed) return textOf(node);
71
+ const text = textOf(typed);
72
+ switch (typed.name) {
73
+ case 'string':
74
+ return text;
75
+ case 'int':
76
+ case 'i4':
77
+ case 'i8':
78
+ return Number.parseInt(text, 10);
79
+ case 'double':
80
+ return Number(text);
81
+ case 'boolean':
82
+ return text.trim() === '1' || text.trim().toLowerCase() === 'true';
83
+ case 'nil':
84
+ return null;
85
+ case 'base64':
86
+ return Buffer.from(text.trim(), 'base64').toString('utf8');
87
+ case 'dateTime.iso8601':
88
+ return xmlDateToIso(text.trim());
89
+ case 'array':
90
+ return (find(typed, 'data')?.children || []).filter((c) => c.name === 'value').map(decodeValue);
91
+ case 'struct': {
92
+ const out = {};
93
+ for (const m of typed.children.filter((c) => c.name === 'member')) {
94
+ out[textOf(find(m, 'name'))] = decodeValue(find(m, 'value'));
95
+ }
96
+ return out;
97
+ }
98
+ default:
99
+ return text;
100
+ }
101
+ }
102
+
103
+ /** "20260101T12:00:00" / "2026-01-01T12:00:00Z" → "2026-01-01T12:00:00Z"(Bugzilla 返回的时间为 UTC) */
104
+ export function xmlDateToIso(s) {
105
+ const m = /^(\d{4})-?(\d{2})-?(\d{2})T(\d{2}):?(\d{2}):?(\d{2})/.exec(s);
106
+ return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z` : s;
107
+ }
108
+
109
+ /** 极简 XML 解析:只处理元素、文本、实体和 CDATA,足够解析 XML-RPC 响应 */
110
+ export function parseXml(xml) {
111
+ const root = { name: '#root', children: [] };
112
+ const stack = [root];
113
+ const re = /<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[^>]*>|<(\/?)([\w.:-]+)[^>]*?(\/?)>|([^<]+)/g;
114
+ let m;
115
+ while ((m = re.exec(String(xml || '')))) {
116
+ const top = stack[stack.length - 1];
117
+ if (m[1] !== undefined) top.children.push(m[1]);
118
+ else if (m[5] !== undefined) top.children.push(decodeEntities(m[5]));
119
+ else if (m[3]) {
120
+ if (m[2] === '/') {
121
+ if (stack.length > 1) stack.pop();
122
+ } else {
123
+ const node = { name: m[3], children: [] };
124
+ top.children.push(node);
125
+ if (m[4] !== '/') stack.push(node);
126
+ }
127
+ }
128
+ }
129
+ return root;
130
+ }
131
+
132
+ function find(node, name) {
133
+ return node?.children?.find((c) => typeof c !== 'string' && c.name === name);
134
+ }
135
+
136
+ function textOf(node) {
137
+ return (node?.children || []).filter((c) => typeof c === 'string').join('');
138
+ }
139
+
140
+ function decodeEntities(s) {
141
+ return s.replace(/&(#x[0-9a-f]+|#\d+|lt|gt|amp|quot|apos);/gi, (_, e) => {
142
+ const k = e.toLowerCase();
143
+ if (k === 'lt') return '<';
144
+ if (k === 'gt') return '>';
145
+ if (k === 'amp') return '&';
146
+ if (k === 'quot') return '"';
147
+ if (k === 'apos') return "'";
148
+ return String.fromCodePoint(k.startsWith('#x') ? Number.parseInt(k.slice(2), 16) : Number.parseInt(k.slice(1), 10));
149
+ });
150
+ }
151
+
152
+ function escapeXml(s) {
153
+ return String(s)
154
+ .replace(/&/g, '&amp;')
155
+ .replace(/</g, '&lt;')
156
+ .replace(/>/g, '&gt;')
157
+ // XML 1.0 不允许大部分控制字符
158
+ .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, '');
159
+ }
@@ -0,0 +1,145 @@
1
+ import { createInterface } from 'node:readline';
2
+ import { validateArgs } from '../lib/util.js';
3
+
4
+ /**
5
+ * 零依赖的 MCP Server(stdio 传输,JSON-RPC 2.0,消息以换行分隔)。
6
+ * 实现 initialize / ping / tools/list / tools/call。
7
+ * 规范:https://modelcontextprotocol.io/specification
8
+ */
9
+ export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
10
+
11
+ const JSONRPC_PARSE_ERROR = -32700;
12
+ const JSONRPC_INVALID_REQUEST = -32600;
13
+ const JSONRPC_METHOD_NOT_FOUND = -32601;
14
+ const JSONRPC_INVALID_PARAMS = -32602;
15
+ const JSONRPC_INTERNAL_ERROR = -32603;
16
+
17
+ export class McpServer {
18
+ /**
19
+ * @param {object} opts
20
+ * @param {{name: string, version: string}} opts.info
21
+ * @param {Array<{name, description, inputSchema, handler}>} opts.tools
22
+ * @param {object} opts.context 传给 handler 的上下文
23
+ * @param {(msg: string) => void} [opts.log]
24
+ * @param {string} [opts.instructions]
25
+ */
26
+ constructor({ info, tools, context, log = () => {}, instructions }) {
27
+ this.info = info;
28
+ this.tools = new Map(tools.map((t) => [t.name, t]));
29
+ this.context = context;
30
+ this.log = log;
31
+ this.instructions = instructions;
32
+ this.write = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`);
33
+ }
34
+
35
+ listen(input = process.stdin, write) {
36
+ if (write) this.write = write;
37
+ const rl = createInterface({ input, crlfDelay: Infinity });
38
+ rl.on('line', (line) => {
39
+ if (!line.trim()) return;
40
+ this.handleLine(line).catch((e) => this.log(`处理消息异常:${e.stack || e.message}`));
41
+ });
42
+ return new Promise((resolve) => rl.on('close', resolve));
43
+ }
44
+
45
+ async handleLine(line) {
46
+ let msg;
47
+ try {
48
+ msg = JSON.parse(line);
49
+ } catch {
50
+ this.write(errorResponse(null, JSONRPC_PARSE_ERROR, 'Parse error'));
51
+ return;
52
+ }
53
+ if (Array.isArray(msg)) {
54
+ const responses = (await Promise.all(msg.map((m) => this.handleMessage(m)))).filter(Boolean);
55
+ if (responses.length) this.write(responses);
56
+ return;
57
+ }
58
+ const response = await this.handleMessage(msg);
59
+ if (response) this.write(response);
60
+ }
61
+
62
+ /** 处理单条消息;通知(无 id)不返回响应 */
63
+ async handleMessage(msg) {
64
+ if (!msg || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
65
+ // 客户端发回的响应(本服务不主动发请求)直接忽略
66
+ if (msg && msg.jsonrpc === '2.0' && ('result' in msg || 'error' in msg)) return null;
67
+ return errorResponse(msg?.id ?? null, JSONRPC_INVALID_REQUEST, 'Invalid Request');
68
+ }
69
+ const isNotification = msg.id === undefined || msg.id === null;
70
+
71
+ try {
72
+ const result = await this.dispatch(msg.method, msg.params || {});
73
+ if (isNotification) return null;
74
+ return { jsonrpc: '2.0', id: msg.id, result };
75
+ } catch (e) {
76
+ if (isNotification) return null;
77
+ return errorResponse(msg.id, e.rpcCode || JSONRPC_INTERNAL_ERROR, e.message);
78
+ }
79
+ }
80
+
81
+ async dispatch(method, params) {
82
+ switch (method) {
83
+ case 'initialize': {
84
+ const requested = params.protocolVersion;
85
+ const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : SUPPORTED_PROTOCOL_VERSIONS[0];
86
+ this.log(`客户端已连接:${params.clientInfo?.name || 'unknown'},协议版本 ${protocolVersion}`);
87
+ return {
88
+ protocolVersion,
89
+ capabilities: { tools: { listChanged: false } },
90
+ serverInfo: this.info,
91
+ instructions: this.instructions,
92
+ };
93
+ }
94
+ case 'notifications/initialized':
95
+ case 'notifications/cancelled':
96
+ return {};
97
+ case 'ping':
98
+ return {};
99
+ case 'tools/list':
100
+ return {
101
+ tools: [...this.tools.values()].map((t) => ({
102
+ name: t.name,
103
+ description: t.description,
104
+ inputSchema: t.inputSchema,
105
+ annotations: t.annotations,
106
+ })),
107
+ };
108
+ case 'tools/call':
109
+ return this.callTool(params);
110
+ default:
111
+ throw rpcError(JSONRPC_METHOD_NOT_FOUND, `Method not found: ${method}`);
112
+ }
113
+ }
114
+
115
+ async callTool(params) {
116
+ const tool = this.tools.get(params.name);
117
+ if (!tool) throw rpcError(JSONRPC_INVALID_PARAMS, `未知工具:${params.name}`);
118
+ const args = params.arguments ?? {};
119
+ const started = Date.now();
120
+ try {
121
+ validateArgs(tool.inputSchema, args);
122
+ const result = await tool.handler(args, this.context);
123
+ this.log(`tool ${tool.name} 完成,用时 ${Date.now() - started}ms`);
124
+ return { content: [{ type: 'text', text: JSON.stringify(stripUndefined(result), null, 2) }] };
125
+ } catch (e) {
126
+ // 工具执行错误以 isError 返回给模型,便于其自行修正参数重试
127
+ this.log(`tool ${tool.name} 失败(${Date.now() - started}ms):${e.message}`);
128
+ return { content: [{ type: 'text', text: `错误:${e.message}` }], isError: true };
129
+ }
130
+ }
131
+ }
132
+
133
+ function rpcError(code, message) {
134
+ const e = new Error(message);
135
+ e.rpcCode = code;
136
+ return e;
137
+ }
138
+
139
+ function errorResponse(id, code, message) {
140
+ return { jsonrpc: '2.0', id, error: { code, message } };
141
+ }
142
+
143
+ function stripUndefined(value) {
144
+ return JSON.parse(JSON.stringify(value ?? null));
145
+ }
@@ -0,0 +1,5 @@
1
+ import { readFileSync } from 'node:fs';
2
+
3
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
4
+
5
+ export const PACKAGE = Object.freeze({ name: pkg.name, version: pkg.version });
package/src/serve.js ADDED
@@ -0,0 +1,55 @@
1
+ import { describeConfig, loadConfig } from './lib/config.js';
2
+ import { BugzillaRpcClient } from './lib/rpc-client.js';
3
+ import { McpServer } from './mcp/server.js';
4
+ import { PACKAGE } from './package-info.js';
5
+ import { TOOLS } from './tools/index.js';
6
+
7
+ // stdout 专用于 MCP 协议消息,日志一律写 stderr
8
+ export const log = (msg) => process.stderr.write(`[${PACKAGE.name}] ${new Date().toISOString()} ${msg}\n`);
9
+
10
+ const INSTRUCTIONS =
11
+ '这是 Bugzilla 4.x 的 MCP(JSON-RPC / XML-RPC)。版本质量统计推荐流程:list_products 确认版本号写法 → ' +
12
+ 'get_field_values(priority) 确认优先级取值与权重表一致(各站点取值可能不是 P0~P3)→ list_version_bugs 查看版本 Bug 分布 → ' +
13
+ 'get_version_bug_weight 计算版本 Bug 权重数。修改类工具(add_comment / update_bug / create_bug)建议先 dry_run。';
14
+
15
+ export async function serve(env) {
16
+ let config;
17
+ let client;
18
+ let configError;
19
+ try {
20
+ config = loadConfig(env);
21
+ client = new BugzillaRpcClient(config);
22
+ log(`v${PACKAGE.version} 配置加载完成:${JSON.stringify(describeConfig(config))}`);
23
+ } catch (e) {
24
+ configError = e.message;
25
+ log(`配置错误:${configError}`);
26
+ }
27
+
28
+ const tools = configError
29
+ ? TOOLS.map((t) => ({
30
+ ...t,
31
+ handler: async () => {
32
+ throw new Error(`${PACKAGE.name} 配置错误:${configError}。运行 npx -y ${PACKAGE.name}@latest --help 查看配置方式`);
33
+ },
34
+ }))
35
+ : TOOLS;
36
+
37
+ const server = new McpServer({
38
+ info: { name: PACKAGE.name, version: PACKAGE.version },
39
+ tools,
40
+ context: { client, config, log },
41
+ log,
42
+ instructions: INSTRUCTIONS,
43
+ });
44
+
45
+ if (client && config.authType !== 'none') {
46
+ client
47
+ .whoami()
48
+ .then((me) => log(`登录校验通过:${me?.name || me?.id}`))
49
+ .catch((e) => log(`登录校验失败:${e.message}`));
50
+ }
51
+
52
+ process.on('unhandledRejection', (e) => log(`未处理的异常:${e?.stack || e}`));
53
+ await server.listen();
54
+ log('stdin 已关闭,退出');
55
+ }