@zereight/mcp-gitlab 2.1.63 → 2.1.65

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.
Files changed (34) hide show
  1. package/README.ko.md +20 -5
  2. package/README.md +19 -6
  3. package/README.zh-CN.md +19 -6
  4. package/build/downloads/proxy.js +14 -7
  5. package/build/index.js +413 -455
  6. package/build/schemas.js +2 -2
  7. package/build/scripts/generate-tool-coverage.js +58 -0
  8. package/build/scripts/generate-tool-docs.js +6 -1
  9. package/build/scripts/tool-coverage/coverage.js +339 -0
  10. package/build/scripts/tool-coverage/coverage.test.js +142 -0
  11. package/build/test/path-segment-encoding.test.js +73 -17
  12. package/build/test/sse-session-limits.test.js +273 -0
  13. package/build/test/test-blank-filters.js +156 -0
  14. package/build/test/test-download-attachment.js +11 -0
  15. package/build/test/test-empty-toolsets.js +535 -0
  16. package/build/test/test-geteffectiveprojectid.js +1 -1
  17. package/build/test/test-job-artifacts.js +22 -0
  18. package/build/test/test-list-issues.js +47 -0
  19. package/build/test/test-list-merge-requests.js +76 -0
  20. package/build/test/test-list-milestones.js +145 -0
  21. package/build/test/test-permission-mode.js +103 -12
  22. package/build/test/test-remote-downloads.js +14 -1
  23. package/build/test/utils/graphql-query.test.js +72 -0
  24. package/build/test/utils/safe-redirect-fetch.test.js +463 -0
  25. package/build/test/utils/tool-args.test.js +89 -1
  26. package/build/test/utils/url.test.js +128 -0
  27. package/build/test-note.js +2 -1
  28. package/build/test-resolve-issue-note.js +4 -3
  29. package/build/tools/registry.js +16 -2
  30. package/build/utils/graphql-query.js +31 -9
  31. package/build/utils/safe-redirect-fetch.js +321 -0
  32. package/build/utils/tool-args.js +47 -3
  33. package/build/utils/url.js +102 -0
  34. package/package.json +2 -1
