@zereight/mcp-gitlab 2.1.70 → 2.2.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.
Files changed (158) hide show
  1. package/README.ko.md +9 -5
  2. package/README.md +15 -11
  3. package/README.pt-BR.md +9 -5
  4. package/README.zh-CN.md +9 -5
  5. package/build/config.js +12 -4
  6. package/build/deprecated-env.js +63 -0
  7. package/build/index.js +430 -200
  8. package/build/oauth-device-flow.js +80 -0
  9. package/build/oauth.js +135 -18
  10. package/build/schemas.js +1 -1
  11. package/build/server/remote-http-stack.js +39 -0
  12. package/build/tools/discover-activation.js +38 -0
  13. package/build/tools/exposed-tools.js +35 -0
  14. package/build/tools/listed-tools.js +76 -0
  15. package/build/tools/registry.js +232 -63
  16. package/build/tools/tool-descriptions.js +3 -3
  17. package/build/tools/tool-profile.js +66 -0
  18. package/build/utils/compact-tool-allowlist.js +14 -0
  19. package/build/utils/logger.js +34 -12
  20. package/package.json +3 -3
  21. package/build/scripts/check-skill-sync.js +0 -143
  22. package/build/scripts/generate-server-card.js +0 -39
  23. package/build/scripts/generate-tool-coverage.js +0 -58
  24. package/build/scripts/generate-tool-docs.js +0 -430
  25. package/build/scripts/tool-coverage/coverage.js +0 -341
  26. package/build/scripts/tool-coverage/coverage.test.js +0 -142
  27. package/build/test/callback-proxy-tests.js +0 -321
  28. package/build/test/cli/args.test.js +0 -175
  29. package/build/test/cli/boolean-flags.test.js +0 -106
  30. package/build/test/cli/compact-mcp-result.test.js +0 -93
  31. package/build/test/cli/credentials.test.js +0 -153
  32. package/build/test/cli/exposure.test.js +0 -104
  33. package/build/test/cli/load-config-snapshot.js +0 -5
  34. package/build/test/cli/output.test.js +0 -74
  35. package/build/test/cli/replay-command.test.js +0 -37
  36. package/build/test/cli/router.test.js +0 -183
  37. package/build/test/client-pool-test.js +0 -109
  38. package/build/test/clients/client.js +0 -34
  39. package/build/test/clients/custom-header-client.js +0 -122
  40. package/build/test/clients/sse-client.js +0 -95
  41. package/build/test/clients/stdio-client.js +0 -113
  42. package/build/test/clients/streamable-http-client.js +0 -95
  43. package/build/test/config-allowed-groups.test.js +0 -97
  44. package/build/test/create-commit-actions.test.js +0 -102
  45. package/build/test/draft-note-schema.test.js +0 -44
  46. package/build/test/dynamic-api-url-allowlist.test.js +0 -121
  47. package/build/test/dynamic-api-url-test.js +0 -304
  48. package/build/test/dynamic-routing-tests.js +0 -495
  49. package/build/test/get-merge-request-discussion-schema.test.js +0 -30
  50. package/build/test/gitlab-api-tool-errors.test.js +0 -112
  51. package/build/test/gitlab-artifact-entry-schema.test.js +0 -44
  52. package/build/test/gitlab-diff-schema.test.js +0 -36
  53. package/build/test/gitlab-pipeline-schedule-schema.test.js +0 -32
  54. package/build/test/gitlab-tag-schema.test.js +0 -51
  55. package/build/test/group-milestone-schema.test.js +0 -45
  56. package/build/test/mcp-oauth-tests.js +0 -905
  57. package/build/test/mcp-server-name.test.js +0 -87
  58. package/build/test/merge-merge-request-schema.test.js +0 -75
  59. package/build/test/multi-server-test.js +0 -190
  60. package/build/test/no-proxy-integration-test.js +0 -183
  61. package/build/test/no-proxy-test.js +0 -149
  62. package/build/test/nullable-gitlab-response-fields.test.js +0 -37
  63. package/build/test/nullish-tool-arguments-schema.test.js +0 -118
  64. package/build/test/oauth-device-flow-tests.js +0 -450
  65. package/build/test/oauth-download-url.test.js +0 -157
  66. package/build/test/oauth-startup.test.js +0 -204
  67. package/build/test/oauth-tests.js +0 -428
  68. package/build/test/path-segment-encoding.test.js +0 -98
  69. package/build/test/remote-auth-simple-test.js +0 -277
  70. package/build/test/remote-auth-tests.js +0 -314
  71. package/build/test/response-masking.test.js +0 -445
  72. package/build/test/schema-tests.js +0 -1679
  73. package/build/test/server/metrics.test.js +0 -47
  74. package/build/test/server/request-helpers.test.js +0 -48
  75. package/build/test/server/version.test.js +0 -13
  76. package/build/test/sse-auth-guard.test.js +0 -96
  77. package/build/test/sse-session-limits.test.js +0 -273
  78. package/build/test/stateless/callback-proxy.test.js +0 -510
  79. package/build/test/stateless/client-id.test.js +0 -177
  80. package/build/test/stateless/codec.test.js +0 -328
  81. package/build/test/stateless/config-ttl.test.js +0 -149
  82. package/build/test/stateless/consumed-proxy-code-cache.test.js +0 -150
  83. package/build/test/stateless/session-id-integration.test.js +0 -675
  84. package/build/test/stateless/session-id.test.js +0 -157
  85. package/build/test/streamable-http-concurrent-session.test.js +0 -171
  86. package/build/test/streamable-http-dns-rebinding.test.js +0 -185
  87. package/build/test/streamable-http-sse-stream.test.js +0 -350
  88. package/build/test/streamable-http-static-token-auth.test.js +0 -157
  89. package/build/test/streamable-http-unauthenticated-discovery.test.js +0 -207
  90. package/build/test/test-all-transport-server.js +0 -255
  91. package/build/test/test-auth-retry.js +0 -195
  92. package/build/test/test-blank-filters.js +0 -156
  93. package/build/test/test-ci-catalog.js +0 -177
  94. package/build/test/test-ci-lint.js +0 -191
  95. package/build/test/test-ci-variables.js +0 -309
  96. package/build/test/test-create-repository.js +0 -120
  97. package/build/test/test-dependency-proxy.js +0 -195
  98. package/build/test/test-deployment-tools.js +0 -463
  99. package/build/test/test-download-attachment.js +0 -190
  100. package/build/test/test-dynamic-project-scope.js +0 -524
  101. package/build/test/test-empty-toolsets.js +0 -535
  102. package/build/test/test-get-file-blame.js +0 -145
  103. package/build/test/test-get-file-contents.js +0 -128
  104. package/build/test/test-geteffectiveprojectid.js +0 -804
  105. package/build/test/test-health-check.js +0 -115
  106. package/build/test/test-issue-description-patch.js +0 -256
  107. package/build/test/test-job-artifacts.js +0 -275
  108. package/build/test/test-json-schema.js +0 -166
  109. package/build/test/test-list-group-members.js +0 -150
  110. package/build/test/test-list-group-merge-requests.js +0 -165
  111. package/build/test/test-list-issues.js +0 -170
  112. package/build/test/test-list-merge-requests.js +0 -201
  113. package/build/test/test-list-milestones.js +0 -145
  114. package/build/test/test-list-project-members.js +0 -132
  115. package/build/test/test-merge-request-approval-state-tools.js +0 -213
  116. package/build/test/test-merge-request-approvals.js +0 -187
  117. package/build/test/test-merge-request-pipelines.js +0 -106
  118. package/build/test/test-mr-diffs-filter.js +0 -132
  119. package/build/test/test-mr-file-diffs.js +0 -251
  120. package/build/test/test-oauth-proxy-rate-limit.js +0 -133
  121. package/build/test/test-orbit.js +0 -155
  122. package/build/test/test-permission-mode.js +0 -424
  123. package/build/test/test-pipeline-schedules.js +0 -484
  124. package/build/test/test-protected-branches.js +0 -174
  125. package/build/test/test-remote-downloads.js +0 -510
  126. package/build/test/test-search-code.js +0 -275
  127. package/build/test/test-snippets.js +0 -735
  128. package/build/test/test-tags.js +0 -220
  129. package/build/test/test-todos.js +0 -195
  130. package/build/test/test-token-optimizations.js +0 -691
  131. package/build/test/test-toolset-filtering.js +0 -499
  132. package/build/test/test-update-issue-slim.js +0 -141
  133. package/build/test/test-update-project.js +0 -112
  134. package/build/test/test-upload-markdown.js +0 -206
  135. package/build/test/test-vulnerabilities.js +0 -399
  136. package/build/test/test-webhooks.js +0 -218
  137. package/build/test/tool-description-quality.test.js +0 -50
  138. package/build/test/utils/bulk-publish-options.test.js +0 -32
  139. package/build/test/utils/download-token.test.js +0 -35
  140. package/build/test/utils/forwarded-public-base-url.test.js +0 -46
  141. package/build/test/utils/gitlab-instance-version.test.js +0 -32
  142. package/build/test/utils/gitlab-version-gate.test.js +0 -74
  143. package/build/test/utils/graphql-query.test.js +0 -168
  144. package/build/test/utils/helpers-path.test.js +0 -104
  145. package/build/test/utils/jmespath-tool-result.test.js +0 -91
  146. package/build/test/utils/masking.test.js +0 -384
  147. package/build/test/utils/merge-request-position.test.js +0 -57
  148. package/build/test/utils/mock-gitlab-server.js +0 -614
  149. package/build/test/utils/proxy-client-ip.test.js +0 -28
  150. package/build/test/utils/redact-sensitive.test.js +0 -32
  151. package/build/test/utils/safe-redirect-fetch.test.js +0 -463
  152. package/build/test/utils/server-launcher.js +0 -231
  153. package/build/test/utils/tool-args.test.js +0 -210
  154. package/build/test/utils/url.test.js +0 -141
  155. package/build/test/utils/version-check.test.js +0 -239
  156. package/build/test/utils/wiki-title.test.js +0 -21
  157. package/build/test-note.js +0 -54
  158. package/build/test-resolve-issue-note.js +0 -127
