@zereight/mcp-gitlab 2.1.62 → 2.1.64

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,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
+ });
@@ -0,0 +1,30 @@
1
+ import assert from "node:assert/strict";
2
+ import { test } from "node:test";
3
+ import { GetMergeRequestDiscussionSchema, GitLabDiscussionSchema } from "../schemas.js";
4
+ test("get discussion input coerces numeric ids and keeps discussion id", () => {
5
+ const parsed = GetMergeRequestDiscussionSchema.parse({
6
+ project_id: 42,
7
+ merge_request_iid: 7,
8
+ discussion_id: "abc123",
9
+ });
10
+ assert.equal(parsed.project_id, "42");
11
+ assert.equal(parsed.merge_request_iid, "7");
12
+ assert.equal(parsed.discussion_id, "abc123");
13
+ });
14
+ test("get discussion input rejects a missing discussion id", () => {
15
+ assert.throws(() => GetMergeRequestDiscussionSchema.parse({
16
+ project_id: "42",
17
+ merge_request_iid: "7",
18
+ }));
19
+ });
20
+ test("single discussion response parses the GitLab discussion item shape", () => {
21
+ const parsed = GitLabDiscussionSchema.parse({
22
+ id: "abc123",
23
+ individual_note: false,
24
+ notes: [{ id: 1, body: "please fix", resolvable: true, resolved: false }],
25
+ });
26
+ assert.equal(parsed.id, "abc123");
27
+ assert.equal(parsed.individual_note, false);
28
+ assert.equal(parsed.notes.length, 1);
29
+ assert.equal(parsed.notes[0].body, "please fix");
30
+ });