package/build/schemas.js CHANGED
@@ -3075,7 +3075,7 @@ export const ListProjectMilestonesSchema = ProjectParamsSchema.extend({
3075
3075
  iids: z
3076
3076
  .array(z.coerce.number())
3077
3077
  .optional()
3078
- .describe("Return only the milestones having the given iid"),
3078
+ .describe("Return only the milestones having the given iid. An empty array is treated as no filter and is left out of the request."),
3079
3079
  state: z
3080
3080
  .enum(["active", "closed"])
3081
3081
  .optional()
@@ -3137,7 +3137,7 @@ export const ListGroupMilestonesSchema = z
3137
3137
  iids: z
3138
3138
  .array(z.coerce.number())
3139
3139
  .optional()
3140
- .describe("Return only the milestones having the given iid"),
3140
+ .describe("Return only the milestones having the given iid. An empty array is treated as no filter and is left out of the request."),
3141
3141
  state: z
3142
3142
  .enum(["active", "closed"])
3143
3143
  .optional()
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env tsx
2
+ /**
3
+ * Generate docs/reference/tool-coverage.md from tools/registry.ts + test/ MCP calls.
4
+ *
5
+ * Detection rules live in ./tool-coverage/coverage.ts (AST-scoped): a tool is
6
+ * invoked when test source sends that name as a `callTool*` argument, as the
7
+ * `name` of a first-argument params object (`client.callTool({ name })`), or as
8
+ * the `name` of a `params` object inside a `tools/call` payload literal.
9
+ *
10
+ * Name-only mentions (toolset tables, description-quality) do not count.
11
+ * callTool(variable) loops are missed unless the name is also a literal in that call.
12
+ *
13
+ * Run with: npm run docs:tools
14
+ */
15
+ import { readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
16
+ import { dirname, join, relative } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { allTools, TOOLSET_DEFINITIONS } from "../tools/registry.js";
19
+ import { assertDetectorHealthy, buildCoverageMarkdown, collectInvocations, countInvoked, groupToolsByToolset, percent, SKIP_FILES, } from "./tool-coverage/coverage.js";
20
+ const __dirname = dirname(fileURLToPath(import.meta.url));
21
+ const REPO_ROOT = join(__dirname, "..");
22
+ const TEST_DIR = join(REPO_ROOT, "test");
23
+ const OUT_PATH = join(REPO_ROOT, "docs", "reference", "tool-coverage.md");
24
+ function walkTestFiles(dir) {
25
+ const out = [];
26
+ for (const name of readdirSync(dir)) {
27
+ const full = join(dir, name);
28
+ const stat = statSync(full);
29
+ if (stat.isDirectory()) {
30
+ out.push(...walkTestFiles(full));
31
+ continue;
32
+ }
33
+ if (/\.(ts|js)$/.test(name) && !SKIP_FILES.has(name)) {
34
+ out.push(full);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ function repoPath(abs) {
40
+ return relative(REPO_ROOT, abs).split("\\").join("/");
41
+ }
42
+ function readScannedFiles() {
43
+ return walkTestFiles(TEST_DIR).map(abs => ({
44
+ path: repoPath(abs),
45
+ text: readFileSync(abs, "utf8"),
46
+ }));
47
+ }
48
+ function main() {
49
+ const toolNames = allTools.map(tool => tool.name);
50
+ const toolNameSet = new Set(toolNames);
51
+ const hits = collectInvocations(readScannedFiles(), toolNameSet);
52
+ const invokedCount = countInvoked(toolNames, hits);
53
+ assertDetectorHealthy(hits, invokedCount);
54
+ const grouped = groupToolsByToolset(toolNames, TOOLSET_DEFINITIONS);
55
+ writeFileSync(OUT_PATH, buildCoverageMarkdown(toolNames, hits, grouped));
56
+ console.log(`generated docs/reference/tool-coverage.md — ${invokedCount}/${toolNames.length} (${percent(invokedCount, toolNames.length)})`);
57
+ }
58
+ main();
@@ -269,6 +269,9 @@ function buildIndexPage(groupedToolsList) {
269
269
  "",
270
270
  "Complete catalog of every tool the GitLab MCP server exposes.",
271
271
  "",
272
+ "Which of these have an MCP `tools/call` test is tracked in",
273
+ "[Tool invocation coverage](../reference/tool-coverage.md).",
274
+ "",
272
275
  "> **Setup first** — if you haven't connected your Personal Access Token or",
273
276
  "> OAuth credentials yet, follow one of the [client setup guides](../clients/claude-code.md)",
274
277
  "> or read [Getting Started](../getting-started/index.md). Tools listed below",
@@ -286,9 +289,11 @@ function buildIndexPage(groupedToolsList) {
286
289
  "Permission modes control which tools are exposed:",
287
290
  "",
288
291
  "- `GITLAB_PERMISSION_MODE=readonly` — hides every write tool regardless of toggles.",
289
- "- `GITLAB_PERMISSION_MODE=modify` — allows create/update but blocks all `delete_*` tools, plus `push_files` `delete`/`move` actions.",
292
+ "- `GITLAB_PERMISSION_MODE=modify` — allows create/update but blocks delete and teardown tools: every `delete_*` tool, `erase_pipeline_job`, `purge_dependency_proxy_cache`, the destructive teardown verbs `cancel_pipeline`, `cancel_pipeline_job`, `stop_environment`, `stop_stale_environments`, `unprotect_branch`, plus `push_files` `delete`/`move` actions.",
290
293
  "- `GITLAB_READ_ONLY_MODE=true` (deprecated) — same as `readonly`; prefer `GITLAB_PERMISSION_MODE=readonly`.",
291
294
  "",
295
+ "The `modify` guard applies to typed tools (`tools/list` and `tools/call`) and to destructive mutations sent through `execute_graphql`: any top-level mutation field whose name contains a deletion verb (`delete`, `destroy`, `remove`, `prune`, `purge`, `erase`) or a teardown verb (`revoke`, `cancel`, `stop`, `terminate`, `unprotect`, `disable`, `deactivate`, `drop`, `unschedule`). See [Environment Variables](../configuration/environment-variables.md#gitlab_permission_mode).",
296
+ "",
292
297
  "See [Environment Variables](../configuration/environment-variables.md)",
293
298
  "and [CLI Arguments](../getting-started/cli-arguments.md) for the full list.",
294
299
  "",
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Portable pure logic for MCP `tools/call` coverage detection.
3
+ *
4
+ * A tool counts as invoked when test source sends that name through MCP, in one
5
+ * of these syntax-scoped positions only:
6
+ *
7
+ * - `callTool("name")`, `callToolJson("name")`, `client.callTool("name")`,
8
+ * `callTool(envOrUrl, "name")` — the name is a string literal directly in the
9
+ * argument list of a `callTool*` callee (identifier or property access).
10
+ * - `client.callTool({ name: "name", arguments })` — SDK shape: the name is the
11
+ * `name` property of an object literal passed as the FIRST argument.
12
+ * - `{ method: "tools/call", params: { name: "name" } }` — the `name` property of
13
+ * a `params` object inside the SAME object literal that carries the method.
14
+ * - `send(proc, "tools/call", { name: "name" })` — the `name` property of an
15
+ * object literal passed as the argument right after a `"tools/call"` method
16
+ * argument (request-helper shape, any callee).
17
+ *
18
+ * Deliberately not counted:
19
+ *
20
+ * - `callTool(toolName, { name: "other" })` — object past the first argument is
21
+ * tool input, not the invoked name.
22
+ * - `name: "tool"` properties outside a `tools/call` payload (fixtures, `tools/list`
23
+ * mocks, tool arguments) in files that merely mention `tools/call`.
24
+ * - variable names (`callTool(env, toolName)`) — not statically resolvable.
25
+ *
26
+ * No filesystem or registry access here; the caller supplies file texts and the
27
+ * tool-name set. The only dependency is the TypeScript parser (devDependency).
28
+ */
29
+ import ts from "typescript";
30
+ export const SKIP_FILES = new Set(["tool-description-quality.test.ts"]);
31
+ export const GROUP_ORDER = [
32
+ "projects",
33
+ "repositories",
34
+ "branches",
35
+ "groups",
36
+ "merge_requests",
37
+ "issues",
38
+ "labels",
39
+ "workitems",
40
+ "ci",
41
+ "pipelines",
42
+ "milestones",
43
+ "wiki",
44
+ "releases",
45
+ "tags",
46
+ "users",
47
+ "variables",
48
+ "webhooks",
49
+ "search",
50
+ "dependency_proxy",
51
+ "vulnerabilities",
52
+ "orbit",
53
+ ];
54
+ export const GROUP_TITLE = {
55
+ merge_requests: "Merge Requests",
56
+ issues: "Issues",
57
+ repositories: "Projects & Files",
58
+ branches: "Branches & Commits",
59
+ projects: "Projects & Namespaces",
60
+ labels: "Labels",
61
+ ci: "CI Lint",
62
+ groups: "Groups",
63
+ pipelines: "Pipelines, Jobs & Deployments",
64
+ milestones: "Milestones",
65
+ wiki: "Wiki",
66
+ releases: "Releases",
67
+ tags: "Tags",
68
+ users: "Users & Events",
69
+ workitems: "Work Items",
70
+ webhooks: "Webhooks",
71
+ search: "Search",
72
+ variables: "Variables",
73
+ dependency_proxy: "Dependency Proxy",
74
+ vulnerabilities: "Vulnerabilities",
75
+ orbit: "GitLab Orbit",
76
+ meta: "Meta & GraphQL",
77
+ };
78
+ export const CANARY_INVOKED = [
79
+ "list_project_variables",
80
+ "orbit_query",
81
+ "list_pipeline_schedules",
82
+ "search_code",
83
+ ];
84
+ export const MIN_INVOKED = 146;
85
+ const CALL_TOOL_CALLEE = /^callTool[A-Za-z]*$/;
86
+ function unwrap(expression) {
87
+ let current = expression;
88
+ while (ts.isAsExpression(current) ||
89
+ ts.isSatisfiesExpression(current) ||
90
+ ts.isParenthesizedExpression(current) ||
91
+ ts.isNonNullExpression(current)) {
92
+ current = current.expression;
93
+ }
94
+ return current;
95
+ }
96
+ function stringValue(expression) {
97
+ const inner = unwrap(expression);
98
+ if (ts.isStringLiteral(inner) || ts.isNoSubstitutionTemplateLiteral(inner)) {
99
+ return inner.text;
100
+ }
101
+ return undefined;
102
+ }
103
+ function propertyKey(prop) {
104
+ const key = prop.name;
105
+ if (ts.isIdentifier(key) || ts.isStringLiteral(key)) {
106
+ return key.text;
107
+ }
108
+ return undefined;
109
+ }
110
+ function namePropertyOf(object) {
111
+ for (const prop of object.properties) {
112
+ if (!ts.isPropertyAssignment(prop)) {
113
+ continue;
114
+ }
115
+ if (propertyKey(prop) !== "name") {
116
+ continue;
117
+ }
118
+ return stringValue(prop.initializer);
119
+ }
120
+ return undefined;
121
+ }
122
+ function callToolCalleeName(callee) {
123
+ if (ts.isIdentifier(callee)) {
124
+ return callee.text;
125
+ }
126
+ if (ts.isPropertyAccessExpression(callee)) {
127
+ return callee.name.text;
128
+ }
129
+ return undefined;
130
+ }
131
+ function collectCallHits(node, toolNames) {
132
+ const calleeName = callToolCalleeName(node.expression);
133
+ if (!calleeName || !CALL_TOOL_CALLEE.test(calleeName)) {
134
+ return [];
135
+ }
136
+ const hits = [];
137
+ node.arguments.forEach((arg, index) => {
138
+ const direct = stringValue(arg);
139
+ if (direct && toolNames.has(direct)) {
140
+ hits.push(direct);
141
+ return;
142
+ }
143
+ // SDK shape only: client.callTool({ name, arguments }) — the object must be
144
+ // the first argument. Objects in later positions are tool input.
145
+ if (index === 0 && ts.isObjectLiteralExpression(unwrap(arg))) {
146
+ const named = namePropertyOf(unwrap(arg));
147
+ if (named && toolNames.has(named)) {
148
+ hits.push(named);
149
+ }
150
+ }
151
+ });
152
+ return hits;
153
+ }
154
+ function collectMethodArgHit(node, toolNames) {
155
+ const args = node.arguments;
156
+ for (let index = 0; index + 1 < args.length; index++) {
157
+ if (stringValue(args[index]) !== "tools/call") {
158
+ continue;
159
+ }
160
+ const params = unwrap(args[index + 1]);
161
+ if (!ts.isObjectLiteralExpression(params)) {
162
+ continue;
163
+ }
164
+ const named = namePropertyOf(params);
165
+ if (named && toolNames.has(named)) {
166
+ return named;
167
+ }
168
+ }
169
+ return undefined;
170
+ }
171
+ function collectPayloadHit(node, toolNames) {
172
+ let isToolsCall = false;
173
+ let paramsName;
174
+ for (const prop of node.properties) {
175
+ if (!ts.isPropertyAssignment(prop)) {
176
+ continue;
177
+ }
178
+ const key = propertyKey(prop);
179
+ if (key === "method" && stringValue(prop.initializer) === "tools/call") {
180
+ isToolsCall = true;
181
+ }
182
+ if (key === "params") {
183
+ const params = unwrap(prop.initializer);
184
+ if (ts.isObjectLiteralExpression(params)) {
185
+ paramsName = namePropertyOf(params);
186
+ }
187
+ }
188
+ }
189
+ if (isToolsCall && paramsName && toolNames.has(paramsName)) {
190
+ return paramsName;
191
+ }
192
+ return undefined;
193
+ }
194
+ /**
195
+ * Scan one source text and return the invoked tool names found in supported
196
+ * call positions. `fileName` selects the TS/JS grammar; unknown extensions
197
+ * parse as TypeScript.
198
+ */
199
+ export function scanSourceForInvocations(sourceText, fileName, toolNames) {
200
+ const hits = new Set();
201
+ const scriptKind = fileName.endsWith(".js") ? ts.ScriptKind.JS : ts.ScriptKind.TS;
202
+ const sourceFile = ts.createSourceFile(fileName, sourceText, ts.ScriptTarget.Latest, false, scriptKind);
203
+ function visit(node) {
204
+ if (ts.isCallExpression(node)) {
205
+ for (const hit of collectCallHits(node, toolNames)) {
206
+ hits.add(hit);
207
+ }
208
+ const methodHit = collectMethodArgHit(node, toolNames);
209
+ if (methodHit) {
210
+ hits.add(methodHit);
211
+ }
212
+ }
213
+ if (ts.isObjectLiteralExpression(node)) {
214
+ const hit = collectPayloadHit(node, toolNames);
215
+ if (hit) {
216
+ hits.add(hit);
217
+ }
218
+ }
219
+ ts.forEachChild(node, visit);
220
+ }
221
+ visit(sourceFile);
222
+ return hits;
223
+ }
224
+ /**
225
+ * Aggregate per-file scan results into tool -> sorted file list. Every known
226
+ * tool gets an entry so uncovered tools render as `- [ ]`.
227
+ */
228
+ export function collectInvocations(files, toolNames) {
229
+ const hits = new Map();
230
+ for (const name of toolNames) {
231
+ hits.set(name, []);
232
+ }
233
+ for (const file of files) {
234
+ for (const name of scanSourceForInvocations(file.text, file.path, toolNames)) {
235
+ const list = hits.get(name);
236
+ if (list && !list.includes(file.path)) {
237
+ list.push(file.path);
238
+ }
239
+ }
240
+ }
241
+ for (const list of hits.values()) {
242
+ list.sort();
243
+ }
244
+ return hits;
245
+ }
246
+ export function countInvoked(toolNames, hits) {
247
+ return toolNames.filter(name => (hits.get(name) ?? []).length > 0).length;
248
+ }
249
+ export function groupToolsByToolset(toolNames, definitions) {
250
+ const categorized = new Set();
251
+ const grouped = [];
252
+ for (const id of GROUP_ORDER) {
253
+ const definition = definitions.find(item => item.id === id);
254
+ if (!definition) {
255
+ throw new Error(`GROUP_ORDER lists '${id}' but TOOLSET_DEFINITIONS does not`);
256
+ }
257
+ const tools = [...definition.tools];
258
+ for (const name of tools) {
259
+ categorized.add(name);
260
+ }
261
+ grouped.push({ id, tools });
262
+ }
263
+ const meta = toolNames.filter(name => !categorized.has(name));
264
+ if (meta.length > 0) {
265
+ grouped.push({ id: "meta", tools: meta });
266
+ }
267
+ return grouped;
268
+ }
269
+ export function percent(invoked, total) {
270
+ if (total === 0) {
271
+ return "0.0%";
272
+ }
273
+ return `${((invoked / total) * 100).toFixed(1)}%`;
274
+ }
275
+ export function toolDocsHref(groupId, toolName) {
276
+ const slug = groupId.replace(/_/g, "-");
277
+ return `../tools/${slug}.md#${toolName}`;
278
+ }
279
+ export function formatFiles(files) {
280
+ return files.map(file => `\`${file}\``).join(", ");
281
+ }
282
+ export function buildCoverageMarkdown(toolNames, hits, grouped) {
283
+ const invokedCount = countInvoked(toolNames, hits);
284
+ const lines = [
285
+ "# Tool invocation coverage",
286
+ "",
287
+ "<!-- Generated by scripts/generate-tool-coverage.ts. Do not edit. -->",
288
+ "",
289
+ "This is **MCP `tools/call` coverage**, not GitLab REST coverage and not line coverage.",
290
+ "",
291
+ 'A tool counts as invoked when a test sends that name through MCP (`callTool` / `callToolJson` / `callToolAsync` / `client.callTool`, or a `tools/call` payload with `name: "…"`). Listing a name in a toolset filter or description-quality test does not count. `test:live` (`test/validate-api.js`) is a REST smoke check and is not included.',
292
+ "",
293
+ "| | |",
294
+ "| --- | ---: |",
295
+ `| Tools | ${toolNames.length} |`,
296
+ `| Invoked | ${invokedCount} |`,
297
+ `| Coverage | ${percent(invokedCount, toolNames.length)} |`,
298
+ "",
299
+ "## By toolset",
300
+ "",
301
+ "| Toolset | Invoked | Total | Coverage |",
302
+ "| --- | ---: | ---: | ---: |",
303
+ ];
304
+ for (const group of grouped) {
305
+ const invoked = countInvoked(group.tools, hits);
306
+ const title = GROUP_TITLE[group.id] ?? group.id;
307
+ lines.push(`| [${title}](#${group.id}) | ${invoked} | ${group.tools.length} | ${percent(invoked, group.tools.length)} |`);
308
+ }
309
+ lines.push("");
310
+ for (const group of grouped) {
311
+ const title = GROUP_TITLE[group.id] ?? group.id;
312
+ lines.push(`## ${title}`);
313
+ lines.push("");
314
+ lines.push(`<a id="${group.id}"></a>`);
315
+ lines.push("");
316
+ for (const name of group.tools) {
317
+ const files = hits.get(name) ?? [];
318
+ const link = `[\`${name}\`](${toolDocsHref(group.id, name)})`;
319
+ if (files.length > 0) {
320
+ lines.push(`- [x] ${link} — ${formatFiles(files)}`);
321
+ }
322
+ else {
323
+ lines.push(`- [ ] ${link}`);
324
+ }
325
+ }
326
+ lines.push("");
327
+ }
328
+ return `${lines.join("\n").trimEnd()}\n`;
329
+ }
330
+ export function assertDetectorHealthy(hits, invokedCount) {
331
+ if (invokedCount < MIN_INVOKED) {
332
+ throw new Error(`scanner found ${invokedCount} invoked tools; expected at least ${MIN_INVOKED} (detector probably broken)`);
333
+ }
334
+ for (const name of CANARY_INVOKED) {
335
+ if ((hits.get(name) ?? []).length === 0) {
336
+ throw new Error(`canary tool ${name} was not detected as invoked (detector probably broken)`);
337
+ }
338
+ }
339
+ }
@@ -0,0 +1,142 @@
1
+ import { describe, test } from "node:test";
2
+ import assert from "node:assert";
3
+ import { assertDetectorHealthy, buildCoverageMarkdown, CANARY_INVOKED, collectInvocations, countInvoked, formatFiles, GROUP_ORDER, groupToolsByToolset, MIN_INVOKED, percent, scanSourceForInvocations, toolDocsHref, } from "./coverage.js";
4
+ const TOOLS = new Set(["list_issues", "get_project", "orbit_query"]);
5
+ function scan(source) {
6
+ return scanSourceForInvocations(source, "probe.ts", TOOLS);
7
+ }
8
+ describe("scanSourceForInvocations", () => {
9
+ test("counts a string literal directly in the argument list", () => {
10
+ assert.deepStrictEqual(scan(`await callTool("list_issues", { project_id: "1" });`), new Set(["list_issues"]));
11
+ });
12
+ test("counts the name in second position after env", () => {
13
+ assert.deepStrictEqual(scan(`await callToolAsync(baseEnv(url), "orbit_query", { query });`), new Set(["orbit_query"]));
14
+ });
15
+ test("counts property-access callees", () => {
16
+ assert.deepStrictEqual(scan(`await client.callTool("get_project", { project_id: "1" });`), new Set(["get_project"]));
17
+ });
18
+ test("counts the SDK object shape when it is the first argument", () => {
19
+ assert.deepStrictEqual(scan(`await client.callTool({ name: "list_issues", arguments: {} });`), new Set(["list_issues"]));
20
+ });
21
+ test("ignores a name object past the first argument (tool input, not invocation)", () => {
22
+ assert.deepStrictEqual(scan(`await callTool(toolName, { name: "get_project" });`), new Set([]));
23
+ });
24
+ test("ignores literals after the call expression closes", () => {
25
+ assert.deepStrictEqual(scan(`await callTool(env, toolName, args);\nconst label = "get_project";`), new Set([]));
26
+ });
27
+ test("ignores variable names", () => {
28
+ assert.deepStrictEqual(scan(`await callTool(env, toolName, args);`), new Set([]));
29
+ });
30
+ test("ignores callees that are not callTool*", () => {
31
+ assert.deepStrictEqual(scan(`await callListIssues({ project_id: "1" }, env);\nnotify("get_project");`), new Set([]));
32
+ });
33
+ test("counts a name inside the same literal as method tools/call", () => {
34
+ assert.deepStrictEqual(scan(`JSON.stringify({
35
+ jsonrpc: "2.0",
36
+ id: 1,
37
+ method: "tools/call",
38
+ params: { name: "list_issues", arguments: args },
39
+ });`), new Set(["list_issues"]));
40
+ });
41
+ test("ignores name properties outside the tools/call payload", () => {
42
+ assert.deepStrictEqual(scan(`
43
+ const listing = { tools: [{ name: "orbit_query", description: "q" }] };
44
+ JSON.stringify({ method: "tools/call", params: { name: "list_issues", arguments: {} } });
45
+ `), new Set(["list_issues"]));
46
+ });
47
+ test("ignores a variable name in the payload", () => {
48
+ assert.deepStrictEqual(scan(`JSON.stringify({ method: "tools/call", params: { name: toolName } });`), new Set([]));
49
+ });
50
+ test("counts a request-helper call with method and params arguments", () => {
51
+ assert.deepStrictEqual(scan(`await sendMcpRequest(proc, "tools/call", { name: "get_project", arguments: {} });`), new Set(["get_project"]));
52
+ });
53
+ test("ignores request-helper calls for other methods", () => {
54
+ assert.deepStrictEqual(scan(`await sendMcpRequest(proc, "initialize", { name: "get_project" });`), new Set([]));
55
+ });
56
+ test("ignores request-helper calls with non-object params", () => {
57
+ assert.deepStrictEqual(scan(`await sendMcpRequest(proc, "tools/call", params);`), new Set([]));
58
+ });
59
+ test("ignores tools/call when params is not an inline object", () => {
60
+ assert.deepStrictEqual(scan(`JSON.stringify({ method: "tools/call", params });`), new Set([]));
61
+ });
62
+ test("accepts quoted property keys and single quotes", () => {
63
+ assert.deepStrictEqual(scan(`JSON.stringify({ "method": 'tools/call', "params": { "name": 'get_project' } });`), new Set(["get_project"]));
64
+ });
65
+ test("unwraps as expressions around the name", () => {
66
+ assert.deepStrictEqual(scan(`await callTool("list_issues" as string);`), new Set(["list_issues"]));
67
+ });
68
+ test("ignores names outside the known tool set", () => {
69
+ assert.deepStrictEqual(scan(`await callTool("no_such_tool", {});`), new Set([]));
70
+ });
71
+ test("parses .js sources", () => {
72
+ const hits = scanSourceForInvocations(`await callTool("get_project", {});`, "probe.js", TOOLS);
73
+ assert.deepStrictEqual(hits, new Set(["get_project"]));
74
+ });
75
+ });
76
+ describe("collectInvocations", () => {
77
+ test("aggregates per-file hits into sorted file lists", () => {
78
+ const hits = collectInvocations([
79
+ { path: "test/b.ts", text: `callTool("get_project", {});` },
80
+ { path: "test/a.ts", text: `callTool("get_project", {}); callTool("list_issues", {});` },
81
+ { path: "test/a.ts", text: `callTool("get_project", {});` },
82
+ ], TOOLS);
83
+ assert.deepStrictEqual(hits.get("get_project"), ["test/a.ts", "test/b.ts"]);
84
+ assert.deepStrictEqual(hits.get("list_issues"), ["test/a.ts"]);
85
+ assert.deepStrictEqual(hits.get("orbit_query"), []);
86
+ });
87
+ });
88
+ describe("groupToolsByToolset", () => {
89
+ test("groups known toolsets and buckets the rest as meta", () => {
90
+ const definitions = GROUP_ORDER.map(id => ({
91
+ id,
92
+ tools: id === "issues" ? ["list_issues"] : [],
93
+ }));
94
+ const grouped = groupToolsByToolset(["list_issues", "stray_tool"], definitions);
95
+ assert.strictEqual(grouped.find(g => g.id === "issues")?.tools.join(","), "list_issues");
96
+ assert.strictEqual(grouped.at(-1)?.id, "meta");
97
+ assert.deepStrictEqual(grouped.at(-1)?.tools, ["stray_tool"]);
98
+ });
99
+ test("throws when GROUP_ORDER names a missing toolset", () => {
100
+ assert.throws(() => groupToolsByToolset([], []), /GROUP_ORDER lists 'projects'/);
101
+ });
102
+ });
103
+ describe("markdown helpers", () => {
104
+ test("percent handles zero totals", () => {
105
+ assert.strictEqual(percent(1, 2), "50.0%");
106
+ assert.strictEqual(percent(0, 0), "0.0%");
107
+ });
108
+ test("toolDocsHref slugifies the group id", () => {
109
+ assert.strictEqual(toolDocsHref("merge_requests", "list_issues"), "../tools/merge-requests.md#list_issues");
110
+ });
111
+ test("formatFiles wraps paths in code spans", () => {
112
+ assert.strictEqual(formatFiles(["test/a.ts", "test/b.ts"]), "`test/a.ts`, `test/b.ts`");
113
+ });
114
+ test("countInvoked counts tools with at least one file", () => {
115
+ const hits = new Map([
116
+ ["list_issues", ["test/a.ts"]],
117
+ ["get_project", []],
118
+ ]);
119
+ assert.strictEqual(countInvoked(["list_issues", "get_project"], hits), 1);
120
+ });
121
+ test("buildCoverageMarkdown renders checked and unchecked rows", () => {
122
+ const markdown = buildCoverageMarkdown(["list_issues", "get_project"], new Map([
123
+ ["list_issues", ["test/a.ts"]],
124
+ ["get_project", []],
125
+ ]), [{ id: "issues", tools: ["list_issues", "get_project"] }]);
126
+ assert.match(markdown, /\| Invoked \| 1 \|/);
127
+ assert.match(markdown, /- \[x\] \[`list_issues`\].*`test\/a\.ts`/);
128
+ assert.match(markdown, /- \[ \] \[`get_project`\]/);
129
+ });
130
+ });
131
+ describe("assertDetectorHealthy", () => {
132
+ test("passes at the floor with all canaries present", () => {
133
+ const hits = new Map(CANARY_INVOKED.map(name => [name, ["test/a.ts"]]));
134
+ assert.doesNotThrow(() => assertDetectorHealthy(hits, MIN_INVOKED));
135
+ });
136
+ test("throws below the floor", () => {
137
+ assert.throws(() => assertDetectorHealthy(new Map(), MIN_INVOKED - 1), /expected at least/);
138
+ });
139
+ test("throws when a canary is missing", () => {
140
+ assert.throws(() => assertDetectorHealthy(new Map(), MIN_INVOKED + 10), /canary tool/);
141
+ });
142
+ });