@@ -1,115 +0,0 @@
1
- import { describe, test } from "node:test";
2
- import assert from "node:assert";
3
- import { spawn } from "child_process";
4
- import fs from "node:fs";
5
- import path, { dirname } from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { MockGitLabServer, findMockServerPort } from "./utils/mock-gitlab-server.js";
8
- const MOCK_TOKEN = "glpat-mock-token-12345";
9
- const __filename = fileURLToPath(import.meta.url);
10
- const __dirname = dirname(__filename);
11
- const packageJsonPath = path.resolve(__dirname, "../package.json");
12
- const PACKAGE_VERSION = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).version;
13
- function createMockGitLabServer(port) {
14
- return new MockGitLabServer({
15
- port,
16
- validTokens: [MOCK_TOKEN],
17
- });
18
- }
19
- function baseEnv(mockGitLabUrl) {
20
- return {
21
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
22
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
23
- GITLAB_TOOLSETS: "projects",
24
- };
25
- }
26
- async function callHealthCheckAsync(env) {
27
- return new Promise((resolve, reject) => {
28
- const proc = spawn("node", ["build/index.js"], {
29
- stdio: ["pipe", "pipe", "pipe"],
30
- env: {
31
- ...process.env,
32
- ...env,
33
- USE_PIPELINE: "true",
34
- },
35
- });
36
- let output = "";
37
- let errorOutput = "";
38
- proc.stdout?.on("data", (chunk) => (output += chunk));
39
- proc.stderr?.on("data", (chunk) => (errorOutput += chunk));
40
- proc.on("close", code => {
41
- if (code !== 0) {
42
- return reject(new Error(`Process exited with code ${code}: ${errorOutput}`));
43
- }
44
- const line = output.split("\n").find(entry => entry.startsWith("{"));
45
- if (!line) {
46
- return reject(new Error("No JSON output found"));
47
- }
48
- try {
49
- const response = JSON.parse(line);
50
- if (response.error) {
51
- reject(response.error);
52
- return;
53
- }
54
- const content = response.result?.content?.[0]?.text;
55
- if (!content) {
56
- reject(new Error("No tool result content"));
57
- return;
58
- }
59
- resolve(JSON.parse(content));
60
- }
61
- catch (error) {
62
- reject(error);
63
- }
64
- });
65
- proc.stdin?.end(JSON.stringify({
66
- jsonrpc: "2.0",
67
- id: 1,
68
- method: "tools/call",
69
- params: { name: "health_check", arguments: {} },
70
- }) + "\n");
71
- });
72
- }
73
- describe("When health_check runs", () => {
74
- describe("with authenticated mock GitLab", () => {
75
- test("should include GitLab instance version metadata", async () => {
76
- const mockPort = await findMockServerPort();
77
- const mockGitLab = createMockGitLabServer(mockPort);
78
- await mockGitLab.start();
79
- try {
80
- const result = await callHealthCheckAsync(baseEnv(mockGitLab.getUrl()));
81
- assert.equal(result.status, "ok");
82
- assert.equal(result.authenticated, true);
83
- assert.equal(result.mcp_server_version, PACKAGE_VERSION);
84
- assert.equal(result.version, "18.3.1-ee");
85
- assert.equal(result.revision, "abc1234");
86
- assert.equal(result.enterprise, true);
87
- }
88
- finally {
89
- await mockGitLab.stop();
90
- }
91
- });
92
- });
93
- describe("when GitLab /version lookup fails", () => {
94
- test("should keep health check ok without version fields", async () => {
95
- const mockPort = await findMockServerPort();
96
- const mockGitLab = createMockGitLabServer(mockPort);
97
- mockGitLab.addMockHandler("get", "/version", (_req, res) => {
98
- res.status(500).json({ message: "version unavailable" });
99
- });
100
- await mockGitLab.start();
101
- try {
102
- const result = await callHealthCheckAsync(baseEnv(mockGitLab.getUrl()));
103
- assert.equal(result.status, "ok");
104
- assert.equal(result.authenticated, true);
105
- assert.equal(result.mcp_server_version, PACKAGE_VERSION);
106
- assert.equal("version" in result, false);
107
- assert.equal("revision" in result, false);
108
- assert.equal("enterprise" in result, false);
109
- }
110
- finally {
111
- await mockGitLab.stop();
112
- }
113
- });
114
- });
115
- });
@@ -1,256 +0,0 @@
1
- /**
2
- * Tests for the update_issue_description_patch tool.
3
- * Tests search_replace, unified_diff, dry_run, create_note, and edge cases.
4
- */
5
- import { describe, test, before, after } from "node:test";
6
- import assert from "node:assert";
7
- import { launchServer, cleanupServers, TransportMode, HOST, } from "./utils/server-launcher.js";
8
- import { MockGitLabServer, findMockServerPort, } from "./utils/mock-gitlab-server.js";
9
- import { CustomHeaderClient } from "./clients/custom-header-client.js";
10
- import { parseSearchReplaceBlocks, applySearchReplace, applyUnifiedDiff, } from "../utils/patch-helper.js";
11
- const MOCK_TOKEN = "glpat-patch-test-token-12345";
12
- // ---- Unit tests for patch helper ----
13
- describe("parseSearchReplaceBlocks", () => {
14
- test("parses a single block", () => {
15
- const blocks = parseSearchReplaceBlocks("<<<<<<< SEARCH\nold text\n=======\nnew text\n>>>>>>> REPLACE");
16
- assert.strictEqual(blocks.length, 1);
17
- assert.strictEqual(blocks[0].search, "old text");
18
- assert.strictEqual(blocks[0].replace, "new text");
19
- });
20
- test("parses multiple blocks", () => {
21
- const blocks = parseSearchReplaceBlocks("<<<<<<< SEARCH\nfirst\n=======\nfirst new\n>>>>>>> REPLACE\n<<<<<<< SEARCH\nsecond\n=======\nsecond new\n>>>>>>> REPLACE");
22
- assert.strictEqual(blocks.length, 2);
23
- });
24
- test("handles empty content", () => {
25
- const blocks = parseSearchReplaceBlocks("");
26
- assert.strictEqual(blocks.length, 0);
27
- });
28
- test("ignores text outside blocks", () => {
29
- const blocks = parseSearchReplaceBlocks("prefix\n<<<<<<< SEARCH\nx\n=======\ny\n>>>>>>> REPLACE\nsuffix");
30
- assert.strictEqual(blocks.length, 1);
31
- });
32
- test("rejects malformed block with missing REPLACE marker", () => {
33
- assert.throws(() => parseSearchReplaceBlocks("<<<<<<< SEARCH\nfirst\n=======\nfirst new\n>>>>>>> REPLACE\n" +
34
- "<<<<<<< SEARCH\nsecond\n=======\nsecond new\n>>>>>>> TYPO"), /malformed|Marker|marker/);
35
- });
36
- test("rejects block with missing ======= marker", () => {
37
- assert.throws(() => parseSearchReplaceBlocks("<<<<<<< SEARCH\nfoo\n\nbar\n>>>>>>> REPLACE"), /malformed|Marker|marker/);
38
- });
39
- test("allows prose around valid blocks", () => {
40
- const blocks = parseSearchReplaceBlocks("# Some notes\n\n<<<<<<< SEARCH\nfoo\n=======\nbar\n>>>>>>> REPLACE\n\nMore context");
41
- assert.strictEqual(blocks.length, 1);
42
- });
43
- });
44
- describe("applySearchReplace", () => {
45
- test("replaces single occurrence", () => {
46
- const result = applySearchReplace("Status: In progress\nDone.", [
47
- { search: "Status: In progress", replace: "Status: Done" },
48
- ]);
49
- assert.strictEqual(result.description, "Status: Done\nDone.");
50
- assert.strictEqual(result.changes, 1);
51
- assert.ok(result.summary.includes("Status: In progress"));
52
- assert.ok(result.preview.includes("-Status: In progress"));
53
- });
54
- test("fails on no match", () => {
55
- assert.throws(() => applySearchReplace("Some text.", [{ search: "Nonexistent", replace: "x" }]), /Search text not found/);
56
- });
57
- test("rejects empty SEARCH body", () => {
58
- assert.throws(() => applySearchReplace("Some text.", [{ search: "", replace: "x" }], true), /Empty SEARCH/);
59
- });
60
- test("fails on duplicate without allowMultiple", () => {
61
- assert.throws(() => applySearchReplace("x\ny\nx\n", [{ search: "x", replace: "z" }]), /matches 2 times/);
62
- });
63
- test("replaces all with allowMultiple", () => {
64
- const result = applySearchReplace("x\ny\nx\n", [{ search: "x", replace: "z" }], true);
65
- assert.strictEqual(result.changes, 2);
66
- assert.strictEqual(result.description, "z\ny\nz\n");
67
- });
68
- test("fails on identical replacement", () => {
69
- assert.throws(() => applySearchReplace("Keep this.", [{ search: "Keep this.", replace: "Keep this." }]), /did not change/);
70
- });
71
- test("preserves leading blank line in SEARCH block", () => {
72
- const source = "\n\nStatus: In progress\n";
73
- const result = applySearchReplace(source, [
74
- { search: "\n\nStatus: In progress", replace: "\n\nStatus: Done" },
75
- ]);
76
- assert.strictEqual(result.description, "\n\nStatus: Done\n");
77
- });
78
- test("preserves leading blank line when patch starts with blank line", () => {
79
- const blocks = parseSearchReplaceBlocks("<<<<<<< SEARCH\n\nfoo\n=======\n\nbar\n>>>>>>> REPLACE");
80
- assert.strictEqual(blocks.length, 1);
81
- assert.strictEqual(blocks[0].search, "\nfoo");
82
- assert.strictEqual(blocks[0].replace, "\nbar");
83
- });
84
- test("replacement with leading blank line works", () => {
85
- const result = applySearchReplace("Header\n\nContent\n", [
86
- { search: "Content", replace: "\nNewContent" },
87
- ]);
88
- assert.strictEqual(result.description, "Header\n\n\nNewContent\n");
89
- });
90
- });
91
- describe("applyUnifiedDiff", () => {
92
- test("applies simple diff", () => {
93
- const source = "Line 1\nLine 2\nLine 3\n";
94
- const patch = "--- old\n+++ new\n@@ -1,3 +1,3 @@\n Line 1\n-Line 2\n+Line 2 modified\n Line 3\n";
95
- const result = applyUnifiedDiff(source, patch);
96
- assert.ok(result.description.includes("Line 2 modified"));
97
- });
98
- test("fails on non-matching diff", () => {
99
- const source = "AAA\nBBB\n";
100
- const patch = "--- old\n+++ new\n@@ -1,2 +1,2 @@\n-XXX\n+YYY\n BBB\n";
101
- assert.throws(() => applyUnifiedDiff(source, patch), /could not be applied/);
102
- });
103
- test("fails on malformed patch", () => {
104
- assert.throws(() => applyUnifiedDiff("text", "not a patch"), /no valid hunks/i);
105
- });
106
- });
107
- // ---- Integration tests via MCP client ----
108
- describe("update_issue_description_patch MCP tool", () => {
109
- let mockGitLab;
110
- let server;
111
- let client;
112
- const MOCK_PORT_BASE = 9600;
113
- const MCP_PORT_BASE = 3600;
114
- let portCounter = 0;
115
- async function launchMcp(mockGitLabUrl, extraEnv = {}) {
116
- const port = MCP_PORT_BASE + portCounter++ * 10;
117
- return launchServer({
118
- mode: TransportMode.STREAMABLE_HTTP,
119
- port,
120
- timeout: 10000,
121
- env: {
122
- STREAMABLE_HTTP: "true",
123
- REMOTE_AUTHORIZATION: "true",
124
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
125
- GITLAB_ACCESS_TOKEN: MOCK_TOKEN,
126
- ...extraEnv,
127
- },
128
- });
129
- }
130
- async function getClient(port) {
131
- const client = new CustomHeaderClient({
132
- headers: {
133
- authorization: `Bearer ${MOCK_TOKEN}`,
134
- },
135
- });
136
- await client.connect(`http://${HOST}:${port}/mcp`);
137
- return client;
138
- }
139
- before(async () => {
140
- const mockPort = await findMockServerPort();
141
- mockGitLab = new MockGitLabServer({
142
- port: mockPort,
143
- validTokens: [MOCK_TOKEN],
144
- });
145
- await mockGitLab.start();
146
- const mockGitLabUrl = mockGitLab.getUrl();
147
- server = await launchMcp(mockGitLabUrl, { GITLAB_TOOLSETS: "issues" });
148
- client = await getClient(server.port ?? 0);
149
- });
150
- after(async () => {
151
- await client?.disconnect();
152
- cleanupServers([server]);
153
- await mockGitLab?.stop();
154
- });
155
- test("tool appears in tool list", async () => {
156
- const result = await client.listTools();
157
- const names = result.tools.map((t) => t.name);
158
- assert.ok(names.includes("update_issue_description_patch"), "tool should be in list");
159
- });
160
- test("dry_run: search_replace returns preview without modifying", async () => {
161
- // Get current description
162
- const getResult = await client.callTool("get_issue", {
163
- project_id: "test/project",
164
- issue_iid: "1",
165
- });
166
- const issue = JSON.parse(getResult.content[0]?.text || "{}");
167
- const originalDesc = issue.description;
168
- // Dry-run
169
- const result = await client.callTool("update_issue_description_patch", {
170
- project_id: "test/project",
171
- issue_iid: "1",
172
- patch_type: "search_replace",
173
- patch: `<<<<<<< SEARCH\n${originalDesc}\n=======\nShould NOT persist\n>>>>>>> REPLACE`,
174
- dry_run: true,
175
- });
176
- const data = JSON.parse(result.content[0]?.text || "{}");
177
- assert.strictEqual(data.status, "preview");
178
- assert.strictEqual(data.dry_run, true);
179
- assert.strictEqual(data.changes, 1);
180
- // Verify NOT updated
181
- const getAgain = await client.callTool("get_issue", {
182
- project_id: "test/project",
183
- issue_iid: "1",
184
- });
185
- const issueAgain = JSON.parse(getAgain.content[0]?.text || "{}");
186
- assert.strictEqual(issueAgain.description, originalDesc, "should be unchanged after dry_run");
187
- });
188
- test("search_replace: applies the patch", async () => {
189
- const result = await client.callTool("update_issue_description_patch", {
190
- project_id: "test/project",
191
- issue_iid: "1",
192
- patch_type: "search_replace",
193
- patch: `<<<<<<< SEARCH\nDescription for issue 1\n=======\nPatched description\n>>>>>>> REPLACE`,
194
- });
195
- const data = JSON.parse(result.content[0]?.text || "{}");
196
- assert.strictEqual(data.status, "success");
197
- assert.strictEqual(data.changes, 1);
198
- // Verify persisted
199
- const getResult = await client.callTool("get_issue", {
200
- project_id: "test/project",
201
- issue_iid: "1",
202
- });
203
- const issue = JSON.parse(getResult.content[0]?.text || "{}");
204
- assert.strictEqual(issue.description, "Patched description");
205
- });
206
- test("create_note: note is attempted after update", async () => {
207
- const result = await client.callTool("update_issue_description_patch", {
208
- project_id: "test/project",
209
- issue_iid: "1",
210
- patch_type: "search_replace",
211
- patch: `<<<<<<< SEARCH\nPatched description\n=======\nDescription with note\n>>>>>>> REPLACE`,
212
- create_note: true,
213
- });
214
- const data = JSON.parse(result.content[0]?.text || "{}");
215
- assert.strictEqual(data.status, "success");
216
- assert.ok(data.note !== undefined, "note result should be present");
217
- });
218
- test("search_replace: fails on no match", async () => {
219
- try {
220
- await client.callTool("update_issue_description_patch", {
221
- project_id: "test/project",
222
- issue_iid: "1",
223
- patch_type: "search_replace",
224
- patch: `<<<<<<< SEARCH\nNonExistentText_{UNIQUE}_\n=======\nShould fail\n>>>>>>> REPLACE`,
225
- });
226
- assert.fail("Should have thrown");
227
- }
228
- catch (err) {
229
- const msg = err.message ?? String(err);
230
- assert.ok(msg.includes("not found"), `Error should mention 'not found': ${msg}`);
231
- }
232
- });
233
- test("unified_diff: applies the patch", async () => {
234
- // Set known state
235
- await client.callTool("update_issue_description_patch", {
236
- project_id: "test/project",
237
- issue_iid: "1",
238
- patch_type: "search_replace",
239
- patch: `<<<<<<< SEARCH\nDescription with note\n=======\nLine 1\nLine 2\nLine 3\n>>>>>>> REPLACE`,
240
- });
241
- const result = await client.callTool("update_issue_description_patch", {
242
- project_id: "test/project",
243
- issue_iid: "1",
244
- patch_type: "unified_diff",
245
- patch: "--- old\n+++ new\n@@ -1,3 +1,3 @@\n Line 1\n-Line 2\n+Line 2 changed\n Line 3\n",
246
- });
247
- const data = JSON.parse(result.content[0]?.text || "{}");
248
- assert.strictEqual(data.status, "success");
249
- const getResult = await client.callTool("get_issue", {
250
- project_id: "test/project",
251
- issue_iid: "1",
252
- });
253
- const issue = JSON.parse(getResult.content[0]?.text || "{}");
254
- assert.ok(issue.description.includes("Line 2 changed"));
255
- });
256
- });
@@ -1,275 +0,0 @@
1
- import { describe, test, it, before, after } 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
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import os from 'node:os';
8
- const MOCK_TOKEN = 'glpat-mock-token-12345';
9
- const TEST_PROJECT_ID = '123';
10
- const TEST_JOB_ID = '456';
11
- const NULL_MODE_JOB_ID = '457';
12
- const REDIRECT_JOB_ID = '789';
13
- const REDIRECT_TARGET = 'http://169.254.169.254/latest/meta-data/';
14
- const TEST_ENCODED_ARTIFACT_PATH = 'reports/report#1.txt';
15
- // Helper to run an MCP tool via the built server
16
- async function callTool(toolName, args, env) {
17
- return new Promise((resolve, reject) => {
18
- const proc = spawn('node', ['build/index.js'], {
19
- stdio: ['pipe', 'pipe', 'pipe'],
20
- env: {
21
- ...process.env,
22
- ...env,
23
- GITLAB_READ_ONLY_MODE: 'true',
24
- USE_PIPELINE: 'true',
25
- },
26
- });
27
- let output = '';
28
- let errorOutput = '';
29
- proc.stdout?.on('data', (d) => (output += d));
30
- proc.stderr?.on('data', (d) => (errorOutput += d));
31
- proc.on('close', (code) => {
32
- if (code !== 0)
33
- return reject(new Error(`Process exited with code ${code}: ${errorOutput}`));
34
- const line = output.split('\n').find((l) => l.startsWith('{'));
35
- if (!line)
36
- return reject(new Error('No JSON output found'));
37
- try {
38
- const response = JSON.parse(line);
39
- if (response.error) {
40
- reject(response.error);
41
- }
42
- else {
43
- const content = response.result?.content?.[0]?.text;
44
- if (content) {
45
- try {
46
- resolve(JSON.parse(content));
47
- }
48
- catch {
49
- // Not JSON (plain text response)
50
- resolve(content);
51
- }
52
- }
53
- else {
54
- resolve(response.result);
55
- }
56
- }
57
- }
58
- catch (e) {
59
- reject(e);
60
- }
61
- });
62
- proc.stdin?.end(JSON.stringify({
63
- jsonrpc: '2.0',
64
- id: 1,
65
- method: 'tools/call',
66
- params: { name: toolName, arguments: args },
67
- }) + '\n');
68
- });
69
- }
70
- describe('job artifacts tools', () => {
71
- let mockGitLab;
72
- let mockGitLabUrl;
73
- let tmpDir;
74
- before(async () => {
75
- const mockPort = await findMockServerPort();
76
- mockGitLab = new MockGitLabServer({
77
- port: mockPort,
78
- validTokens: [MOCK_TOKEN],
79
- });
80
- // Add mock handler for artifact tree listing
81
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${TEST_JOB_ID}/artifacts/tree`, (req, res) => {
82
- res.json([
83
- {
84
- name: 'report.xml',
85
- path: 'report.xml',
86
- type: 'file',
87
- size: 1024,
88
- mode: '100644',
89
- },
90
- {
91
- name: 'logs',
92
- path: 'logs',
93
- type: 'directory',
94
- mode: '040755',
95
- },
96
- {
97
- name: 'output.log',
98
- path: 'logs/output.log',
99
- type: 'file',
100
- size: 512,
101
- mode: '100644',
102
- },
103
- ]);
104
- });
105
- // Add mock handler for downloading the full artifact archive
106
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${TEST_JOB_ID}/artifacts`, (req, res) => {
107
- // Return a minimal zip-like binary content for testing
108
- const fakeZipContent = Buffer.from('PK\x03\x04fake-zip-content-for-testing');
109
- res.set('Content-Type', 'application/zip');
110
- res.set('Content-Disposition', `attachment; filename="artifacts_job_${TEST_JOB_ID}.zip"`);
111
- res.send(fakeZipContent);
112
- });
113
- // Add mock handler for getting a single artifact file
114
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${TEST_JOB_ID}/artifacts/report.xml`, (req, res) => {
115
- res.set('Content-Type', 'application/xml');
116
- res.send('<testsuites><testsuite name="unit" tests="5" failures="1"></testsuite></testsuites>');
117
- });
118
- // Add mock handler for path that requires URL encoding
119
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${TEST_JOB_ID}/artifacts/reports/report%231.txt`, (req, res) => {
120
- res.set('Content-Type', 'text/plain');
121
- res.send('encoded artifact content');
122
- });
123
- // GitLab.com can return mode/size as null on artifacts/tree entries (#661)
124
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${NULL_MODE_JOB_ID}/artifacts/tree`, (req, res) => {
125
- res.json([
126
- {
127
- name: 'report.xml',
128
- path: 'report.xml',
129
- type: 'file',
130
- size: 1024,
131
- mode: null,
132
- },
133
- {
134
- name: 'logs',
135
- path: 'logs',
136
- type: 'directory',
137
- size: null,
138
- mode: '040755',
139
- },
140
- ]);
141
- });
142
- // Add mock handler for 404 on non-existent artifact
143
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/999/artifacts/tree`, (req, res) => {
144
- res.status(404).json({ message: 'Not Found' });
145
- });
146
- // GitLab redirects artifact downloads to its object storage, so the hop after this
147
- // response leaves the origin. The destination is a non-public address here.
148
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${REDIRECT_JOB_ID}/artifacts`, (req, res) => {
149
- res.redirect(REDIRECT_TARGET);
150
- });
151
- mockGitLab.addMockHandler('get', `/projects/${TEST_PROJECT_ID}/jobs/${REDIRECT_JOB_ID}/artifacts/report.xml`, (req, res) => {
152
- res.redirect(REDIRECT_TARGET);
153
- });
154
- await mockGitLab.start();
155
- mockGitLabUrl = mockGitLab.getUrl();
156
- // Relative temp dir — absolute local_path is rejected as traversal
157
- tmpDir = `gitlab-mcp-test-artifacts-${process.pid}`;
158
- fs.mkdirSync(tmpDir, { recursive: true });
159
- });
160
- after(async () => {
161
- await mockGitLab.stop();
162
- // Clean up temp directory
163
- if (tmpDir && fs.existsSync(tmpDir)) {
164
- fs.rmSync(tmpDir, { recursive: true, force: true });
165
- }
166
- });
167
- test('list_job_artifacts returns artifact entries', async () => {
168
- const result = await callTool('list_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID }, {
169
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
170
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
171
- });
172
- assert.ok(Array.isArray(result), 'Response should be an array');
173
- assert.strictEqual(result.length, 3, 'Should return 3 artifact entries');
174
- assert.strictEqual(result[0].name, 'report.xml');
175
- assert.strictEqual(result[0].type, 'file');
176
- assert.strictEqual(result[0].size, 1024);
177
- assert.strictEqual(result[1].name, 'logs');
178
- assert.strictEqual(result[1].type, 'directory');
179
- });
180
- describe('When listing job artifacts', () => {
181
- describe('with a null mode entry', () => {
182
- it('should return the entries instead of failing', async () => {
183
- const result = await callTool('list_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: NULL_MODE_JOB_ID }, {
184
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
185
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
186
- });
187
- assert.ok(Array.isArray(result), 'Response should be an array');
188
- assert.strictEqual(result.length, 2);
189
- assert.strictEqual(result[0].mode, null);
190
- assert.strictEqual(result[1].size, null);
191
- });
192
- });
193
- });
194
- test('download_job_artifacts saves archive to disk', async () => {
195
- const result = await callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID, local_path: tmpDir }, {
196
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
197
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
198
- });
199
- assert.ok(result.success, 'Download should succeed');
200
- assert.ok(result.file_path.endsWith('.zip'), 'File should have .zip extension');
201
- assert.ok(fs.existsSync(result.file_path), `File should exist at ${result.file_path}`);
202
- const stats = fs.statSync(result.file_path);
203
- assert.ok(stats.size > 0, 'Downloaded file should not be empty');
204
- });
205
- test('download_job_artifacts creates nested destination directories', async () => {
206
- const nestedLocalPath = path.join(tmpDir, 'artifacts', 'run-42');
207
- const result = await callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID, local_path: nestedLocalPath }, {
208
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
209
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
210
- });
211
- assert.ok(result.success, 'Download should succeed');
212
- assert.ok(fs.existsSync(result.file_path), `File should exist at ${result.file_path}`);
213
- assert.ok(fs.existsSync(nestedLocalPath), `Directory should be created at ${nestedLocalPath}`);
214
- });
215
- test('download_job_artifacts rejects local_path with directory traversal', async () => {
216
- await assert.rejects(() => callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID, local_path: '../../../tmp' }, {
217
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
218
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
219
- }), (err) => {
220
- const msg = String(err.message || err).toLowerCase();
221
- return msg.includes('traversal') || msg.includes('invalid');
222
- });
223
- });
224
- test('download_job_artifacts rejects symlink local_path escape', async () => {
225
- const linkName = path.join(tmpDir, 'symlink-escape');
226
- fs.symlinkSync(os.tmpdir(), linkName);
227
- await assert.rejects(() => callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: TEST_JOB_ID, local_path: linkName }, {
228
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
229
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
230
- }), (err) => {
231
- const msg = String(err.message || err).toLowerCase();
232
- return (msg.includes('symbolic') ||
233
- msg.includes('symlink') ||
234
- msg.includes('escapes') ||
235
- msg.includes('traversal') ||
236
- msg.includes('invalid'));
237
- });
238
- });
239
- test('get_job_artifact_file returns file content', async () => {
240
- const result = await callTool('get_job_artifact_file', {
241
- project_id: TEST_PROJECT_ID,
242
- job_id: TEST_JOB_ID,
243
- artifact_path: 'report.xml',
244
- }, {
245
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
246
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
247
- });
248
- assert.ok(typeof result === 'string', 'Response should be a string');
249
- assert.ok(result.includes('<testsuites>'), 'Should contain XML content');
250
- assert.ok(result.includes('failures="1"'), 'Should contain failure data');
251
- });
252
- test('get_job_artifact_file handles artifact paths with reserved characters', async () => {
253
- const result = await callTool('get_job_artifact_file', {
254
- project_id: TEST_PROJECT_ID,
255
- job_id: TEST_JOB_ID,
256
- artifact_path: TEST_ENCODED_ARTIFACT_PATH,
257
- }, {
258
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
259
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
260
- });
261
- assert.strictEqual(result, 'encoded artifact content');
262
- });
263
- test('download_job_artifacts refuses a redirect to a non-public address', async () => {
264
- await assert.rejects(() => callTool('download_job_artifacts', { project_id: TEST_PROJECT_ID, job_id: REDIRECT_JOB_ID, local_path: tmpDir }, {
265
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
266
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
267
- }), (err) => String(err.message || err).toLowerCase().includes('non-public address'));
268
- });
269
- test('get_job_artifact_file refuses a redirect to a non-public address', async () => {
270
- await assert.rejects(() => callTool('get_job_artifact_file', { project_id: TEST_PROJECT_ID, job_id: REDIRECT_JOB_ID, artifact_path: 'report.xml' }, {
271
- GITLAB_API_URL: `${mockGitLabUrl}/api/v4`,
272
- GITLAB_PERSONAL_ACCESS_TOKEN: MOCK_TOKEN,
273
- }), (err) => String(err.message || err).toLowerCase().includes('non-public address'));
274
- });
275
- });