@zereight/mcp-gitlab 2.1.63 → 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.
@@ -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",
@@ -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,156 @@
1
+ import { describe, test, before, after, afterEach } from "node:test";
2
+ import assert from "node:assert";
3
+ import { spawn } from "child_process";
4
+ import { MockGitLabServer, findMockServerPort } from "./utils/mock-gitlab-server.js";
5
+ const MOCK_TOKEN = "glpat-mock-token-12345";
6
+ const TEST_PROJECT_ID = "123";
7
+ // Cases below cover tools outside the default toolsets, so every toolset is enabled.
8
+ const TOOLSET_ENV = { GITLAB_TOOLSETS: "all" };
9
+ // Helper to run an MCP tool through the stdio server
10
+ async function callTool(toolName, args, env) {
11
+ return new Promise((resolve, reject) => {
12
+ const proc = spawn("node", ["build/index.js"], {
13
+ stdio: ["pipe", "pipe", "pipe"],
14
+ env: {
15
+ ...process.env,
16
+ ...TOOLSET_ENV,
17
+ ...env,
18
+ GITLAB_READ_ONLY_MODE: "true",
19
+ },
20
+ });
21
+ let output = "";
22
+ let errorOutput = "";
23
+ proc.stdout?.on("data", d => (output += d));
24
+ proc.stderr?.on("data", d => (errorOutput += d));
25
+ proc.on("close", code => {
26
+ if (code !== 0)
27
+ return reject(new Error(`Process exited with code ${code}: ${errorOutput}`));
28
+ const line = output.split("\n").find(l => l.startsWith("{"));
29
+ if (!line)
30
+ return reject(new Error("No JSON output found"));
31
+ try {
32
+ const response = JSON.parse(line);
33
+ if (response.error) {
34
+ reject(new Error(JSON.stringify(response.error)));
35
+ return;
36
+ }
37
+ const content = response.result?.content?.[0]?.text;
38
+ if (content) {
39
+ try {
40
+ resolve(JSON.parse(content));
41
+ }
42
+ catch {
43
+ reject(new Error(`Failed to parse tool output JSON: ${content}`));
44
+ }
45
+ }
46
+ else {
47
+ resolve(response.result);
48
+ }
49
+ }
50
+ catch (e) {
51
+ reject(e);
52
+ }
53
+ });
54
+ proc.stdin?.end(JSON.stringify({
55
+ jsonrpc: "2.0",
56
+ id: 1,
57
+ method: "tools/call",
58
+ params: { name: toolName, arguments: args },
59
+ }) + "\n");
60
+ });
61
+ }
62
+ describe("blank query filters", () => {
63
+ let mockGitLab;
64
+ let mockGitLabUrl;
65
+ before(async () => {
66
+ const mockPort = await findMockServerPort();
67
+ mockGitLab = new MockGitLabServer({ port: mockPort, validTokens: [MOCK_TOKEN] });
68
+ await mockGitLab.start();
69
+ mockGitLabUrl = mockGitLab.getUrl();
70
+ });
71
+ after(async () => {
72
+ await mockGitLab.stop();
73
+ });
74
+ afterEach(() => {
75
+ mockGitLab.clearCustomHandlers();
76
+ });
77
+ const env = () => ({
78
+ GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
79
+ GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
80
+ });
81
+ // Registers a handler that captures the request URL and answers with an empty list
82
+ function captureRequest(path) {
83
+ let capturedUrl;
84
+ mockGitLab.addMockHandler("get", path, (req, res) => {
85
+ capturedUrl = req.originalUrl;
86
+ res.json([]);
87
+ });
88
+ return () => {
89
+ assert.ok(capturedUrl, "Mock handler should have received a request");
90
+ return capturedUrl;
91
+ };
92
+ }
93
+ function searchOf(capturedUrl) {
94
+ return new URL(capturedUrl, "http://localhost").search;
95
+ }
96
+ test("list_labels omits blank filters", async () => {
97
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/labels`);
98
+ const labels = await callTool("list_labels", { project_id: TEST_PROJECT_ID, search: "" }, env());
99
+ assert.deepStrictEqual(labels, []);
100
+ assert.strictEqual(searchOf(capturedUrl()), "");
101
+ });
102
+ test("list_tags omits blank filters", async () => {
103
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/repository/tags`);
104
+ const tags = await callTool("list_tags", { project_id: TEST_PROJECT_ID, search: " " }, env());
105
+ assert.deepStrictEqual(tags, []);
106
+ assert.strictEqual(searchOf(capturedUrl()), "");
107
+ });
108
+ test("list_pipelines omits blank filters", async () => {
109
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/pipelines`);
110
+ const pipelines = await callTool("list_pipelines", { project_id: TEST_PROJECT_ID, ref: "" }, env());
111
+ assert.deepStrictEqual(pipelines, []);
112
+ assert.strictEqual(searchOf(capturedUrl()), "");
113
+ });
114
+ test("list_deployments omits blank filters", async () => {
115
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/deployments`);
116
+ const deployments = await callTool("list_deployments", { project_id: TEST_PROJECT_ID, environment: "", ref: "\t" }, env());
117
+ assert.deepStrictEqual(deployments, []);
118
+ assert.strictEqual(searchOf(capturedUrl()), "");
119
+ });
120
+ test("list_environments omits blank filters", async () => {
121
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/environments`);
122
+ const environments = await callTool("list_environments", { project_id: TEST_PROJECT_ID, name: " ", search: "" }, env());
123
+ assert.deepStrictEqual(environments, []);
124
+ assert.strictEqual(searchOf(capturedUrl()), "");
125
+ });
126
+ test("list_job_artifacts omits blank filters", async () => {
127
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/jobs/7/artifacts/tree`);
128
+ const artifacts = await callTool("list_job_artifacts", { project_id: TEST_PROJECT_ID, job_id: "7", path: "" }, env());
129
+ assert.deepStrictEqual(artifacts, []);
130
+ assert.strictEqual(searchOf(capturedUrl()), "");
131
+ });
132
+ test("list_events omits blank filters", async () => {
133
+ const capturedUrl = captureRequest("/events");
134
+ const events = await callTool("list_events", { action: "", scope: " \t" }, env());
135
+ assert.deepStrictEqual(events, []);
136
+ assert.strictEqual(searchOf(capturedUrl()), "");
137
+ });
138
+ test("list_project_variables omits blank nested filters", async () => {
139
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/variables`);
140
+ const variables = await callTool("list_project_variables", { project_id: TEST_PROJECT_ID, filter: { environment_scope: " " } }, env());
141
+ assert.deepStrictEqual(variables, []);
142
+ assert.strictEqual(searchOf(capturedUrl()), "");
143
+ });
144
+ test("list_labels keeps a non-blank filter", async () => {
145
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/labels`);
146
+ await callTool("list_labels", { project_id: TEST_PROJECT_ID, search: "bug" }, env());
147
+ const params = new URL(capturedUrl(), "http://localhost").searchParams;
148
+ assert.deepStrictEqual(params.getAll("search"), ["bug"]);
149
+ });
150
+ test("list_project_variables keeps a non-blank nested filter", async () => {
151
+ const capturedUrl = captureRequest(`/projects/${TEST_PROJECT_ID}/variables`);
152
+ await callTool("list_project_variables", { project_id: TEST_PROJECT_ID, filter: { environment_scope: "production" } }, env());
153
+ const params = new URL(capturedUrl(), "http://localhost").searchParams;
154
+ assert.deepStrictEqual(params.getAll("filter[environment_scope]"), ["production"]);
155
+ });
156
+ });