forked from zereight/gitlab-mcp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
5350 lines (4816 loc) · 170 KB
/
index.ts
File metadata and controls
5350 lines (4816 loc) · 170 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import express, { Request, Response } from "express";
import fetchCookie from "fetch-cookie";
import fs from "fs";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import nodeFetch from "node-fetch";
import path, { dirname } from "path";
import { SocksProxyAgent } from "socks-proxy-agent";
import { CookieJar, parse as parseCookie } from "tough-cookie";
import { fileURLToPath } from "url";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
// Add type imports for proxy agents
import { Agent } from "http";
import { Agent as HttpsAgent } from "https";
import { URL } from "url";
import {
BulkPublishDraftNotesSchema,
CancelPipelineSchema,
CreateBranchOptionsSchema,
CreateBranchSchema,
CreateDraftNoteSchema,
CreateIssueLinkSchema,
CreateIssueNoteSchema,
CreateIssueOptionsSchema,
CreateIssueSchema,
CreateLabelSchema, // Added
CreateMergeRequestNoteSchema,
CreateMergeRequestOptionsSchema,
CreateMergeRequestSchema,
CreateMergeRequestThreadSchema,
CreateNoteSchema,
CreateOrUpdateFileSchema,
CreatePipelineSchema,
CreateProjectMilestoneSchema,
CreateRepositoryOptionsSchema,
CreateRepositorySchema,
CreateWikiPageSchema,
DeleteDraftNoteSchema,
DeleteIssueLinkSchema,
DeleteIssueSchema,
DeleteLabelSchema,
DeleteProjectMilestoneSchema,
DeleteWikiPageSchema,
EditProjectMilestoneSchema,
type FileOperation,
ForkRepositorySchema,
GetBranchDiffsSchema,
GetCommitDiffSchema,
GetCommitSchema,
GetDraftNoteSchema,
GetFileContentsSchema,
GetIssueLinkSchema,
GetIssueSchema,
GetLabelSchema,
GetMergeRequestDiffsSchema,
GetMergeRequestSchema,
GetMilestoneBurndownEventsSchema,
GetMilestoneIssuesSchema,
GetMilestoneMergeRequestsSchema,
GetNamespaceSchema,
// pipeline job schemas
GetPipelineJobOutputSchema,
GetPipelineSchema,
GetProjectMilestoneSchema,
GetProjectSchema,
type GetRepositoryTreeOptions,
GetRepositoryTreeSchema,
GetUsersSchema,
GetWikiPageSchema,
type GitLabCommit,
GitLabCommitSchema,
GitLabCompareResult,
GitLabCompareResultSchema,
type GitLabContent,
GitLabContentSchema,
type GitLabCreateUpdateFileResponse,
GitLabCreateUpdateFileResponseSchema,
GitLabDiffSchema,
type GitLabDiscussion,
// Discussion Types
type GitLabDiscussionNote,
// Discussion Schemas
GitLabDiscussionNoteSchema, // Added
GitLabDiscussionSchema,
// Draft Notes Types
type GitLabDraftNote,
// Draft Notes Schemas
GitLabDraftNoteSchema,
type GitLabFork,
GitLabForkSchema,
type GitLabIssue,
type GitLabIssueLink,
GitLabIssueLinkSchema,
GitLabIssueSchema,
type GitLabIssueWithLinkDetails,
GitLabIssueWithLinkDetailsSchema,
type GitLabLabel,
GitLabMarkdownUpload,
GitLabMarkdownUploadSchema,
type GitLabMergeRequest,
type GitLabMergeRequestDiff,
GitLabMergeRequestSchema,
type GitLabMilestones,
GitLabMilestonesSchema,
type GitLabNamespace,
type GitLabNamespaceExistsResponse,
GitLabNamespaceExistsResponseSchema,
GitLabNamespaceSchema,
type GitLabPipeline,
type GitLabPipelineJob,
GitLabPipelineJobSchema,
GitLabPipelineSchema,
type GitLabPipelineTriggerJob,
GitLabPipelineTriggerJobSchema,
type GitLabProject,
type GitLabProjectMember,
GitLabProjectMemberSchema,
GitLabProjectSchema,
type GitLabReference,
GitLabReferenceSchema,
type GitLabRepository,
GitLabRepositorySchema,
type GitLabSearchResponse,
GitLabSearchResponseSchema,
type GitLabTree,
type GitLabTreeItem,
GitLabTreeItemSchema,
GitLabTreeSchema,
type GitLabUser,
GitLabUserSchema,
type GitLabUsersResponse,
GitLabUsersResponseSchema,
type GitLabWikiPage,
GitLabWikiPageSchema,
GroupIteration,
type ListCommitsOptions,
ListCommitsSchema,
ListDraftNotesSchema,
ListGroupIterationsSchema,
ListGroupProjectsSchema,
ListIssueDiscussionsSchema,
ListIssueLinksSchema,
ListIssuesSchema,
ListLabelsSchema,
ListMergeRequestDiffsSchema, // Added
ListMergeRequestDiscussionsSchema,
ListMergeRequestsSchema,
ListNamespacesSchema,
type ListPipelineJobsOptions,
ListPipelineJobsSchema,
type ListPipelinesOptions,
ListPipelinesSchema,
type ListPipelineTriggerJobsOptions,
ListPipelineTriggerJobsSchema,
type ListProjectMembersOptions,
ListProjectMembersSchema,
ListProjectMilestonesSchema,
ListProjectsSchema,
ListWikiPagesOptions,
ListWikiPagesSchema,
MarkdownUploadSchema,
MergeMergeRequestSchema,
type MergeRequestThreadPosition,
type MergeRequestThreadPositionCreate,
type MyIssuesOptions,
MyIssuesSchema,
type PaginatedDiscussionsResponse,
PaginatedDiscussionsResponseSchema,
type PaginationOptions,
PromoteProjectMilestoneSchema,
PublishDraftNoteSchema,
PushFilesSchema,
RetryPipelineSchema,
SearchRepositoriesSchema,
UpdateDraftNoteSchema,
UpdateIssueNoteSchema,
UpdateIssueSchema,
UpdateLabelSchema,
UpdateMergeRequestNoteSchema,
UpdateMergeRequestSchema,
UpdateWikiPageSchema,
VerifyNamespaceSchema
} from "./schemas.js";
import { randomUUID } from "crypto";
import { pino } from "pino";
const logger = pino({
level: process.env.LOG_LEVEL || "info",
transport: {
target: "pino-pretty",
options: {
colorize: true,
levelFirst: true,
destination: 2,
},
},
});
/**
* Available transport modes for MCP server
*/
enum TransportMode {
STDIO = "stdio",
SSE = "sse",
STREAMABLE_HTTP = "streamable-http",
}
/**
* Read version from package.json
*/
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const packageJsonPath = path.resolve(__dirname, "../package.json");
let SERVER_VERSION = "unknown";
try {
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
SERVER_VERSION = packageJson.version || SERVER_VERSION;
}
} catch (error) {
// Warning: Could not read version from package.json - silently continue
}
const server = new Server(
{
name: "better-gitlab-mcp-server",
version: SERVER_VERSION,
},
{
capabilities: {
tools: {},
},
}
);
const GITLAB_PERSONAL_ACCESS_TOKEN = process.env.GITLAB_PERSONAL_ACCESS_TOKEN;
const GITLAB_AUTH_COOKIE_PATH = process.env.GITLAB_AUTH_COOKIE_PATH;
const IS_OLD = process.env.GITLAB_IS_OLD === "true";
const GITLAB_READ_ONLY_MODE = process.env.GITLAB_READ_ONLY_MODE === "true";
const USE_GITLAB_WIKI = process.env.USE_GITLAB_WIKI === "true";
const USE_MILESTONE = process.env.USE_MILESTONE === "true";
const USE_PIPELINE = process.env.USE_PIPELINE === "true";
const SSE = process.env.SSE === "true";
const STREAMABLE_HTTP = process.env.STREAMABLE_HTTP === "true";
const HOST = process.env.HOST || "0.0.0.0";
const PORT = process.env.PORT || 3002;
// Add proxy configuration
const HTTP_PROXY = process.env.HTTP_PROXY;
const HTTPS_PROXY = process.env.HTTPS_PROXY;
const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
const GITLAB_CA_CERT_PATH = process.env.GITLAB_CA_CERT_PATH;
let sslOptions = undefined;
if (NODE_TLS_REJECT_UNAUTHORIZED === "0") {
sslOptions = { rejectUnauthorized: false };
} else if (GITLAB_CA_CERT_PATH) {
const ca = fs.readFileSync(GITLAB_CA_CERT_PATH);
sslOptions = { ca };
}
// Configure proxy agents if proxies are set
let httpAgent: Agent | undefined = undefined;
let httpsAgent: Agent | undefined = undefined;
if (HTTP_PROXY) {
if (HTTP_PROXY.startsWith("socks")) {
httpAgent = new SocksProxyAgent(HTTP_PROXY);
} else {
httpAgent = new HttpProxyAgent(HTTP_PROXY);
}
}
if (HTTPS_PROXY) {
if (HTTPS_PROXY.startsWith("socks")) {
httpsAgent = new SocksProxyAgent(HTTPS_PROXY);
} else {
httpsAgent = new HttpsProxyAgent(HTTPS_PROXY, sslOptions);
}
}
httpsAgent = httpsAgent || new HttpsAgent(sslOptions);
httpAgent = httpAgent || new Agent();
// Create cookie jar with clean Netscape file parsing
const createCookieJar = (): CookieJar | null => {
if (!GITLAB_AUTH_COOKIE_PATH) return null;
try {
const cookiePath = GITLAB_AUTH_COOKIE_PATH.startsWith("~/")
? path.join(process.env.HOME || "", GITLAB_AUTH_COOKIE_PATH.slice(2))
: GITLAB_AUTH_COOKIE_PATH;
const jar = new CookieJar();
const cookieContent = fs.readFileSync(cookiePath, "utf8");
cookieContent.split("\n").forEach(line => {
// Handle #HttpOnly_ prefix
if (line.startsWith("#HttpOnly_")) {
line = line.slice(10);
}
// Skip comments and empty lines
if (line.startsWith("#") || !line.trim()) {
return;
}
// Parse Netscape format: domain, flag, path, secure, expires, name, value
const parts = line.split("\t");
if (parts.length >= 7) {
const [domain, , path, secure, expires, name, value] = parts;
// Build cookie string in standard format
const cookieStr = `${name}=${value}; Domain=${domain}; Path=${path}${secure === "TRUE" ? "; Secure" : ""}${expires !== "0" ? `; Expires=${new Date(parseInt(expires) * 1000).toUTCString()}` : ""}`;
// Use tough-cookie's parse function for robust parsing
const cookie = parseCookie(cookieStr);
if (cookie) {
const url = `${secure === "TRUE" ? "https" : "http"}://${domain.startsWith(".") ? domain.slice(1) : domain}`;
jar.setCookieSync(cookie, url);
}
}
});
return jar;
} catch (error) {
logger.error("Error loading cookie file:", error);
return null;
}
};
// Initialize cookie jar and fetch
const cookieJar = createCookieJar();
const fetch = cookieJar ? fetchCookie(nodeFetch, cookieJar) : nodeFetch;
// Ensure session is established for the current request
async function ensureSessionForRequest(): Promise<void> {
if (!cookieJar || !GITLAB_AUTH_COOKIE_PATH) return;
// Extract the base URL from GITLAB_API_URL
const apiUrl = new URL(GITLAB_API_URL);
const baseUrl = `${apiUrl.protocol}//${apiUrl.hostname}`;
// Check if we already have GitLab session cookies
const gitlabCookies = cookieJar.getCookiesSync(baseUrl);
const hasSessionCookie = gitlabCookies.some(
cookie => cookie.key === "_gitlab_session" || cookie.key === "remember_user_token"
);
if (!hasSessionCookie) {
try {
// Establish session with a lightweight request
await fetch(`${GITLAB_API_URL}/user`, {
...DEFAULT_FETCH_CONFIG,
redirect: "follow",
}).catch(() => {
// Ignore errors - the important thing is that cookies get set during redirects
});
// Small delay to ensure cookies are fully processed
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
// Ignore session establishment errors
}
}
}
// Modify DEFAULT_HEADERS to include agent configuration
const DEFAULT_HEADERS: Record<string, string> = {
Accept: "application/json",
"Content-Type": "application/json",
};
if (IS_OLD) {
DEFAULT_HEADERS["Private-Token"] = `${GITLAB_PERSONAL_ACCESS_TOKEN}`;
} else {
DEFAULT_HEADERS["Authorization"] = `Bearer ${GITLAB_PERSONAL_ACCESS_TOKEN}`;
}
// Create a default fetch configuration object that includes proxy agents if set
const DEFAULT_FETCH_CONFIG = {
headers: DEFAULT_HEADERS,
agent: (parsedUrl: URL) => {
if (parsedUrl.protocol === "https:") {
return httpsAgent;
}
return httpAgent;
},
};
// Define all available tools
const allTools = [
{
name: "merge_merge_request",
description: "Merge a merge request in a GitLab project",
inputSchema: zodToJsonSchema(MergeMergeRequestSchema),
},
{
name: "create_or_update_file",
description: "Create or update a single file in a GitLab project",
inputSchema: zodToJsonSchema(CreateOrUpdateFileSchema),
},
{
name: "search_repositories",
description: "Search for GitLab projects",
inputSchema: zodToJsonSchema(SearchRepositoriesSchema),
},
{
name: "create_repository",
description: "Create a new GitLab project",
inputSchema: zodToJsonSchema(CreateRepositorySchema),
},
{
name: "get_file_contents",
description: "Get the contents of a file or directory from a GitLab project",
inputSchema: zodToJsonSchema(GetFileContentsSchema),
},
{
name: "push_files",
description: "Push multiple files to a GitLab project in a single commit",
inputSchema: zodToJsonSchema(PushFilesSchema),
},
{
name: "create_issue",
description: "Create a new issue in a GitLab project",
inputSchema: zodToJsonSchema(CreateIssueSchema),
},
{
name: "create_merge_request",
description: "Create a new merge request in a GitLab project",
inputSchema: zodToJsonSchema(CreateMergeRequestSchema),
},
{
name: "fork_repository",
description: "Fork a GitLab project to your account or specified namespace",
inputSchema: zodToJsonSchema(ForkRepositorySchema),
},
{
name: "create_branch",
description: "Create a new branch in a GitLab project",
inputSchema: zodToJsonSchema(CreateBranchSchema),
},
{
name: "get_merge_request",
description:
"Get details of a merge request (Either mergeRequestIid or branchName must be provided)",
inputSchema: zodToJsonSchema(GetMergeRequestSchema),
},
{
name: "get_merge_request_diffs",
description:
"Get the changes/diffs of a merge request (Either mergeRequestIid or branchName must be provided)",
inputSchema: zodToJsonSchema(GetMergeRequestDiffsSchema),
},
{
name: "list_merge_request_diffs",
description:
"List merge request diffs with pagination support (Either mergeRequestIid or branchName must be provided)",
inputSchema: zodToJsonSchema(ListMergeRequestDiffsSchema),
},
{
name: "get_branch_diffs",
description: "Get the changes/diffs between two branches or commits in a GitLab project",
inputSchema: zodToJsonSchema(GetBranchDiffsSchema),
},
{
name: "update_merge_request",
description: "Update a merge request (Either mergeRequestIid or branchName must be provided)",
inputSchema: zodToJsonSchema(UpdateMergeRequestSchema),
},
{
name: "create_note",
description: "Create a new note (comment) to an issue or merge request",
inputSchema: zodToJsonSchema(CreateNoteSchema),
},
{
name: "create_merge_request_thread",
description: "Create a new thread on a merge request",
inputSchema: zodToJsonSchema(CreateMergeRequestThreadSchema),
},
{
name: "mr_discussions",
description: "List discussion items for a merge request",
inputSchema: zodToJsonSchema(ListMergeRequestDiscussionsSchema),
},
{
name: "update_merge_request_note",
description: "Modify an existing merge request thread note",
inputSchema: zodToJsonSchema(UpdateMergeRequestNoteSchema),
},
{
name: "create_merge_request_note",
description: "Add a new note to an existing merge request thread",
inputSchema: zodToJsonSchema(CreateMergeRequestNoteSchema),
},
{
name: "get_draft_note",
description: "Get a single draft note from a merge request",
inputSchema: zodToJsonSchema(GetDraftNoteSchema),
},
{
name: "list_draft_notes",
description: "List draft notes for a merge request",
inputSchema: zodToJsonSchema(ListDraftNotesSchema),
},
{
name: "create_draft_note",
description: "Create a draft note for a merge request",
inputSchema: zodToJsonSchema(CreateDraftNoteSchema),
},
{
name: "update_draft_note",
description: "Update an existing draft note",
inputSchema: zodToJsonSchema(UpdateDraftNoteSchema),
},
{
name: "delete_draft_note",
description: "Delete a draft note",
inputSchema: zodToJsonSchema(DeleteDraftNoteSchema),
},
{
name: "publish_draft_note",
description: "Publish a single draft note",
inputSchema: zodToJsonSchema(PublishDraftNoteSchema),
},
{
name: "bulk_publish_draft_notes",
description: "Publish all draft notes for a merge request",
inputSchema: zodToJsonSchema(BulkPublishDraftNotesSchema),
},
{
name: "update_issue_note",
description: "Modify an existing issue thread note",
inputSchema: zodToJsonSchema(UpdateIssueNoteSchema),
},
{
name: "create_issue_note",
description: "Add a new note to an existing issue thread",
inputSchema: zodToJsonSchema(CreateIssueNoteSchema),
},
{
name: "list_issues",
description:
"List issues (default: created by current user only; use scope='all' for all accessible issues)",
inputSchema: zodToJsonSchema(ListIssuesSchema),
},
{
name: "my_issues",
description: "List issues assigned to the authenticated user (defaults to open issues)",
inputSchema: zodToJsonSchema(MyIssuesSchema),
},
{
name: "get_issue",
description: "Get details of a specific issue in a GitLab project",
inputSchema: zodToJsonSchema(GetIssueSchema),
},
{
name: "update_issue",
description: "Update an issue in a GitLab project",
inputSchema: zodToJsonSchema(UpdateIssueSchema),
},
{
name: "delete_issue",
description: "Delete an issue from a GitLab project",
inputSchema: zodToJsonSchema(DeleteIssueSchema),
},
{
name: "list_issue_links",
description: "List all issue links for a specific issue",
inputSchema: zodToJsonSchema(ListIssueLinksSchema),
},
{
name: "list_issue_discussions",
description: "List discussions for an issue in a GitLab project",
inputSchema: zodToJsonSchema(ListIssueDiscussionsSchema),
},
{
name: "get_issue_link",
description: "Get a specific issue link",
inputSchema: zodToJsonSchema(GetIssueLinkSchema),
},
{
name: "create_issue_link",
description: "Create an issue link between two issues",
inputSchema: zodToJsonSchema(CreateIssueLinkSchema),
},
{
name: "delete_issue_link",
description: "Delete an issue link",
inputSchema: zodToJsonSchema(DeleteIssueLinkSchema),
},
{
name: "list_namespaces",
description: "List all namespaces available to the current user",
inputSchema: zodToJsonSchema(ListNamespacesSchema),
},
{
name: "get_namespace",
description: "Get details of a namespace by ID or path",
inputSchema: zodToJsonSchema(GetNamespaceSchema),
},
{
name: "verify_namespace",
description: "Verify if a namespace path exists",
inputSchema: zodToJsonSchema(VerifyNamespaceSchema),
},
{
name: "get_project",
description: "Get details of a specific project",
inputSchema: zodToJsonSchema(GetProjectSchema),
},
{
name: "list_projects",
description: "List projects accessible by the current user",
inputSchema: zodToJsonSchema(ListProjectsSchema),
},
{
name: "list_project_members",
description: "List members of a GitLab project",
inputSchema: zodToJsonSchema(ListProjectMembersSchema),
},
{
name: "list_labels",
description: "List labels for a project",
inputSchema: zodToJsonSchema(ListLabelsSchema),
},
{
name: "get_label",
description: "Get a single label from a project",
inputSchema: zodToJsonSchema(GetLabelSchema),
},
{
name: "create_label",
description: "Create a new label in a project",
inputSchema: zodToJsonSchema(CreateLabelSchema),
},
{
name: "update_label",
description: "Update an existing label in a project",
inputSchema: zodToJsonSchema(UpdateLabelSchema),
},
{
name: "delete_label",
description: "Delete a label from a project",
inputSchema: zodToJsonSchema(DeleteLabelSchema),
},
{
name: "list_group_projects",
description: "List projects in a GitLab group with filtering options",
inputSchema: zodToJsonSchema(ListGroupProjectsSchema),
},
{
name: "list_wiki_pages",
description: "List wiki pages in a GitLab project",
inputSchema: zodToJsonSchema(ListWikiPagesSchema),
},
{
name: "get_wiki_page",
description: "Get details of a specific wiki page",
inputSchema: zodToJsonSchema(GetWikiPageSchema),
},
{
name: "create_wiki_page",
description: "Create a new wiki page in a GitLab project",
inputSchema: zodToJsonSchema(CreateWikiPageSchema),
},
{
name: "update_wiki_page",
description: "Update an existing wiki page in a GitLab project",
inputSchema: zodToJsonSchema(UpdateWikiPageSchema),
},
{
name: "delete_wiki_page",
description: "Delete a wiki page from a GitLab project",
inputSchema: zodToJsonSchema(DeleteWikiPageSchema),
},
{
name: "get_repository_tree",
description: "Get the repository tree for a GitLab project (list files and directories)",
inputSchema: zodToJsonSchema(GetRepositoryTreeSchema),
},
{
name: "list_pipelines",
description: "List pipelines in a GitLab project with filtering options",
inputSchema: zodToJsonSchema(ListPipelinesSchema),
},
{
name: "get_pipeline",
description: "Get details of a specific pipeline in a GitLab project",
inputSchema: zodToJsonSchema(GetPipelineSchema),
},
{
name: "list_pipeline_jobs",
description: "List all jobs in a specific pipeline",
inputSchema: zodToJsonSchema(ListPipelineJobsSchema),
},
{
name: "list_pipeline_trigger_jobs",
description:
"List all trigger jobs (bridges) in a specific pipeline that trigger downstream pipelines",
inputSchema: zodToJsonSchema(ListPipelineTriggerJobsSchema),
},
{
name: "get_pipeline_job",
description: "Get details of a GitLab pipeline job number",
inputSchema: zodToJsonSchema(GetPipelineJobOutputSchema),
},
{
name: "get_pipeline_job_output",
description:
"Get the output/trace of a GitLab pipeline job with optional pagination to limit context window usage",
inputSchema: zodToJsonSchema(GetPipelineJobOutputSchema),
},
{
name: "create_pipeline",
description: "Create a new pipeline for a branch or tag",
inputSchema: zodToJsonSchema(CreatePipelineSchema),
},
{
name: "retry_pipeline",
description: "Retry a failed or canceled pipeline",
inputSchema: zodToJsonSchema(RetryPipelineSchema),
},
{
name: "cancel_pipeline",
description: "Cancel a running pipeline",
inputSchema: zodToJsonSchema(CancelPipelineSchema),
},
{
name: "list_merge_requests",
description: "List merge requests in a GitLab project with filtering options",
inputSchema: zodToJsonSchema(ListMergeRequestsSchema),
},
{
name: "list_milestones",
description: "List milestones in a GitLab project with filtering options",
inputSchema: zodToJsonSchema(ListProjectMilestonesSchema),
},
{
name: "get_milestone",
description: "Get details of a specific milestone",
inputSchema: zodToJsonSchema(GetProjectMilestoneSchema),
},
{
name: "create_milestone",
description: "Create a new milestone in a GitLab project",
inputSchema: zodToJsonSchema(CreateProjectMilestoneSchema),
},
{
name: "edit_milestone",
description: "Edit an existing milestone in a GitLab project",
inputSchema: zodToJsonSchema(EditProjectMilestoneSchema),
},
{
name: "delete_milestone",
description: "Delete a milestone from a GitLab project",
inputSchema: zodToJsonSchema(DeleteProjectMilestoneSchema),
},
{
name: "get_milestone_issue",
description: "Get issues associated with a specific milestone",
inputSchema: zodToJsonSchema(GetMilestoneIssuesSchema),
},
{
name: "get_milestone_merge_requests",
description: "Get merge requests associated with a specific milestone",
inputSchema: zodToJsonSchema(GetMilestoneMergeRequestsSchema),
},
{
name: "promote_milestone",
description: "Promote a milestone to the next stage",
inputSchema: zodToJsonSchema(PromoteProjectMilestoneSchema),
},
{
name: "get_milestone_burndown_events",
description: "Get burndown events for a specific milestone",
inputSchema: zodToJsonSchema(GetMilestoneBurndownEventsSchema),
},
{
name: "get_users",
description: "Get GitLab user details by usernames",
inputSchema: zodToJsonSchema(GetUsersSchema),
},
{
name: "list_commits",
description: "List repository commits with filtering options",
inputSchema: zodToJsonSchema(ListCommitsSchema),
},
{
name: "get_commit",
description: "Get details of a specific commit",
inputSchema: zodToJsonSchema(GetCommitSchema),
},
{
name: "get_commit_diff",
description: "Get changes/diffs of a specific commit",
inputSchema: zodToJsonSchema(GetCommitDiffSchema),
},
{
name: "list_group_iterations",
description: "List group iterations with filtering options",
inputSchema: zodToJsonSchema(ListGroupIterationsSchema),
},
{
name: "upload_markdown",
description: "Upload a file to a GitLab project for use in markdown content",
inputSchema: zodToJsonSchema(MarkdownUploadSchema),
},
];
// Define which tools are read-only
const readOnlyTools = [
"search_repositories",
"get_file_contents",
"get_merge_request",
"get_merge_request_diffs",
"get_branch_diffs",
"mr_discussions",
"list_issues",
"my_issues",
"list_merge_requests",
"get_issue",
"list_issue_links",
"list_issue_discussions",
"get_issue_link",
"list_namespaces",
"get_namespace",
"verify_namespace",
"get_project",
"list_projects",
"list_project_members",
"get_pipeline",
"list_pipelines",
"list_pipeline_jobs",
"list_pipeline_trigger_jobs",
"get_pipeline_job",
"get_pipeline_job_output",
"list_labels",
"get_label",
"list_group_projects",
"get_repository_tree",
"list_milestones",
"get_milestone",
"get_milestone_issue",
"get_milestone_merge_requests",
"get_milestone_burndown_events",
"list_wiki_pages",
"get_wiki_page",
"get_users",
"list_commits",
"get_commit",
"get_commit_diff",
"list_group_iterations",
"get_group_iteration",
];
// Define which tools are related to wiki and can be toggled by USE_GITLAB_WIKI
const wikiToolNames = [
"list_wiki_pages",
"get_wiki_page",
"create_wiki_page",
"update_wiki_page",
"delete_wiki_page",
"upload_wiki_attachment",
];
// Define which tools are related to milestones and can be toggled by USE_MILESTONE
const milestoneToolNames = [
"list_milestones",
"get_milestone",
"create_milestone",
"edit_milestone",
"delete_milestone",
"get_milestone_issue",
"get_milestone_merge_requests",
"promote_milestone",
"get_milestone_burndown_events",
];
// Define which tools are related to pipelines and can be toggled by USE_PIPELINE
const pipelineToolNames = [
"list_pipelines",
"get_pipeline",
"list_pipeline_jobs",
"list_pipeline_trigger_jobs",
"get_pipeline_job",
"get_pipeline_job_output",
"create_pipeline",
"retry_pipeline",
"cancel_pipeline",
];
/**
* Smart URL handling for GitLab API
*
* @param {string | undefined} url - Input GitLab API URL
* @returns {string} Normalized GitLab API URL with /api/v4 path
*/
function normalizeGitLabApiUrl(url?: string): string {
if (!url) {
return "https://gitlab.com/api/v4";
}
// Remove trailing slash if present
let normalizedUrl = url.endsWith("/") ? url.slice(0, -1) : url;
// Check if URL already has /api/v4
if (!normalizedUrl.endsWith("/api/v4") && !normalizedUrl.endsWith("/api/v4/")) {
// Append /api/v4 if not already present
normalizedUrl = `${normalizedUrl}/api/v4`;
}
return normalizedUrl;
}
// Use the normalizeGitLabApiUrl function to handle various URL formats
const GITLAB_API_URL = normalizeGitLabApiUrl(process.env.GITLAB_API_URL || "");
const GITLAB_PROJECT_ID = process.env.GITLAB_PROJECT_ID;
const GITLAB_ALLOWED_PROJECT_IDS = process.env.GITLAB_ALLOWED_PROJECT_IDS?.split(',').map(id => id.trim()).filter(Boolean) || [];
if (!GITLAB_PERSONAL_ACCESS_TOKEN) {
logger.error("GITLAB_PERSONAL_ACCESS_TOKEN environment variable is not set");
process.exit(1);
}
/**
* Utility function for handling GitLab API errors
* API 에러 처리를 위한 유틸리티 함수 (Utility function for handling API errors)
*
* @param {import("node-fetch").Response} response - The response from GitLab API
* @throws {Error} Throws an error with response details if the request failed
*/
async function handleGitLabError(response: import("node-fetch").Response): Promise<void> {
if (!response.ok) {
const errorBody = await response.text();
// Check specifically for Rate Limit error
if (response.status === 403 && errorBody.includes("User API Key Rate limit exceeded")) {
logger.error("GitLab API Rate Limit Exceeded:", errorBody);
logger.error("User API Key Rate limit exceeded. Please try again later.");
throw new Error(`GitLab API Rate Limit Exceeded: ${errorBody}`);
} else {
// Handle other API errors
throw new Error(`GitLab API error: ${response.status} ${response.statusText}\n${errorBody}`);
}
}
}
/**
* @param {string} projectId - The project ID parameter passed to the function
* @returns {string} The project ID to use for the API call
* @throws {Error} If GITLAB_ALLOWED_PROJECT_IDS is set and the requested project is not in the whitelist
*/
function getEffectiveProjectId(projectId: string): string {
if (GITLAB_ALLOWED_PROJECT_IDS.length > 0) {
// If there's only one allowed project, use it as default
if (GITLAB_ALLOWED_PROJECT_IDS.length === 1 && !projectId) {
return GITLAB_ALLOWED_PROJECT_IDS[0];
}
// If a project ID is provided, check if it's in the whitelist
if (projectId && !GITLAB_ALLOWED_PROJECT_IDS.includes(projectId)) {
throw new Error(`Access denied: Project ${projectId} is not in the allowed project list: ${GITLAB_ALLOWED_PROJECT_IDS.join(', ')}`);
}
// If no project ID provided but we have multiple allowed projects, require an explicit choice
if (!projectId && GITLAB_ALLOWED_PROJECT_IDS.length > 1) {
throw new Error(`Multiple projects allowed (${GITLAB_ALLOWED_PROJECT_IDS.join(', ')}). Please specify a project ID.`);
}
return projectId || GITLAB_ALLOWED_PROJECT_IDS[0];
}
return GITLAB_PROJECT_ID || projectId;
}
/**
* Create a fork of a GitLab project
* 프로젝트 포크 생성 (Create a project fork)
*
* @param {string} projectId - The ID or URL-encoded path of the project
* @param {string} [namespace] - The namespace to fork the project to
* @returns {Promise<GitLabFork>} The created fork
*/
async function forkProject(projectId: string, namespace?: string): Promise<GitLabFork> {
projectId = decodeURIComponent(projectId); // Decode project ID
const effectiveProjectId = getEffectiveProjectId(projectId);
const url = new URL(`${GITLAB_API_URL}/projects/${encodeURIComponent(effectiveProjectId)}/fork`);
if (namespace) {
url.searchParams.append("namespace", namespace);
}
const response = await fetch(url.toString(), {
...DEFAULT_FETCH_CONFIG,
method: "POST",
});