-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathindex.ts
More file actions
10266 lines (9174 loc) · 331 KB
/
index.ts
File metadata and controls
10266 lines (9174 loc) · 331 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 {
getConfig,
ENABLE_DYNAMIC_API_URL,
GITLAB_AUTH_COOKIE_PATH,
GITLAB_CA_CERT_PATH,
GITLAB_JOB_TOKEN,
GITLAB_MCP_OAUTH,
GITLAB_OAUTH_APP_ID,
GITLAB_OAUTH_SCOPES,
GITLAB_PERSONAL_ACCESS_TOKEN,
GITLAB_POOL_MAX_SIZE,
GITLAB_READ_ONLY_MODE,
GITLAB_TOOLSETS_RAW,
GITLAB_TOOLS_RAW,
HOST,
HTTP_PROXY,
HTTPS_PROXY,
IS_OLD,
MCP_SERVER_URL,
NODE_TLS_REJECT_UNAUTHORIZED,
NO_PROXY,
PORT,
REMOTE_AUTHORIZATION,
SESSION_TIMEOUT_SECONDS,
SSE,
STREAMABLE_HTTP,
USE_GITLAB_WIKI,
USE_MILESTONE,
USE_OAUTH,
USE_PIPELINE,
GITLAB_TOOL_POLICY_APPROVE_RAW,
GITLAB_TOOL_POLICY_HIDDEN_RAW,
} from "./config.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.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 { AsyncLocalStorage } from "node:async_hooks";
import express, { NextFunction, Request, Response } from "express";
import fetchCookie from "fetch-cookie";
import fs from "node:fs";
import os from "node:os";
import nodeFetch from "node-fetch";
import path, { dirname } from "node:path";
import { CookieJar, parse as parseCookie } from "tough-cookie";
import { fileURLToPath, URL } from "node:url";
import { z } from "zod";
import { initializeOAuthClient, GitLabOAuth } from "./oauth.js";
import { createGitLabOAuthProvider } from "./oauth-proxy.js";
import { mcpAuthRouter } from "@modelcontextprotocol/sdk/server/auth/router.js";
import { normalizeGitLabApiUrl } from "./utils/url.js";
import { estimateMergeCommitCount, filterDiffsByPatterns, summarizeWebhookEvents } from "./utils/helpers.js";
import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
import { GitLabClientPool } from "./gitlab-client-pool.js";
import {
allTools,
readOnlyTools,
destructiveTools,
parseEnabledToolsets,
parseIndividualTools,
buildFeatureFlagOverrides,
isToolInEnabledToolset,
TOOLSET_DEFINITIONS,
ALL_TOOLSET_IDS,
type ToolsetId,
} from "./tools/registry.js";
import {
BulkPublishDraftNotesSchema,
CancelPipelineJobSchema,
CancelPipelineSchema,
CreateBranchOptionsSchema,
CreateBranchSchema,
CreateDraftNoteSchema,
CreateIssueLinkSchema,
CreateIssueNoteSchema,
CreateIssueOptionsSchema,
CreateIssueSchema,
CreateLabelSchema, // Added
CreateMergeRequestNoteSchema,
CreateMergeRequestDiscussionNoteSchema,
CreateMergeRequestOptionsSchema,
CreateMergeRequestSchema,
CreateMergeRequestThreadSchema,
CreateNoteSchema,
CreateOrUpdateFileSchema,
CreatePipelineSchema,
CreateProjectMilestoneSchema,
CreateRepositoryOptionsSchema,
CreateRepositorySchema,
CreateWikiPageSchema,
CreateGroupWikiPageSchema,
DeleteDraftNoteSchema,
DeleteGroupWikiPageSchema,
DeleteIssueLinkSchema,
DeleteIssueSchema,
DeleteLabelSchema,
DeleteProjectMilestoneSchema,
DeleteWikiPageSchema,
DeleteMergeRequestNoteSchema,
EditProjectMilestoneSchema,
type FileOperation,
ForkRepositorySchema,
GetBranchDiffsSchema,
GetCommitDiffSchema,
GetCommitSchema,
GetDraftNoteSchema,
GetFileContentsSchema,
GetIssueLinkSchema,
GetIssueSchema,
GetLabelSchema,
GetMergeRequestDiffsSchema,
GetMergeRequestSchema,
GetMilestoneBurndownEventsSchema,
GetMilestoneIssuesSchema,
GetMilestoneMergeRequestsSchema,
GetDeploymentSchema,
GetEnvironmentSchema,
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,
GitLabNamespaceExistsResponseSchema,
GitLabNamespaceSchema,
type GitLabPipeline,
type GitLabPipelineJob,
type GitLabDeployment,
type GitLabEnvironment,
GitLabPipelineJobSchema,
GitLabDeploymentSchema,
GitLabEnvironmentSchema,
GitLabPipelineSchema,
type GitLabPipelineTriggerJob,
GitLabPipelineTriggerJobSchema,
type GitLabProject,
type GitLabProjectMember,
GitLabProjectMemberSchema,
GitLabProjectSchema,
type GitLabReference,
GitLabReferenceSchema,
type GitLabRepository,
GitLabRepositorySchema,
GitLabSearchBlobResultSchema,
type GitLabSearchBlobResult,
type GitLabSearchResponse,
GitLabSearchResponseSchema,
type GitLabTreeItem,
GitLabTreeItemSchema,
type GitLabUser,
GitLabUserSchema,
type GitLabUsersResponse,
GitLabUsersResponseSchema,
type GitLabWikiPage,
GitLabWikiPageSchema,
GroupIteration,
type ListCommitsOptions,
ListCommitsSchema,
ListDraftNotesSchema,
ListGroupIterationsSchema,
ListGroupProjectsSchema,
ListIssueDiscussionsSchema,
ListIssueLinksSchema,
ListIssuesSchema,
ListLabelsSchema,
ListMergeRequestDiffsSchema, // Added
GetMergeRequestFileDiffSchema,
ListMergeRequestChangedFilesSchema,
ListMergeRequestDiscussionsSchema,
ListMergeRequestsSchema,
ListMergeRequestVersionsSchema,
GetMergeRequestVersionSchema,
GitLabMergeRequestVersionSchema,
GitLabMergeRequestVersionDetailSchema,
type GitLabMergeRequestVersion,
type GitLabMergeRequestVersionDetail,
ListNamespacesSchema,
type ListPipelineJobsOptions,
ListPipelineJobsSchema,
type ListPipelinesOptions,
ListPipelinesSchema,
type ListDeploymentsOptions,
ListDeploymentsSchema,
type ListEnvironmentsOptions,
ListEnvironmentsSchema,
type ListPipelineTriggerJobsOptions,
ListPipelineTriggerJobsSchema,
type ListProjectMembersOptions,
ListProjectMembersSchema,
ListProjectMilestonesSchema,
ListProjectsSchema,
ListWikiPagesOptions,
ListWikiPagesSchema,
GetGroupWikiPageSchema,
ListGroupWikiPagesSchema,
UpdateGroupWikiPageSchema,
type ListGroupWikiPagesOptions,
MarkdownUploadSchema,
DownloadAttachmentSchema,
DownloadJobArtifactsSchema,
GetJobArtifactFileSchema,
type GitLabArtifactEntry,
GitLabArtifactEntrySchema,
ListJobArtifactsSchema,
MergeMergeRequestSchema,
ApproveMergeRequestSchema,
UnapproveMergeRequestSchema,
GetMergeRequestApprovalStateSchema,
GetMergeRequestConflictsSchema,
GitLabMergeRequestApprovalsResponseSchema,
GitLabMergeRequestApprovalStateSchema,
type GitLabApprovalUser,
type GitLabMergeRequestApprovalState,
type MergeRequestThreadPosition,
type MyIssuesOptions,
MyIssuesSchema,
type PaginatedDiscussionsResponse,
PaginatedDiscussionsResponseSchema,
type PaginationOptions,
PromoteProjectMilestoneSchema,
PublishDraftNoteSchema,
PlayPipelineJobSchema,
PushFilesSchema,
RetryPipelineJobSchema,
RetryPipelineSchema,
SearchCodeSchema,
SearchGroupCodeSchema,
SearchProjectCodeSchema,
SearchRepositoriesSchema,
UpdateDraftNoteSchema,
UpdateIssueNoteSchema,
UpdateIssueSchema,
UpdateLabelSchema,
UpdateMergeRequestNoteSchema,
UpdateMergeRequestDiscussionNoteSchema,
UpdateMergeRequestSchema,
UpdateWikiPageSchema,
VerifyNamespaceSchema,
GitLabEventSchema,
ListEventsSchema,
GetProjectEventsSchema,
GitLabEvent,
ExecuteGraphQLSchema,
type GitLabRelease,
GitLabReleaseSchema,
ListReleasesSchema,
GetReleaseSchema,
CreateReleaseSchema,
UpdateReleaseSchema,
DeleteReleaseSchema,
CreateReleaseEvidenceSchema,
DownloadReleaseAssetSchema,
GetMergeRequestNotesSchema,
GetMergeRequestNoteSchema,
DeleteMergeRequestDiscussionNoteSchema,
ResolveMergeRequestThreadSchema,
GetWorkItemSchema,
ListWorkItemsSchema,
CreateWorkItemSchema,
UpdateWorkItemSchema,
ConvertWorkItemTypeSchema,
ListWorkItemStatusesSchema,
ListWorkItemNotesSchema,
CreateWorkItemNoteSchema,
MoveWorkItemSchema,
ListCustomFieldDefinitionsSchema,
GetTimelineEventsSchema,
CreateTimelineEventSchema,
ListWebhooksSchema,
ListWebhookEventsSchema,
GetWebhookEventSchema,
} from "./schemas.js";
import { randomUUID } from "node: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 {
// Intentionally ignored: version read failure is non-critical
}
/**
* Create a new MCP Server instance with request handlers registered.
* Each transport connection gets its own Server instance to prevent
* cross-client data leakage (GHSA-345p-7cg4-v4c7).
*/
function createServer(): McpServer {
// Precompute filtered tool list once at server creation (Steps 1–5 are static)
// Step 1: Toolset filter — keep tools in enabled toolsets
const toolsAfterToolsets = allTools.filter(tool =>
isToolInEnabledToolset(tool.name, enabledToolsets)
);
// Step 2: Add GITLAB_TOOLS (individual tools bypass toolset filter)
const toolsetToolNames = new Set(toolsAfterToolsets.map(t => t.name));
const toolsAfterIndividual = [
...toolsAfterToolsets,
...allTools.filter(
tool => individuallyEnabledTools.has(tool.name) && !toolsetToolNames.has(tool.name)
),
];
// Step 3: Add legacy flag overrides (USE_PIPELINE, USE_MILESTONE, USE_GITLAB_WIKI)
const afterIndividualNames = new Set(toolsAfterIndividual.map(t => t.name));
const toolsAfterLegacy = [
...toolsAfterIndividual,
...allTools.filter(
tool => featureFlagOverrides.has(tool.name) && !afterIndividualNames.has(tool.name)
),
];
// Step 4: Read-only filter
const toolsAfterReadOnly = GITLAB_READ_ONLY_MODE
? toolsAfterLegacy.filter(tool => readOnlyTools.has(tool.name))
: toolsAfterLegacy;
// Step 5: Regex denial filter
let filteredTools = GITLAB_DENIED_TOOLS_REGEX
? toolsAfterReadOnly.filter(tool => !GITLAB_DENIED_TOOLS_REGEX!.test(tool.name))
: [...toolsAfterReadOnly];
// Step 5.5: Always include discover_tools meta-tool (bypasses toolset filter)
const discoverTool = allTools.find(t => t.name === "discover_tools");
const filteredToolNames = new Set(filteredTools.map(t => t.name));
if (discoverTool && !filteredToolNames.has("discover_tools")) {
// Respect read-only and regex denial filters
const passesReadOnly = !GITLAB_READ_ONLY_MODE || readOnlyTools.has("discover_tools");
const passesRegex = !GITLAB_DENIED_TOOLS_REGEX?.test("discover_tools");
if (passesReadOnly && passesRegex) {
filteredTools.push(discoverTool);
}
}
// Step 5.7: Remove hidden policy tools
if (hiddenToolSet.size > 0) {
filteredTools = filteredTools.filter(tool => !hiddenToolSet.has(tool.name));
}
const mcpServer = new McpServer(
{
name: "better-gitlab-mcp-server",
version: SERVER_VERSION,
},
{
capabilities: {
tools: {},
},
}
);
mcpServer.server.setRequestHandler(ListToolsRequestSchema, async () => {
// Step 6: Gemini $schema cleanup + annotations (only dynamic step per request)
// <<< START: Remove $schema for Gemini compatibility >>>
const tools = filteredTools.map(tool => {
const modified: any = { ...tool };
// Safety net: remove $schema if present (toJSONSchema strips it for zod schemas,
// but manually-defined schemas like discover_tools may still have it)
if (modified.inputSchema && typeof modified.inputSchema === "object" && modified.inputSchema !== null) {
if ("$schema" in modified.inputSchema) {
modified.inputSchema = { ...modified.inputSchema };
delete modified.inputSchema.$schema;
}
}
// Add MCP tool annotations
modified.annotations = {
...(readOnlyTools.has(tool.name) ? { readOnlyHint: true } : {}),
...(destructiveTools.has(tool.name) ? { destructiveHint: true } : {}),
...(approveToolSet.has(tool.name) ? { confirmationHint: true } : {}),
openWorldHint: true,
};
// Inject _confirmed optional parameter for approve-policy tools
if (approveToolSet.has(tool.name) && modified.inputSchema?.properties) {
modified.inputSchema = {
...modified.inputSchema,
properties: {
...modified.inputSchema.properties,
_confirmed: {
type: "boolean",
description: "Set to true to confirm execution of this approval-required tool.",
},
},
};
}
return modified;
});
// <<< END: Remove $schema for Gemini compatibility >>>
return {
tools, // return tool list with $schema removed
};
});
mcpServer.server.setRequestHandler(CallToolRequestSchema, async (request: any) => {
// Manually retrieve the session context using the session ID passed in the request.
// This is a robust workaround for AsyncLocalStorage context loss.
const sessionId = request.params.sessionId;
const toolName = request.params.name;
const start = Date.now();
const logCompletion = (result: any) => {
const durationMs = Date.now() - start;
logger.info({ tool: toolName, event: "tool_call_done", durationMs }, `tool_call_done: ${toolName} (${durationMs}ms)`);
return result;
};
const logError = (error: unknown) => {
const durationMs = Date.now() - start;
logger.error({ tool: toolName, event: "tool_call_error", durationMs, error: error instanceof Error ? error.message : String(error) }, `tool_call_error: ${toolName} (${durationMs}ms)`);
throw error;
};
try {
// Handle discover_tools meta-tool directly (needs access to mcpServer and filteredTools)
if (toolName === "discover_tools") {
const category = request.params.arguments?.category?.trim()?.toLowerCase();
const currentToolNames = new Set(filteredTools.map(t => t.name));
if (!category) {
// List available categories with activation status
const categories = TOOLSET_DEFINITIONS.map(def => ({
id: def.id,
toolCount: def.tools.size,
active: [...def.tools].some(t => currentToolNames.has(t)),
isDefault: def.isDefault,
}));
return logCompletion({
content: [{
type: "text",
text: JSON.stringify({ categories, hint: "Call discover_tools with a category name to activate it" }, null, 2),
}],
});
}
if (!ALL_TOOLSET_IDS.has(category as ToolsetId)) {
return logCompletion({
content: [{
type: "text",
text: `Unknown category "${category}". Available: ${[...ALL_TOOLSET_IDS].join(", ")}`,
}],
isError: true,
});
}
const toolsetDef = TOOLSET_DEFINITIONS.find(d => d.id === category);
if (!toolsetDef) {
return logCompletion({
content: [{ type: "text", text: `Category "${category}" not found.` }],
isError: true,
});
}
// Check if already fully active
const alreadyActive = [...toolsetDef.tools].every(t => currentToolNames.has(t));
if (alreadyActive) {
return logCompletion({
content: [{
type: "text",
text: `Category "${category}" is already active (${toolsetDef.tools.size} tools).`,
}],
});
}
// Add tools from this toolset, respecting all filtering policies
const newTools: typeof allTools = [];
for (const tool of allTools) {
if (!toolsetDef.tools.has(tool.name)) continue;
if (currentToolNames.has(tool.name)) continue;
if (GITLAB_READ_ONLY_MODE && !readOnlyTools.has(tool.name)) continue;
if (GITLAB_DENIED_TOOLS_REGEX?.test(tool.name)) continue;
if (hiddenToolSet.has(tool.name)) continue;
newTools.push(tool);
}
if (newTools.length === 0) {
return logCompletion({
content: [{
type: "text",
text: `Category "${category}" has no additional tools to activate (all already active or filtered).`,
}],
});
}
filteredTools.push(...newTools);
// Notify client that tool list has changed
try {
await mcpServer.server.sendToolListChanged();
} catch {
// Client may not support notifications - safe to ignore
}
const addedNames = newTools.map(t => t.name);
logger.info({ event: "toolset_activated", category, toolCount: addedNames.length }, `Activated toolset: ${category} (+${addedNames.length} tools)`);
return logCompletion({
content: [{
type: "text",
text: JSON.stringify({
activated: category,
addedTools: addedNames,
totalTools: filteredTools.length,
}, null, 2),
}],
});
}
// Check approve policy: tool is exposed but requires explicit confirmation
if (approveToolSet.has(toolName)) {
const confirmed = request.params.arguments?._confirmed === true;
if (!confirmed) {
logger.info({ tool: toolName, event: "tool_call_approval_required" }, `Approval required: ${toolName}`);
return logCompletion({
content: [{
type: "text",
text: `Tool "${toolName}" requires confirmation. This tool is marked as requiring approval before execution. Re-call with _confirmed: true to proceed.`,
}],
});
}
// Strip _confirmed from args before forwarding to handler
const { _confirmed, ...cleanArgs } = request.params.arguments || {};
request.params.arguments = cleanArgs;
}
if ((REMOTE_AUTHORIZATION || GITLAB_MCP_OAUTH) && sessionId && authBySession[sessionId]) {
const authData = authBySession[sessionId];
const sessionContext: SessionAuth = {
sessionId,
header: authData.header,
token: authData.token,
lastUsed: authData.lastUsed,
apiUrl: authData.apiUrl,
};
// Run the handler within the retrieved context
const result = await sessionAuthStore.run(sessionContext, () => handleToolCall(request.params));
return logCompletion(result);
}
// Fallback for non-remote-auth mode or if session is not found
const result = await handleToolCall(request.params);
return logCompletion(result);
} catch (error) {
logError(error);
}
});
return mcpServer;
}
/**
* Validate configuration at startup
*/
function validateConfiguration(): void {
const errors: string[] = [];
// Validate SESSION_TIMEOUT_SECONDS
const timeoutStr = process.env.SESSION_TIMEOUT_SECONDS;
if (timeoutStr) {
const timeout = Number.parseInt(timeoutStr, 10);
// Allow values >=1 for testing purposes, but recommend 60-86400 for production
if (Number.isNaN(timeout) || timeout < 1 || timeout > 86400) {
errors.push(
`SESSION_TIMEOUT_SECONDS must be between 1 and 86400 seconds, got: ${timeoutStr}`
);
}
if (timeout < 60) {
logger.warn(
`SESSION_TIMEOUT_SECONDS=${timeout} is below recommended minimum of 60 seconds. Only use low values for testing.`
);
}
}
// Validate MAX_SESSIONS
const maxSessionsStr = process.env.MAX_SESSIONS;
if (maxSessionsStr) {
const maxSessions = Number.parseInt(maxSessionsStr, 10);
if (Number.isNaN(maxSessions) || maxSessions < 1 || maxSessions > 10000) {
errors.push(`MAX_SESSIONS must be between 1 and 10000, got: ${maxSessionsStr}`);
}
}
// Validate MAX_REQUESTS_PER_MINUTE
const maxReqStr = process.env.MAX_REQUESTS_PER_MINUTE;
if (maxReqStr) {
const maxReq = Number.parseInt(maxReqStr, 10);
if (Number.isNaN(maxReq) || maxReq < 1 || maxReq > 1000) {
errors.push(`MAX_REQUESTS_PER_MINUTE must be between 1 and 1000, got: ${maxReqStr}`);
}
}
// Validate PORT
const portStr = getConfig("port", "PORT");
if (portStr) {
const port = Number.parseInt(portStr, 10);
if (Number.isNaN(port) || port < 1 || port > 65535) {
errors.push(`PORT must be between 1 and 65535, got: ${portStr}`);
}
}
// Validate GITLAB_API_URL format
const apiUrls = getConfig("api-url", "GITLAB_API_URL")?.split(",") || [];
if (apiUrls.length > 0) {
for (const url of apiUrls) {
try {
new URL(url.trim());
} catch {
errors.push(`GITLAB_API_URL contains an invalid URL: ${url.trim()}`);
}
}
}
// Validate auth configuration
const remoteAuth = getConfig("remote-auth", "REMOTE_AUTHORIZATION") === "true";
const useOAuth = getConfig("use-oauth", "GITLAB_USE_OAUTH") === "true";
const hasToken = !!getConfig("token", "GITLAB_PERSONAL_ACCESS_TOKEN");
const hasJobToken = !!getConfig("job-token", "GITLAB_JOB_TOKEN");
const hasCookie = !!getConfig("cookie-path", "GITLAB_AUTH_COOKIE_PATH");
const mcpOAuth = getConfig("mcp-oauth", "GITLAB_MCP_OAUTH") === "true";
const mcpServerUrl = getConfig("mcp-server-url", "MCP_SERVER_URL");
if (!remoteAuth && !useOAuth && !hasToken && !hasJobToken && !hasCookie && !mcpOAuth) {
errors.push(
"Either --token, --job-token, --cookie-path, --use-oauth=true, --remote-auth=true, or --mcp-oauth=true must be set (or use environment variables)"
);
}
if (mcpOAuth) {
if (!mcpServerUrl) {
errors.push(
"MCP_SERVER_URL is required when GITLAB_MCP_OAUTH=true (e.g. https://mcp.example.com)"
);
} else {
try {
const u = new URL(mcpServerUrl);
const isInsecure = u.protocol !== "https:";
const isLocalhost = u.hostname === "localhost" || u.hostname === "127.0.0.1";
const allowInsecure =
process.env.MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL === "true";
if (isInsecure && !isLocalhost && !allowInsecure) {
errors.push(
"MCP_SERVER_URL must use HTTPS in production " +
"(set MCP_DANGEROUSLY_ALLOW_INSECURE_ISSUER_URL=true for local dev)"
);
}
} catch {
errors.push(`MCP_SERVER_URL is not a valid URL: ${mcpServerUrl}`);
}
}
if (!getConfig("api-url", "GITLAB_API_URL")) {
errors.push("GITLAB_API_URL is required when GITLAB_MCP_OAUTH=true");
}
if (!getConfig("oauth-app-id", "GITLAB_OAUTH_APP_ID")) {
errors.push(
"GITLAB_OAUTH_APP_ID is required when GITLAB_MCP_OAUTH=true " +
"(create an OAuth application in GitLab Admin with the required scopes)"
);
}
}
const enableDynamicApiUrl =
getConfig("enable-dynamic-api-url", "ENABLE_DYNAMIC_API_URL") === "true";
if (enableDynamicApiUrl && !remoteAuth) {
errors.push("ENABLE_DYNAMIC_API_URL=true requires REMOTE_AUTHORIZATION=true");
}
if (errors.length > 0) {
logger.error("Configuration validation failed:");
errors.forEach(err => logger.error(` - ${err}`));
process.exit(1);
}
logger.info("Configuration validation passed");
}
let OAUTH_ACCESS_TOKEN: string | null = null;
let oauthClient: GitLabOAuth | null = null;
/**
* Ensure the OAuth token is valid before making an API call.
* Refreshes the token lazily (only when a tool is actually called).
* This avoids background timers that cause issues with multiple instances.
*/
async function ensureValidOAuthToken(): Promise<void> {
if (!oauthClient) return;
if (oauthClient.hasValidToken()) return;
try {
logger.info("OAuth token expired or missing, refreshing...");
const freshToken = await oauthClient.getAccessToken();
OAUTH_ACCESS_TOKEN = freshToken;
logger.info("OAuth token refreshed successfully");
} catch (error) {
logger.error("Failed to refresh OAuth token:", error);
throw error;
}
}
const GITLAB_DENIED_TOOLS_REGEX = (() => {
const pattern = getConfig("denied-tools-regex", "GITLAB_DENIED_TOOLS_REGEX");
if (!pattern) return undefined;
// Reject patterns that are too long (potential ReDoS vector)
const MAX_PATTERN_LENGTH = 200;
if (pattern.length > MAX_PATTERN_LENGTH) {
logger.error(
`GITLAB_DENIED_TOOLS_REGEX pattern exceeds ${MAX_PATTERN_LENGTH} chars. Ignoring.`
);
return undefined;
}
// Reject patterns with nested quantifiers that can cause catastrophic backtracking (ReDoS)
// e.g., (a+)+, (a*)+, (a+)*, (a{1,})+
// Note: lookahead (?!), (?=), lookbehind (?<), and named groups (?<name>) are safe and allowed
const NESTED_QUANTIFIER_PATTERN = /(\(.*[+*?].*\)|\[.*\])[+*?]/;
if (NESTED_QUANTIFIER_PATTERN.test(pattern)) {
logger.error(
`GITLAB_DENIED_TOOLS_REGEX contains potentially unsafe nested quantifiers. Ignoring.`
);
return undefined;
}
try {
const regex = new RegExp(pattern);
// Dry-run against a sample string to catch immediate issues
regex.test("sample_tool_name");
return regex;
} catch {
logger.error(`Invalid GITLAB_DENIED_TOOLS_REGEX pattern: "${pattern}". Ignoring.`);
return undefined;
}
})();
// ---------------------------------------------------------------------------
// Tool policy: approve / hidden sets
// ---------------------------------------------------------------------------
const approveToolSet = new Set(
(GITLAB_TOOL_POLICY_APPROVE_RAW || "")
.split(",")
.map(s => s.trim())
.filter(Boolean)
);
const hiddenToolSet = new Set(
(GITLAB_TOOL_POLICY_HIDDEN_RAW || "")
.split(",")
.map(s => s.trim())
.filter(Boolean)
);
// Validate approve/hidden tool names against known tools at startup
{
const knownToolNames = new Set(allTools.map(t => t.name));
for (const name of approveToolSet) {
if (!knownToolNames.has(name)) {
logger.warn({ event: "unknown_approve_tool", name }, `GITLAB_TOOL_POLICY_APPROVE contains unknown tool: "${name}"`);
}
}
for (const name of hiddenToolSet) {
if (!knownToolNames.has(name)) {
logger.warn({ event: "unknown_hidden_tool", name }, `GITLAB_TOOL_POLICY_HIDDEN contains unknown tool: "${name}"`);
}
}
}
const clientPool = new GitLabClientPool({
apiUrls: (getConfig("api-url", "GITLAB_API_URL") || "https://gitlab.com")
.split(",")
.map(normalizeGitLabApiUrl),
httpProxy: HTTP_PROXY,
httpsProxy: HTTPS_PROXY,
noProxy: NO_PROXY,
rejectUnauthorized: NODE_TLS_REJECT_UNAUTHORIZED !== "0",
caCertPath: GITLAB_CA_CERT_PATH,
poolMaxSize: GITLAB_POOL_MAX_SIZE,
});
// Create cookie jar with clean Netscape file parsing
// Resolve cookie path once using os.homedir() for cross-platform support
const resolvedCookiePath = GITLAB_AUTH_COOKIE_PATH
? GITLAB_AUTH_COOKIE_PATH.startsWith("~/")
? path.join(os.homedir(), GITLAB_AUTH_COOKIE_PATH.slice(2))
: GITLAB_AUTH_COOKIE_PATH
: null;
const createCookieJar = async (): Promise<CookieJar | null> => {
if (!resolvedCookiePath) return null;
let cookieContent: string;
try {
cookieContent = await fs.promises.readFile(resolvedCookiePath, "utf8");
} catch (error) {
logger.error({ error, path: resolvedCookiePath }, "Failed to read cookie file");
return null;
}
const jar = new CookieJar();
for (let line of cookieContent.split("\n")) {
// Handle #HttpOnly_ prefix
if (line.startsWith("#HttpOnly_")) {
line = line.slice(10);
}
// Skip comments and empty lines
if (line.startsWith("#") || !line.trim()) {
continue;
}
// Parse Netscape format: domain, flag, path, secure, expires, name, value
const parts = line.split("\t");
if (parts.length >= 7) {
const [domain, , cookiePath, secure, expires, name, value] = parts;
// Build cookie string in standard format
const secureFlag = secure === "TRUE" ? "; Secure" : "";
const expiresFlag =
expires === "0"
? ""
: `; Expires=${new Date(Number.parseInt(expires, 10) * 1000).toUTCString()}`;
const cookieStr = `${name}=${value}; Domain=${domain}; Path=${cookiePath}${secureFlag}${expiresFlag}`;
// 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;
};
// Auth retry helpers — extracted to auth-retry.ts for testability (no side effects)
export {
headersToPlainObject,
isNonReplayableBody,
wrapWithAuthRetry,
type AuthRetryConfig,
} from "./auth-retry.js";
import { wrapWithAuthRetry } from "./auth-retry.js";
/** Build AuthRetryConfig from module globals (lazy — reads globals at call time). */
function defaultAuthRetryConfig() {
return {
isOAuthEnabled: () => USE_OAUTH && oauthClient != null,
refreshToken: (force: boolean) => oauthClient!.getAccessToken(force),
onTokenRefreshed: (token: string) => { OAUTH_ACCESS_TOKEN = token; },
buildAuthHeaders,
logger,
};
}
// Cookie jar and fetch - reloaded when cookie file changes
let cookieJar: CookieJar | null = null;
let fetch: typeof nodeFetch = wrapWithAuthRetry(nodeFetch, defaultAuthRetryConfig());
let lastCookieMtime = 0;
let cookieReloadLock: Promise<void> | null = null; // Mutex to prevent parallel reloads
// Auth proxies may redirect and set cookies on the first request. We make a throwaway
// request so subsequent requests have the correct cookies. Reset when cookies reload.
let initialSessionRequestMade = false;
// Cookie jar is loaded on first request via reloadCookiesIfChanged (lastCookieMtime=0 triggers load)
async function reloadCookiesIfChanged(): Promise<void> {
if (!resolvedCookiePath) return;
if (cookieReloadLock) return cookieReloadLock;
cookieReloadLock = (async () => {
try {
const mtime = (await fs.promises.stat(resolvedCookiePath)).mtimeMs;
if (mtime !== lastCookieMtime) {
logger.info(
{ oldMtime: lastCookieMtime, newMtime: mtime },
lastCookieMtime === 0 ? "Loading cookie file" : "Cookie file changed, reloading"
);
lastCookieMtime = mtime;
const newJar = await createCookieJar();
cookieJar = newJar;
fetch = wrapWithAuthRetry(newJar ? fetchCookie(nodeFetch, newJar) : nodeFetch, defaultAuthRetryConfig());
initialSessionRequestMade = false;
}
} catch {
// File deleted or inaccessible - clear cached cookies
if (cookieJar) {
logger.info("Cookie file removed, clearing cached cookies");
cookieJar = null;
fetch = wrapWithAuthRetry(nodeFetch, defaultAuthRetryConfig());
lastCookieMtime = 0;
initialSessionRequestMade = false;
}
}
})();
try {
await cookieReloadLock;
} finally {
cookieReloadLock = null;
}
}
async function ensureSessionForRequest(): Promise<void> {
if (!resolvedCookiePath) return;
await reloadCookiesIfChanged();
if (!cookieJar || initialSessionRequestMade) return;
try {
const response = await fetch(`${getEffectiveApiUrl()}/user`, {
...getFetchConfig(),
redirect: "follow",
});
// 401 means auth failed but the request completed - cookies were still exchanged
initialSessionRequestMade = response.ok || response.status === 401;
} catch {
logger.debug("Session warmup request failed, will retry on next request");
}
}
// Session auth context for remote authorization
interface SessionAuth {
sessionId: string;
header: "Authorization" | "Private-Token" | "JOB-TOKEN";