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.
@@ -0,0 +1,250 @@
1
+ import { assertBugId, buildSearch, hasServerFilter, parseDate } from '../lib/search.js';
2
+ import { FILTER_PROPERTIES, bugUrl, groupCount, listFields, requireProduct, searchAll, summarizeBug } from './common.js';
3
+
4
+ const IDS_PROP = {
5
+ type: 'array',
6
+ items: { type: ['string', 'integer'] },
7
+ minItems: 1,
8
+ maxItems: 500,
9
+ description: 'Bug ID 或别名列表',
10
+ };
11
+
12
+ export const getBugStatus = {
13
+ name: 'get_bug_status',
14
+ description: '快速批量查询 Bug 状态:状态、解决结果、优先级、严重程度、处理人、最后修改时间。不存在或无权查看的 ID 会列在 not_found 中。',
15
+ inputSchema: { type: 'object', properties: { ids: IDS_PROP }, required: ['ids'], additionalProperties: false },
16
+ async handler(args, { client, config }) {
17
+ const ids = args.ids.map(assertBugId);
18
+ const fields = ['id', 'alias', 'summary', 'status', 'resolution', 'is_open', 'priority', 'severity', 'assigned_to', 'last_change_time', 'dupe_of', 'product', 'version', 'target_milestone'];
19
+ const data = await client.getBugs(ids, fields);
20
+ const bugs = (data?.bugs || []).map((b) => ({
21
+ id: b.id,
22
+ summary: b.summary,
23
+ status: b.status,
24
+ resolution: b.resolution || undefined,
25
+ is_open: b.is_open,
26
+ dupe_of: b.dupe_of || undefined,
27
+ priority: b.priority,
28
+ severity: b.severity,
29
+ assigned_to: b.assigned_to,
30
+ last_change_time: b.last_change_time,
31
+ url: bugUrl(config, b.id),
32
+ }));
33
+ const found = new Set((data?.bugs || []).flatMap((b) => [String(b.id), b.alias && String(b.alias)].filter(Boolean)));
34
+ return {
35
+ count: bugs.length,
36
+ open: bugs.filter((b) => b.is_open).length,
37
+ closed: bugs.filter((b) => b.is_open === false).length,
38
+ by_status: groupCount(bugs, 'status'),
39
+ not_found: ids.filter((id) => !found.has(id)),
40
+ faults: data?.faults?.length ? data.faults : undefined,
41
+ bugs,
42
+ };
43
+ },
44
+ };
45
+
46
+ export const getBug = {
47
+ name: 'get_bug',
48
+ description: '获取一个或多个 Bug 的完整信息(含自定义字段 cf_*、依赖、CC、关键字),可附带描述(第一条评论)。',
49
+ inputSchema: {
50
+ type: 'object',
51
+ properties: {
52
+ ids: IDS_PROP,
53
+ include_fields: { type: 'array', items: { type: 'string' }, description: '只返回这些字段;默认全部' },
54
+ include_description: { type: 'boolean', default: false },
55
+ },
56
+ required: ['ids'],
57
+ additionalProperties: false,
58
+ },
59
+ async handler(args, { client, config }) {
60
+ const ids = args.ids.map(assertBugId);
61
+ const includeFields = args.include_fields?.length ? [...new Set(['id', ...args.include_fields])] : undefined;
62
+ const data = await client.getBugs(ids, includeFields);
63
+ const bugs = (data?.bugs || []).map((b) => ({ ...b, url: bugUrl(config, b.id) }));
64
+ if (args.include_description && bugs.length) {
65
+ const c = await client.comments(bugs.map((b) => b.id)).catch(() => null);
66
+ for (const bug of bugs) bug.description = c?.bugs?.[bug.id]?.comments?.[0]?.text;
67
+ }
68
+ return { count: bugs.length, bugs, faults: data?.faults?.length ? data.faults : undefined };
69
+ },
70
+ };
71
+
72
+ export const searchBugs = {
73
+ name: 'search_bugs',
74
+ description:
75
+ '按产品、组件、版本、里程碑、状态、解决结果、优先级、严重程度、处理人、报告人、标题 / 白板子串、创建 / 修改时间等条件搜索 Bug(Bugzilla 4.0 Bug.search)。' +
76
+ '4.0 不支持的条件(时间上限、未解决 / 已解决、排除解决结果、关键字、自定义字段)会在本地对结果过滤。',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: {
80
+ ...FILTER_PROPERTIES,
81
+ limit: { type: 'integer', minimum: 1, maximum: 1000, default: 100, description: '单页条数(fetch_all=false 时生效)' },
82
+ offset: { type: 'integer', minimum: 0, default: 0 },
83
+ fetch_all: { type: 'boolean', default: false, description: '自动翻页拉取全部(受 BUGZILLA_MAX_RESULTS 限制);有本地过滤条件时建议开启' },
84
+ include_fields: { type: 'array', items: { type: 'string' }, description: '额外返回的字段,如 ["cf_root_cause"]' },
85
+ },
86
+ additionalProperties: false,
87
+ },
88
+ async handler(args, { client, config }) {
89
+ const search = buildSearch(args, { versionField: config.versionField });
90
+ if (!hasServerFilter(search.server)) throw new Error('至少需要一个服务端可用的条件(如 product / status / version / created_after),避免全库扫描');
91
+ const extra = args.include_fields || [];
92
+ const includeFields = listFields(config, extra);
93
+
94
+ if (args.fetch_all) {
95
+ const r = await searchAll(client, search, { includeFields, max: config.maxResults, pageSize: config.pageSize });
96
+ return {
97
+ count: r.bugs.length,
98
+ truncated: r.truncated,
99
+ by_status: groupCount(r.bugs, 'status'),
100
+ warnings: r.warnings.length ? r.warnings : undefined,
101
+ bugs: r.bugs.map((b) => summarizeBug(b, config, extra)),
102
+ };
103
+ }
104
+ const limit = args.limit ?? 100;
105
+ const offset = args.offset ?? 0;
106
+ const fields = [...new Set([...includeFields, ...search.filterFields])];
107
+ const data = await client.searchBugs({ ...search.server, include_fields: fields, limit, offset });
108
+ const page = data?.bugs || [];
109
+ const bugs = page.filter(search.filter);
110
+ return {
111
+ count: bugs.length,
112
+ offset,
113
+ next_offset: page.length === limit ? offset + limit : undefined,
114
+ warnings: search.localConditions.length
115
+ ? [`本页服务端返回 ${page.length} 条,本地过滤(${search.localConditions.join(';')})后剩 ${bugs.length} 条;需要完整结果请用 fetch_all=true`]
116
+ : undefined,
117
+ bugs: bugs.map((b) => summarizeBug(b, config, extra)),
118
+ };
119
+ },
120
+ };
121
+
122
+ export const listVersionBugs = {
123
+ name: 'list_version_bugs',
124
+ description:
125
+ '查询某产品某(些)版本下的 Bug 列表,并按状态 / 优先级 / 严重程度 / 组件分组统计。' +
126
+ '"版本"默认对应 version 字段,可通过 version_field 或 BUGZILLA_VERSION_FIELD 改为 target_milestone 或自定义字段(自定义字段在本地过滤)。',
127
+ inputSchema: {
128
+ type: 'object',
129
+ properties: {
130
+ ...FILTER_PROPERTIES,
131
+ versions: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 100, description: '版本号列表,如 ["2.3.0"]' },
132
+ version_field: { type: 'string', description: '版本对应的字段,默认取 BUGZILLA_VERSION_FIELD(version)' },
133
+ group_by: { type: 'array', items: { type: 'string' }, default: ['status', 'priority', 'severity', 'component'] },
134
+ include_bugs: { type: 'boolean', default: true },
135
+ max_listed: { type: 'integer', minimum: 0, maximum: 5000, default: 500, description: '明细最多返回条数(统计不受影响)' },
136
+ },
137
+ required: ['versions'],
138
+ additionalProperties: false,
139
+ },
140
+ async handler(args, { client, config }) {
141
+ const product = requireProduct(args, config);
142
+ const versionField = args.version_field || config.versionField;
143
+ const search = buildSearch({ ...args, product }, { versionField });
144
+ const includeFields = listFields({ ...config, versionField });
145
+ const r = await searchAll(client, search, { includeFields, max: config.maxResults, pageSize: config.pageSize });
146
+
147
+ const groupBy = args.group_by?.length ? args.group_by : ['status', 'priority', 'severity', 'component'];
148
+ const stats = {};
149
+ for (const f of groupBy) stats[f] = groupCount(r.bugs, f);
150
+ if (args.versions.length > 1) stats[versionField] = groupCount(r.bugs, versionField);
151
+ const maxListed = args.max_listed ?? 500;
152
+ return {
153
+ product,
154
+ versions: args.versions,
155
+ version_field: versionField,
156
+ total: r.bugs.length,
157
+ open: r.bugs.filter((b) => b.is_open).length,
158
+ closed: r.bugs.filter((b) => b.is_open === false).length,
159
+ truncated: r.truncated,
160
+ stats,
161
+ warnings: r.warnings.length ? r.warnings : undefined,
162
+ listed: args.include_bugs === false ? 0 : Math.min(r.bugs.length, maxListed),
163
+ bugs: args.include_bugs === false ? undefined : r.bugs.slice(0, maxListed).map((b) => summarizeBug(b, config, [versionField])),
164
+ };
165
+ },
166
+ };
167
+
168
+ export const getBugHistory = {
169
+ name: 'get_bug_history',
170
+ description: '获取 Bug 的变更历史(谁在何时把哪个字段从什么改成什么),并统计 Reopen 次数。',
171
+ inputSchema: {
172
+ type: 'object',
173
+ properties: {
174
+ id: { type: ['string', 'integer'] },
175
+ since: { type: 'string', description: '只返回该时间之后的变更(本地过滤)' },
176
+ },
177
+ required: ['id'],
178
+ additionalProperties: false,
179
+ },
180
+ async handler(args, { client }) {
181
+ const id = assertBugId(args.id);
182
+ const data = await client.history([id]);
183
+ const bug = data?.bugs?.[0] || { history: [] };
184
+ let history = bug.history || [];
185
+ if (args.since) {
186
+ const t = parseDate(args.since, 'since').getTime();
187
+ history = history.filter((h) => Date.parse(h.when) >= t);
188
+ }
189
+ let reopenCount = 0;
190
+ for (const h of history) for (const c of h.changes || []) if (c.field_name === 'bug_status' || c.field_name === 'status') if (/REOPENED/i.test(c.added)) reopenCount += 1;
191
+ return { id: bug.id ?? id, change_sets: history.length, reopen_count: reopenCount, history };
192
+ },
193
+ };
194
+
195
+ export const getBugComments = {
196
+ name: 'get_bug_comments',
197
+ description: '获取 Bug 的评论(第一条为 Bug 描述)。',
198
+ inputSchema: {
199
+ type: 'object',
200
+ properties: {
201
+ id: { type: ['string', 'integer'] },
202
+ since: { type: 'string', description: '只返回该时间之后的评论' },
203
+ max: { type: 'integer', minimum: 1, maximum: 2000, default: 200, description: '最多返回条数(取最新的)' },
204
+ },
205
+ required: ['id'],
206
+ additionalProperties: false,
207
+ },
208
+ async handler(args, { client }) {
209
+ const id = assertBugId(args.id);
210
+ const data = await client.comments([id], args.since ? parseDate(args.since, 'since') : undefined);
211
+ const entry = data?.bugs ? Object.values(data.bugs)[0] : null;
212
+ const all = entry?.comments || [];
213
+ const max = args.max ?? 200;
214
+ const comments = all.slice(-max).map((c) => ({
215
+ id: c.id,
216
+ author: c.author || c.creator,
217
+ time: c.time || c.creation_time,
218
+ is_private: c.is_private || undefined,
219
+ text: c.text,
220
+ }));
221
+ return { id, total: all.length, returned: comments.length, comments };
222
+ },
223
+ };
224
+
225
+ export const listAttachments = {
226
+ name: 'list_attachments',
227
+ description: '列出 Bug 的附件元数据(文件名、类型、上传者、是否补丁 / 过期),不下载附件内容。',
228
+ inputSchema: { type: 'object', properties: { id: { type: ['string', 'integer'] } }, required: ['id'], additionalProperties: false },
229
+ async handler(args, { client, config }) {
230
+ const id = assertBugId(args.id);
231
+ const data = await client.attachments([id]);
232
+ const list = data?.bugs ? Object.values(data.bugs)[0] || [] : [];
233
+ return {
234
+ id,
235
+ count: list.length,
236
+ attachments: list.map((a) => ({
237
+ id: a.id,
238
+ file_name: a.file_name,
239
+ summary: a.summary || a.description,
240
+ content_type: a.content_type,
241
+ size: a.size,
242
+ creator: a.creator || a.attacher,
243
+ creation_time: a.creation_time,
244
+ is_patch: Boolean(a.is_patch),
245
+ is_obsolete: Boolean(a.is_obsolete),
246
+ url: `${config.baseUrl}/attachment.cgi?id=${a.id}`,
247
+ })),
248
+ };
249
+ },
250
+ };
@@ -0,0 +1,147 @@
1
+ import { DEFAULT_LIST_FIELDS } from '../lib/search.js';
2
+
3
+ const STR_OR_LIST = { type: ['string', 'array'], items: { type: 'string' } };
4
+
5
+ /** 搜索类工具共享的过滤条件(Bug.search 不支持的条件会在本地过滤) */
6
+ export const FILTER_PROPERTIES = {
7
+ product: { ...STR_OR_LIST, description: '产品名,可传数组' },
8
+ component: { ...STR_OR_LIST, description: '组件名,可传数组' },
9
+ version: { ...STR_OR_LIST, description: '版本(version 字段),可传数组' },
10
+ target_milestone: { ...STR_OR_LIST, description: '目标里程碑,可传数组' },
11
+ status: { ...STR_OR_LIST, description: '状态,如 NEW / ASSIGNED / REOPENED / RESOLVED / VERIFIED / CLOSED' },
12
+ resolution: { ...STR_OR_LIST, description: '解决结果,如 FIXED / INVALID / DUPLICATE' },
13
+ priority: { ...STR_OR_LIST, description: '优先级,如 P1 / P2' },
14
+ severity: { ...STR_OR_LIST, description: '严重程度,如 blocker / critical / major' },
15
+ assigned_to: { ...STR_OR_LIST, description: '处理人登录名(邮箱)' },
16
+ creator: { ...STR_OR_LIST, description: '报告人登录名(邮箱)' },
17
+ qa_contact: { ...STR_OR_LIST, description: 'QA 负责人' },
18
+ op_sys: { ...STR_OR_LIST, description: '操作系统' },
19
+ platform: { ...STR_OR_LIST, description: '硬件平台' },
20
+ alias: { ...STR_OR_LIST, description: 'Bug 别名' },
21
+ summary: { type: 'string', description: '标题包含的文本(子串)' },
22
+ whiteboard: { type: 'string', description: '白板包含的文本(子串)' },
23
+ url: { type: 'string', description: 'URL 字段包含的文本(子串)' },
24
+ keywords: { ...STR_OR_LIST, description: '关键字(任一匹配,本地过滤)' },
25
+ status_scope: { type: 'string', enum: ['all', 'open', 'closed'], description: 'open=未解决,closed=已解决 / 已关闭(本地按 is_open 过滤)' },
26
+ exclude_resolutions: { type: 'array', items: { type: 'string' }, description: '排除的解决结果(本地过滤)' },
27
+ created_after: { type: 'string', description: '创建时间下限(YYYY-MM-DD 或 ISO 8601,默认 UTC)' },
28
+ created_before: { type: 'string', description: '创建时间上限(本地过滤)' },
29
+ changed_after: { type: 'string', description: '最后修改时间下限' },
30
+ changed_before: { type: 'string', description: '最后修改时间上限(本地过滤)' },
31
+ custom_fields: {
32
+ type: 'object',
33
+ additionalProperties: { ...STR_OR_LIST },
34
+ description: '自定义字段精确匹配(本地过滤),如 {"cf_found_in": ["1.2.0"]}',
35
+ },
36
+ };
37
+
38
+ export function bugUrl(config, id) {
39
+ return `${config.baseUrl}/show_bug.cgi?id=${id}`;
40
+ }
41
+
42
+ export function summarizeBug(bug, config, extraFields = []) {
43
+ const out = {
44
+ id: bug.id,
45
+ summary: bug.summary,
46
+ status: bug.status,
47
+ resolution: bug.resolution || undefined,
48
+ is_open: bug.is_open,
49
+ priority: bug.priority,
50
+ severity: bug.severity,
51
+ product: bug.product,
52
+ component: bug.component,
53
+ version: bug.version,
54
+ target_milestone: bug.target_milestone,
55
+ assigned_to: bug.assigned_to,
56
+ creator: bug.creator,
57
+ creation_time: bug.creation_time,
58
+ last_change_time: bug.last_change_time,
59
+ keywords: bug.keywords?.length ? bug.keywords : undefined,
60
+ whiteboard: bug.whiteboard || undefined,
61
+ url: bugUrl(config, bug.id),
62
+ };
63
+ for (const f of extraFields) if (bug[f] !== undefined && out[f] === undefined) out[f] = bug[f];
64
+ return out;
65
+ }
66
+
67
+ export function listFields(config, extra = []) {
68
+ return [...new Set([...DEFAULT_LIST_FIELDS, config.weightField, config.versionField, ...extra])];
69
+ }
70
+
71
+ /**
72
+ * 分页拉取 Bug.search 结果并做本地过滤。
73
+ * 4.0 的 Bug.search 支持 limit / offset,但不保证排序稳定,因此按 ID 去重;
74
+ * 若服务端忽略 offset(同一页反复返回),自动停止并给出提示。
75
+ * @returns {Promise<{ bugs: object[], fetched: number, truncated: boolean, warnings: string[] }>}
76
+ */
77
+ export async function searchAll(client, search, { includeFields, max, pageSize }) {
78
+ const seen = new Map();
79
+ const warnings = [];
80
+ let truncated = false;
81
+ const fields = [...new Set([...includeFields, ...search.filterFields])];
82
+
83
+ if (!pageSize) {
84
+ const data = await client.searchBugs({ ...search.server, include_fields: fields });
85
+ for (const b of data?.bugs || []) seen.set(b.id, b);
86
+ if (seen.size > max) {
87
+ truncated = true;
88
+ warnings.push(`返回 ${seen.size} 条,超过 BUGZILLA_MAX_RESULTS=${max},只保留前 ${max} 条`);
89
+ }
90
+ } else {
91
+ let offset = 0;
92
+ for (;;) {
93
+ const limit = Math.min(pageSize, max - seen.size);
94
+ const data = await client.searchBugs({ ...search.server, include_fields: fields, limit, offset });
95
+ const page = data?.bugs || [];
96
+ let added = 0;
97
+ for (const b of page) {
98
+ if (!seen.has(b.id)) {
99
+ seen.set(b.id, b);
100
+ added += 1;
101
+ }
102
+ }
103
+ if (page.length > limit) break; // 服务端忽略了 limit,已一次返回全部
104
+ if (page.length < limit) break;
105
+ if (added === 0) {
106
+ warnings.push('服务端似乎不支持 offset 分页,已停止翻页;可设置 BUGZILLA_PAGE_SIZE=0 一次性拉取');
107
+ truncated = true;
108
+ break;
109
+ }
110
+ offset += page.length;
111
+ if (seen.size >= max) {
112
+ const probe = await client.searchBugs({ ...search.server, include_fields: ['id'], limit: 1, offset });
113
+ truncated = Boolean(probe?.bugs?.some((b) => !seen.has(b.id)));
114
+ if (truncated) warnings.push(`结果超过 BUGZILLA_MAX_RESULTS=${max},统计不完整,请缩小范围或调大该值`);
115
+ break;
116
+ }
117
+ }
118
+ }
119
+
120
+ const all = [...seen.values()].slice(0, max);
121
+ const bugs = all.filter(search.filter);
122
+ if (search.localConditions.length) {
123
+ warnings.push(`以下条件 Bugzilla 4.0 不支持服务端查询,已在本地过滤:${search.localConditions.join(';')}(服务端返回 ${all.length} 条,过滤后 ${bugs.length} 条)`);
124
+ }
125
+ return { bugs, fetched: all.length, truncated, warnings };
126
+ }
127
+
128
+ export function groupCount(bugs, field) {
129
+ const out = {};
130
+ for (const b of bugs) {
131
+ const v = b[field];
132
+ const key = v === undefined || v === null || v === '' ? '(空)' : Array.isArray(v) ? v.join(',') : String(v);
133
+ out[key] = (out[key] || 0) + 1;
134
+ }
135
+ return Object.fromEntries(Object.entries(out).sort((a, b) => b[1] - a[1]));
136
+ }
137
+
138
+ export function assertWritable(config) {
139
+ if (config.readOnly) throw new Error('当前为只读模式(BUGZILLA_READ_ONLY=true),禁止修改 Bugzilla。可使用 dry_run=true 预览');
140
+ if (config.authType === 'none') throw new Error('匿名模式无法修改 Bugzilla,请配置 BUGZILLA_LOGIN / BUGZILLA_PASSWORD');
141
+ }
142
+
143
+ export function requireProduct(args, config) {
144
+ const product = args.product ?? config.defaultProduct;
145
+ if (!product) throw new Error('需要指定 product(或配置 BUGZILLA_DEFAULT_PRODUCT)');
146
+ return product;
147
+ }
@@ -0,0 +1,30 @@
1
+ import { getBug, getBugComments, getBugHistory, getBugStatus, listAttachments, listVersionBugs, searchBugs } from './bugs.js';
2
+ import { getFieldValues, listProducts, searchUsers, verifyAuth } from './meta.js';
3
+ import { getVersionBugWeight } from './weight.js';
4
+ import { addComment, createBug, updateBug } from './write.js';
5
+
6
+ const WRITE_TOOLS = new Set(['add_comment', 'update_bug', 'create_bug']);
7
+
8
+ export const TOOLS = [
9
+ getBugStatus,
10
+ getBug,
11
+ searchBugs,
12
+ listVersionBugs,
13
+ getVersionBugWeight,
14
+ getBugHistory,
15
+ getBugComments,
16
+ listAttachments,
17
+ listProducts,
18
+ getFieldValues,
19
+ searchUsers,
20
+ verifyAuth,
21
+ addComment,
22
+ updateBug,
23
+ createBug,
24
+ ];
25
+
26
+ for (const tool of TOOLS) {
27
+ tool.annotations = WRITE_TOOLS.has(tool.name)
28
+ ? { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true }
29
+ : { readOnlyHint: true, openWorldHint: true };
30
+ }
@@ -0,0 +1,119 @@
1
+ import { assertFieldName } from '../lib/search.js';
2
+ import { mapLimit } from '../lib/util.js';
3
+
4
+ /** 常用字段的别名:用户习惯写 severity / status,Bug.fields 里叫 bug_severity / bug_status */
5
+ const FIELD_ALIASES = { severity: 'bug_severity', status: 'bug_status', platform: 'rep_platform' };
6
+
7
+ export const verifyAuth = {
8
+ name: 'verify_auth',
9
+ description: '校验 Bugzilla 4.0 连接与登录是否正常,返回服务器版本、当前账号、协议、只读模式以及生效的权重配置。连接异常时优先调用。',
10
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
11
+ async handler(_args, { client, config }) {
12
+ const version = await client.version().then((r) => r?.version).catch((e) => `获取失败:${e.message}`);
13
+ const base = {
14
+ endpoint: client.endpoint,
15
+ protocol_setting: config.protocol,
16
+ protocol_in_use: client.protocol,
17
+ protocol_fallback_reason: client.fallbackReason,
18
+ auth_type: config.authType,
19
+ server_version: version,
20
+ read_only: config.readOnly,
21
+ weight_config: {
22
+ weights: config.weights,
23
+ weight_field: config.weightField,
24
+ default_weight: config.defaultWeight,
25
+ version_field: config.versionField,
26
+ exclude_resolutions: config.excludeResolutions,
27
+ },
28
+ };
29
+ if (config.authType === 'none') return { authenticated: false, ...base, note: '匿名模式只能读公开 Bug,无法修改' };
30
+ const me = await client.whoami();
31
+ return { authenticated: true, account: { id: me?.id, name: me?.name, real_name: me?.real_name }, ...base };
32
+ },
33
+ };
34
+
35
+ export const listProducts = {
36
+ name: 'list_products',
37
+ description: '列出可访问的产品及其版本(versions)、里程碑(milestones)和组件(components),用于确认查询时的版本号写法。',
38
+ inputSchema: {
39
+ type: 'object',
40
+ properties: {
41
+ names: { type: 'array', items: { type: 'string' }, maxItems: 100, description: '只查这些产品;不传则列出全部可访问产品' },
42
+ detail: { type: 'boolean', default: true, description: 'false 时只返回产品名' },
43
+ },
44
+ additionalProperties: false,
45
+ },
46
+ async handler(args, { client, config }) {
47
+ const { ids = [] } = (await client.accessibleProducts()) || {};
48
+ if (!ids.length) return { count: 0, products: [] };
49
+ const data = await client.getProducts(ids);
50
+ let products = data?.products || [];
51
+ if (args.names?.length) {
52
+ const set = new Set(args.names.map((n) => n.toLowerCase()));
53
+ products = products.filter((p) => set.has(String(p.name).toLowerCase()));
54
+ }
55
+ if (args.detail === false) return { count: products.length, products: products.map((p) => ({ id: p.id, name: p.name })) };
56
+
57
+ // 4.0 的 Product.get 不返回 versions / components / milestones(4.2 起才有),用 Bug.legal_values 补齐
58
+ const names = (list) => (list || []).filter((x) => x.is_active !== false).map((x) => (typeof x === 'string' ? x : x.name));
59
+ const out = await mapLimit(products, config.concurrency, async (p) => {
60
+ const legal = async (field) => (await client.legalValues(field, p.id).catch(() => null))?.values;
61
+ return {
62
+ id: p.id,
63
+ name: p.name,
64
+ description: p.description,
65
+ versions: p.versions ? names(p.versions) : await legal('version'),
66
+ milestones: p.milestones ? names(p.milestones) : await legal('target_milestone'),
67
+ components: p.components ? names(p.components) : await legal('component'),
68
+ };
69
+ });
70
+ return { count: out.length, products: out };
71
+ },
72
+ };
73
+
74
+ export const getFieldValues = {
75
+ name: 'get_field_values',
76
+ description: '获取字段的合法取值,如 priority / severity / status / resolution / op_sys / platform 或自定义下拉字段,用于确认权重表的键名和搜索取值。',
77
+ inputSchema: {
78
+ type: 'object',
79
+ properties: { field: { type: 'string', description: '字段名,如 priority、severity、status、resolution、cf_xxx' } },
80
+ required: ['field'],
81
+ additionalProperties: false,
82
+ },
83
+ async handler(args, { client }) {
84
+ const input = assertFieldName(args.field, 'field');
85
+ const name = FIELD_ALIASES[input] || input;
86
+ try {
87
+ const data = await client.fields([name]);
88
+ const field = data?.fields?.[0];
89
+ if (field) {
90
+ return {
91
+ name: field.name,
92
+ display_name: field.display_name,
93
+ type: field.type,
94
+ is_custom: field.is_custom,
95
+ values: (field.values || []).map((v) => ({ name: v.name, sort_key: v.sort_key, is_open: v.is_open, can_change_to: v.can_change_to?.map((t) => t.name) })),
96
+ };
97
+ }
98
+ } catch {
99
+ // Bug.fields 不可用时回退到 Bug.legal_values
100
+ }
101
+ const legal = await client.legalValues(input);
102
+ return { name: input, source: 'Bug.legal_values', values: (legal?.values || []).map((v) => ({ name: v })) };
103
+ },
104
+ };
105
+
106
+ export const searchUsers = {
107
+ name: 'search_users',
108
+ description: '按登录名 / 邮箱 / 姓名模糊匹配用户(User.get match),用于确认 assigned_to 等字段的取值。',
109
+ inputSchema: {
110
+ type: 'object',
111
+ properties: { match: { type: 'string', minLength: 2 } },
112
+ required: ['match'],
113
+ additionalProperties: false,
114
+ },
115
+ async handler(args, { client }) {
116
+ const data = await client.getUsers({ match: [args.match] });
117
+ return { users: (data?.users || []).map((u) => ({ id: u.id, name: u.name, real_name: u.real_name, can_login: u.can_login })) };
118
+ },
119
+ };
@@ -0,0 +1,72 @@
1
+ import { assertFieldName, buildSearch } from '../lib/search.js';
2
+ import { round } from '../lib/util.js';
3
+ import { computeWeight, parseWeights } from '../lib/weights.js';
4
+ import { FILTER_PROPERTIES, listFields, requireProduct, searchAll } from './common.js';
5
+
6
+ export const getVersionBugWeight = {
7
+ name: 'get_version_bug_weight',
8
+ description:
9
+ '快速计算某产品某(些)版本下的 Bug 权重数:Σ(各 Bug 优先级对应的权重)。默认权重 P0=5、P1=3、P2=1、P3=0.2,' +
10
+ '可通过 weights 参数临时覆盖,或用 BUGZILLA_PRIORITY_WEIGHTS 全局设置;也可改为按 severity 等字段计权。' +
11
+ '默认统计全部状态并排除 INVALID / DUPLICATE / WORKSFORME。传入 kloc 时同时给出千行权重 Bug 率。',
12
+ inputSchema: {
13
+ type: 'object',
14
+ properties: {
15
+ ...FILTER_PROPERTIES,
16
+ versions: { type: 'array', items: { type: 'string' }, minItems: 1, maxItems: 100, description: '版本号列表' },
17
+ version_field: { type: 'string', description: '版本对应的字段,默认取 BUGZILLA_VERSION_FIELD(version)' },
18
+ weights: {
19
+ type: ['object', 'string'],
20
+ additionalProperties: { type: 'number', minimum: 0 },
21
+ description: '本次使用的权重表,如 {"P0":5,"P1":3,"P2":1,"P3":0.2} 或 "P0=5,P1=3";不传则用配置值',
22
+ },
23
+ weight_field: { type: 'string', description: '按哪个字段计权,默认 priority;可设为 severity 或自定义字段' },
24
+ default_weight: { type: 'number', minimum: 0, description: '权重表中不存在的取值使用的权重,默认 0' },
25
+ group_by: { type: 'string', description: '额外按该字段分组汇总权重,如 component / assigned_to / version' },
26
+ kloc: { type: 'number', minimum: 0, description: '版本 KLOC(可取自 Gerrit MCP 的 get_version_kloc)' },
27
+ include_bug_ids: { type: 'boolean', default: true },
28
+ },
29
+ required: ['versions'],
30
+ additionalProperties: false,
31
+ },
32
+ async handler(args, { client, config }) {
33
+ const product = requireProduct(args, config);
34
+ const versionField = args.version_field ? assertFieldName(args.version_field, 'version_field') : config.versionField;
35
+ const weightField = args.weight_field ? assertFieldName(args.weight_field, 'weight_field') : config.weightField;
36
+ const weights = args.weights ? parseWeights(args.weights, 'weights') : config.weights;
37
+ const defaultWeight = args.default_weight ?? config.defaultWeight;
38
+ const excludeResolutions = args.exclude_resolutions ?? config.excludeResolutions;
39
+ const groupBy = args.group_by ? assertFieldName(args.group_by, 'group_by') : undefined;
40
+
41
+ const search = buildSearch({ ...args, product, exclude_resolutions: excludeResolutions }, { versionField });
42
+ const includeFields = listFields({ ...config, versionField, weightField }, groupBy ? [groupBy] : []);
43
+ const r = await searchAll(client, search, { includeFields, max: config.maxResults, pageSize: config.pageSize });
44
+
45
+ const result = computeWeight(r.bugs, { weights, field: weightField, defaultWeight, groupBy });
46
+ if (args.include_bug_ids === false) {
47
+ for (const slot of Object.values(result.by_level)) delete slot.bug_ids;
48
+ for (const slot of Object.values(result.unmatched || {})) delete slot.bug_ids;
49
+ }
50
+ const warnings = [...r.warnings];
51
+ if (result.unmatched) {
52
+ warnings.push(`存在权重表未覆盖的 ${weightField} 取值:${Object.keys(result.unmatched).join(', ')},已按 default_weight=${defaultWeight} 计入。可用 get_field_values 查看实际取值`);
53
+ }
54
+
55
+ return {
56
+ product,
57
+ versions: args.versions,
58
+ version_field: versionField,
59
+ weight_field: weightField,
60
+ weights,
61
+ default_weight: defaultWeight,
62
+ status_scope: args.status_scope || 'all',
63
+ excluded_resolutions: excludeResolutions,
64
+ formula: `权重数 = Σ 每个 Bug 的 ${weightField} 权重`,
65
+ ...result,
66
+ weight_per_kloc: args.kloc ? round(result.total_weight / args.kloc, 4) : undefined,
67
+ bugs_per_kloc: args.kloc ? round(result.bug_count / args.kloc, 4) : undefined,
68
+ truncated: r.truncated,
69
+ warnings: warnings.length ? warnings : undefined,
70
+ };
71
+ },
72
+ };