@zereight/mcp-gitlab 2.3.27 → 2.3.28-next.237
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.
- package/README.ko.md +2 -0
- package/README.md +3 -0
- package/README.pt-BR.md +2 -0
- package/README.zh-CN.md +2 -0
- package/build/cli/args.js +2 -0
- package/build/cli-boolean-flags.js +1 -0
- package/build/config.js +11 -0
- package/build/index.js +26 -5
- package/build/utils/audit-log.js +441 -0
- package/package.json +1 -1
package/README.ko.md
CHANGED
|
@@ -307,6 +307,8 @@ v2.3.1 이후의 GitHub 릴리스마다 `gitlab-mcp.mcpb` [MCP Bundle](https://g
|
|
|
307
307
|
- `--compact-result-chars` - compact 임계값 문자 수 (`GITLAB_MCP_COMPACT_RESULT_CHARS` 대체, 기본 `4000`)
|
|
308
308
|
- `--compact-tools` - 전역 compact를 켜지 않고, 응답이 클 때 compact할 도구 이름을 쉼표로 지정 (`GITLAB_MCP_COMPACT_TOOLS` 대체)
|
|
309
309
|
- `--list-summary-default=true` - `list_*` 도구에서 `summary` 인자를 생략하면 `true`로 처리. `summary: false`를 넘기면 전체 JSON을 반환 (`GITLAB_MCP_LIST_SUMMARY_DEFAULT` 대체, 기본 꺼짐)
|
|
310
|
+
- `--audit-log=true` - MCP 도구 호출 SIEM용 NDJSON 감사 로그 (선택, `GITLAB_AUDIT_LOG` 대체, 기본 꺼짐)
|
|
311
|
+
- `--audit-log-file` - 감사 로그 파일 경로. 비우면 stderr NDJSON, stdout에는 쓰지 않음 (`GITLAB_AUDIT_LOG_FILE` 대체)
|
|
310
312
|
- `--tool-profile` - `full`(기본값) 또는 `slim`. `slim`은 draft note, 이모지 반응, 라벨, CI 카탈로그 도구와 `create_group`을 초기 목록에서 뺌. `GITLAB_TOOLSETS`에 공백이 아닌 값이 설정된 경우에만 무시됨 (`GITLAB_TOOL_PROFILE` 대체)
|
|
311
313
|
|
|
312
314
|
이미 `GITLAB_TOOLSETS` 또는 `--toolsets`를 설정했다면 목록을 바꾸지 말고 `wiki`, `milestones`, `pipelines`를 기존 목록에 추가하세요. 이미 `GITLAB_TOOLS` 또는 `--tools`를 설정했다면 `validate_ci_lint`와 `validate_project_ci_lint`를 그 목록에 추가하세요. 명시적 목록은 기본 `core` toolset을 대체하며, 합쳐지지 않습니다.
|
package/README.md
CHANGED
|
@@ -312,6 +312,8 @@ Some MCP clients (like GitHub Copilot CLI) have issues with environment variable
|
|
|
312
312
|
- `--compact-result-chars` - Character threshold for compacting (replaces `GITLAB_MCP_COMPACT_RESULT_CHARS`; default `4000`)
|
|
313
313
|
- `--compact-tools` - Comma-separated tool names to compact when oversized, without turning global compact on (replaces `GITLAB_MCP_COMPACT_TOOLS`)
|
|
314
314
|
- `--list-summary-default=true` - `list_*` tools and `mr_discussions` treat an omitted `summary` argument as `true`; `summary: false` still returns the full JSON (replaces `GITLAB_MCP_LIST_SUMMARY_DEFAULT`; default off)
|
|
315
|
+
- `--audit-log=true` - Opt-in NDJSON audit log of MCP tool calls for SIEM ingestion (replaces `GITLAB_AUDIT_LOG`; default off)
|
|
316
|
+
- `--audit-log-file` - Append audit lines to this file; unset writes NDJSON to stderr, never stdout (replaces `GITLAB_AUDIT_LOG_FILE`)
|
|
315
317
|
- `--tool-profile` - `full` (default) or `slim`. `slim` drops draft notes, emoji reactions, labels, CI catalog tools, and `create_group` from the initial list. Ignored when `GITLAB_TOOLSETS` is set (replaces `GITLAB_TOOL_PROFILE`)
|
|
316
318
|
|
|
317
319
|
If you already set `GITLAB_TOOLSETS` or `--toolsets`, append `wiki`, `milestones`, or `pipelines` to that list instead of replacing it. If you already set `GITLAB_TOOLS` or `--tools`, append `validate_ci_lint` and `validate_project_ci_lint` to that list instead of replacing it. An explicit list replaces the default `core` toolset; it does not merge.
|
|
@@ -590,6 +592,7 @@ The reference document also covers:
|
|
|
590
592
|
- dynamic tool discovery via `discover_tools` (on-demand toolset activation)
|
|
591
593
|
- transport and session variables
|
|
592
594
|
- proxy and TLS variables
|
|
595
|
+
- opt-in SIEM audit log (`GITLAB_AUDIT_LOG`)
|
|
593
596
|
|
|
594
597
|
For callback proxy mode details, see [GitLab MCP OAuth Callback Proxy](./docs/auth/oauth-callback-proxy.md).
|
|
595
598
|
|
package/README.pt-BR.md
CHANGED
|
@@ -307,6 +307,8 @@ Alguns clientes MCP, como o GitHub Copilot CLI, têm problemas com variáveis de
|
|
|
307
307
|
- `--compact-result-chars` - limite de caracteres para compactação (substitui `GITLAB_MCP_COMPACT_RESULT_CHARS`; padrão `4000`)
|
|
308
308
|
- `--compact-tools` - nomes de ferramentas separados por vírgula para compactar quando a resposta for grande, sem ativar o compact global (substitui `GITLAB_MCP_COMPACT_TOOLS`)
|
|
309
309
|
- `--list-summary-default=true` - ferramentas `list_*` tratam o argumento `summary` omitido como `true`; `summary: false` ainda retorna o JSON completo (substitui `GITLAB_MCP_LIST_SUMMARY_DEFAULT`; desativado por padrão)
|
|
310
|
+
- `--audit-log=true` - log de auditoria NDJSON opcional das chamadas de ferramentas MCP para ingestão SIEM (substitui `GITLAB_AUDIT_LOG`; desativado por padrão)
|
|
311
|
+
- `--audit-log-file` - anexa as linhas de auditoria a este arquivo; se omitido, escreve NDJSON em stderr, nunca em stdout (substitui `GITLAB_AUDIT_LOG_FILE`)
|
|
310
312
|
- `--tool-profile` - `full` (padrão) ou `slim`. `slim` remove draft notes, reações com emoji, labels, ferramentas do catálogo de CI e `create_group` da lista inicial. Ignorado apenas quando `GITLAB_TOOLSETS` tem um valor não em branco (substitui `GITLAB_TOOL_PROFILE`)
|
|
311
313
|
|
|
312
314
|
Se você já definiu `GITLAB_TOOLSETS` ou `--toolsets`, acrescente `wiki`, `milestones` ou `pipelines` a essa lista em vez de substituí-la. Se você já definiu `GITLAB_TOOLS` ou `--tools`, acrescente `validate_ci_lint` e `validate_project_ci_lint` a essa lista em vez de substituí-la. Uma lista explícita substitui o toolset padrão `core`; ela não é mesclada.
|
package/README.zh-CN.md
CHANGED
|
@@ -307,6 +307,8 @@ v2.3.1 之后的每个 GitHub Release 都附带 `gitlab-mcp.mcpb` [MCP Bundle](h
|
|
|
307
307
|
- `--compact-result-chars` - compact 字符阈值(替代 `GITLAB_MCP_COMPACT_RESULT_CHARS`,默认 `4000`)
|
|
308
308
|
- `--compact-tools` - 以逗号分隔的工具名,仅在回复过大时对这些工具进行 compact,而不开启全局 compact(替代 `GITLAB_MCP_COMPACT_TOOLS`)
|
|
309
309
|
- `--list-summary-default=true` - `list_*` 工具省略 `summary` 参数时按 `true` 处理;传 `summary: false` 仍返回完整 JSON(替代 `GITLAB_MCP_LIST_SUMMARY_DEFAULT`,默认关闭)
|
|
310
|
+
- `--audit-log=true` - 可选的 MCP 工具调用 NDJSON 审计日志,供 SIEM 采集(替代 `GITLAB_AUDIT_LOG`,默认关闭)
|
|
311
|
+
- `--audit-log-file` - 将审计行追加到该文件;未设置时写入 stderr 的 NDJSON,绝不写入 stdout(替代 `GITLAB_AUDIT_LOG_FILE`)
|
|
310
312
|
- `--tool-profile` - `full`(默认)或 `slim`。`slim` 会从初始列表中移除 draft note、表情回应、标签、CI 目录工具以及 `create_group`。仅当 `GITLAB_TOOLSETS` 设置为非空白值时忽略(替代 `GITLAB_TOOL_PROFILE`)
|
|
311
313
|
|
|
312
314
|
如果已经设置了 `GITLAB_TOOLSETS` 或 `--toolsets`,请把 `wiki`、`milestones` 或 `pipelines` 追加到该列表,不要整段替换。如果已经设置了 `GITLAB_TOOLS` 或 `--tools`,请把 `validate_ci_lint` 和 `validate_project_ci_lint` 追加到该列表,不要整段替换。显式列表会替换默认的 `core` toolset,不会合并。
|
package/build/cli/args.js
CHANGED
package/build/config.js
CHANGED
|
@@ -42,6 +42,17 @@ export const GITLAB_MASKING_POLICY_FILE = getConfig("masking-policy-file", "GITL
|
|
|
42
42
|
export const GITLAB_MASKING_WORKSPACE_DIR = getConfig("masking-workspace-dir", "GITLAB_MASKING_WORKSPACE_DIR");
|
|
43
43
|
/** Directory that download_attachment saves files under (default .gitlab-mcp-downloads). */
|
|
44
44
|
export const GITLAB_DOWNLOAD_DIR = getConfig("download-dir", "GITLAB_DOWNLOAD_DIR");
|
|
45
|
+
/**
|
|
46
|
+
* Opt-in NDJSON audit log of MCP tool calls for SIEM ingestion.
|
|
47
|
+
* Off by default: unset or any value other than `true` leaves tool-call
|
|
48
|
+
* behavior and output unchanged.
|
|
49
|
+
*/
|
|
50
|
+
export const GITLAB_AUDIT_LOG = getConfig("audit-log", "GITLAB_AUDIT_LOG") === "true";
|
|
51
|
+
/**
|
|
52
|
+
* Optional destination file for the audit log. When unset, NDJSON lines go to
|
|
53
|
+
* stderr. Never stdout: stdio transport uses stdout for MCP messages.
|
|
54
|
+
*/
|
|
55
|
+
export const GITLAB_AUDIT_LOG_FILE = getConfig("audit-log-file", "GITLAB_AUDIT_LOG_FILE");
|
|
45
56
|
const PERMISSION_MODES = ["readonly", "modify", "full"];
|
|
46
57
|
export const GITLAB_PERMISSION_MODE_RAW = getConfig("permission-mode", "GITLAB_PERMISSION_MODE");
|
|
47
58
|
export const GITLAB_PERMISSION_MODE = (() => {
|
package/build/index.js
CHANGED
|
@@ -149,6 +149,7 @@ GitLabDiscussionSchema,
|
|
|
149
149
|
GitLabDraftNoteSchema, GitLabForkSchema, GitLabBranchSchema, GitLabProtectedBranchSchema, GitLabGroupSchema, GitLabIssueLinkSchema, GitLabIssueSchema, GitLabIssueWithLinkDetailsSchema, GitLabMarkdownUploadSchema, GitLabMergeRequestPipelineSchema, GitLabMergeRequestSchema, GitLabNamespaceExistsResponseSchema, GitLabNamespaceSchema, GitLabPipelineJobSchema, GitLabDeploymentSchema, GitLabEnvironmentSchema, GitLabPipelineSchema, GitLabPipelineScheduleSchema, GitLabPipelineScheduleVariableSchema, GitLabPipelineSchedulePlayResultSchema, ListPipelineSchedulesSchema, GetPipelineScheduleSchema, ListPipelineSchedulePipelinesSchema, CreatePipelineScheduleSchema, UpdatePipelineScheduleSchema, DeletePipelineScheduleSchema, PlayPipelineScheduleSchema, TakeOwnershipPipelineScheduleSchema, GetPipelineScheduleVariableSchema, CreatePipelineScheduleVariableSchema, UpdatePipelineScheduleVariableSchema, DeletePipelineScheduleVariableSchema, GitLabPipelineTriggerJobSchema, GitLabProjectMemberSchema, GitLabProjectSchema, GitLabTodoSchema, GitLabReferenceSchema, GitLabRepositorySchema, GitLabSearchBlobResultSchema, GitLabSearchResponseSchema, GitLabTreeItemSchema, GitLabUserSchema, GitLabUsersResponseSchema, GroupIteration, ListCommitStatusesSchema, ListBranchesSchema, ListCommitsSchema, ListDraftNotesSchema, ListGroupIterationsSchema, GetGroupIterationSchema, UpdateGroupIterationSchema, CreateGroupIterationSchema, GroupIterationCadence, ListGroupIterationCadencesSchema, DeleteGroupIterationSchema, ListProjectIterationsSchema, CreateGroupIterationCadenceSchema, UpdateGroupIterationCadenceSchema, DeleteGroupIterationCadenceSchema, ListGroupProjectsSchema, GitLabCiVariableSchema, ListProjectVariablesSchema, GetProjectVariableSchema, CreateProjectVariableSchema, UpdateProjectVariableSchema, DeleteProjectVariableSchema, ListGroupVariablesSchema, GetGroupVariableSchema, CreateGroupVariableSchema, UpdateGroupVariableSchema, DeleteGroupVariableSchema, GitLabDependencyProxySchema, GitLabDependencyProxyBlobSchema, GetDependencyProxySettingsSchema, UpdateDependencyProxySettingsSchema, ListDependencyProxyBlobsSchema, PurgeDependencyProxyCacheSchema, ListProjectVulnerabilitiesSchema, GetVulnerabilitySchema, DismissVulnerabilitySchema, ConfirmVulnerabilitySchema, ListIssueDiscussionsSchema, ListIssueLinksSchema, ListIssuesSchema, ListTodosSchema, ListMergeRequestDiffsSchema, // Added
|
|
150
150
|
GetMergeRequestFileDiffSchema, ListMergeRequestChangedFilesSchema, ListMergeRequestDiscussionsSchema, ListMergeRequestPipelinesSchema, ListMergeRequestsSchema, ListGroupMergeRequestsSchema, ListMergeRequestVersionsSchema, GetMergeRequestVersionSchema, GitLabMergeRequestVersionSchema, GitLabMergeRequestVersionDetailSchema, ListNamespacesSchema, ListPipelineJobsSchema, ListPipelinesSchema, ListDeploymentsSchema, ListEnvironmentsSchema, ListProjectRunnersSchema, GetRunnerSchema, ListPipelineTriggerJobsSchema, ValidateCiLintSchema, ValidateProjectCiLintSchema, ListCiCatalogResourcesSchema, GetCiCatalogResourceSchema, ListProjectMembersSchema, ListGroupMembersSchema, ListProjectsSchema, MarkdownUploadSchema, MarkdownUploadRemoteSchema, DownloadAttachmentSchema, DownloadJobArtifactsSchema, GetJobArtifactFileSchema, GitLabArtifactEntrySchema, ListJobArtifactsSchema, MergeMergeRequestSchema, ApproveMergeRequestSchema, UnapproveMergeRequestSchema, RebaseMergeRequestSchema, GetMergeRequestApprovalStateSchema, GetMergeRequestConflictsSchema, GitLabMergeRequestApprovalStateSchema, MyIssuesSchema, OrbitQuerySchema, OrbitSchemaSchema, OrbitStatusSchema, OrbitToolsSchema, MarkAllTodosDoneSchema, MarkTodoDoneSchema, PaginatedDiscussionsResponseSchema, PublishDraftNoteSchema, PlayPipelineJobSchema, PushFilesSchema, RetryPipelineJobSchema, RetryPipelineSchema, SearchCodeSchema, SearchGroupCodeSchema, SearchProjectCodeSchema, SearchRepositoriesSchema, UpdateDraftNoteSchema, UpdateIssueNoteSchema, UpdateIssueSchema, UpdateIssueDescriptionPatchSchema, ReorderIssueSchema, UpdateProjectSchema, UpdateMergeRequestNoteSchema, UpdateMergeRequestDiscussionNoteSchema, UpdateMergeRequestSchema, VerifyNamespaceSchema, GitLabEventSchema, ListEventsSchema, GetProjectEventsSchema, ExecuteGraphQLSchema, GitLabReleaseSchema, ListReleasesSchema, GetReleaseSchema, CreateReleaseSchema, UpdateReleaseSchema, DeleteReleaseSchema, CreateReleaseEvidenceSchema, DownloadReleaseAssetSchema, ListSnippetsSchema, GetSnippetSchema, CreateSnippetSchema, UpdateSnippetSchema, DeleteSnippetSchema, GitLabSnippetSchema, GetMergeRequestNotesSchema, GetMergeRequestNoteSchema, GetMergeRequestDiscussionSchema, DeleteMergeRequestDiscussionNoteSchema, ResolveMergeRequestThreadSchema, GetWorkItemSchema, ListWorkItemsSchema, CreateWorkItemSchema, UpdateWorkItemSchema, ConvertWorkItemTypeSchema, ListWorkItemStatusesSchema, ListWorkItemNotesSchema, CreateWorkItemNoteSchema, CreateWorkItemEmojiReactionSchema, CreateWorkItemNoteEmojiReactionSchema, ListWorkItemEmojiReactionsSchema, ListWorkItemNoteEmojiReactionsSchema, DeleteWorkItemEmojiReactionSchema, DeleteWorkItemNoteEmojiReactionSchema, MoveWorkItemSchema, ListCustomFieldDefinitionsSchema, GetTimelineEventsSchema, CreateTimelineEventSchema, ListWebhooksSchema, CreateWebhookSchema, UpdateWebhookSchema, DeleteWebhookSchema, ListWebhookEventsSchema, GetWebhookEventSchema, HealthCheckSchema, } from "./schemas.js";
|
|
151
151
|
import { createHash, randomUUID, timingSafeEqual } from "node:crypto";
|
|
152
|
+
import { createGraphQLAuditFailure, createToolCallAuditor, graphqlPayloadHasErrors, markToolResultAsAuditFailure, readKnownGitLabUserId, readKnownGitLabUsername, } from "./utils/audit-log.js";
|
|
152
153
|
import { createLogger, flushBufferedLogs, flushStartupLogs } from "./utils/logger.js";
|
|
153
154
|
const logger = createLogger();
|
|
154
155
|
function exitAfterFlush(code) {
|
|
@@ -240,7 +241,7 @@ function createServer() {
|
|
|
240
241
|
tools: getListedTools(filteredTools, listedToolsCache.revision),
|
|
241
242
|
};
|
|
242
243
|
});
|
|
243
|
-
mcpServer.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
244
|
+
mcpServer.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
244
245
|
// Manually retrieve the session context using the session ID passed in the request.
|
|
245
246
|
// This is a robust workaround for AsyncLocalStorage context loss.
|
|
246
247
|
const sessionId = request.params.sessionId;
|
|
@@ -248,6 +249,14 @@ function createServer() {
|
|
|
248
249
|
const start = Date.now();
|
|
249
250
|
let maskingEngine;
|
|
250
251
|
const requestArguments = readOwnRecord(request.params.arguments);
|
|
252
|
+
const auditor = createToolCallAuditor({
|
|
253
|
+
toolName,
|
|
254
|
+
sessionId: extra.sessionId ?? sessionId,
|
|
255
|
+
args: requestArguments,
|
|
256
|
+
startedAtMs: start,
|
|
257
|
+
gitlabUserId: readKnownGitLabUserId(extra.authInfo?.extra),
|
|
258
|
+
gitlabUsername: readKnownGitLabUsername(extra.authInfo?.extra),
|
|
259
|
+
});
|
|
251
260
|
const jmespathExpression = readJmespathExpression(requestArguments === undefined ? undefined : { ...requestArguments });
|
|
252
261
|
const listSummaryRequested = toolAcceptsDecoratedSummary(toolName) &&
|
|
253
262
|
readListSummaryRequested(requestArguments === undefined ? undefined : { ...requestArguments }, GITLAB_MCP_LIST_SUMMARY_DEFAULT && toolUsesListSummaryDefault(toolName, requestArguments));
|
|
@@ -268,7 +277,7 @@ function createServer() {
|
|
|
268
277
|
})
|
|
269
278
|
: filtered;
|
|
270
279
|
// Last exit for successful results: structuredContent is object-or-absent (#675).
|
|
271
|
-
|
|
280
|
+
const finalized = finalizeToolCallResult({
|
|
272
281
|
result: masked,
|
|
273
282
|
enabled: shouldCompactToolResult(toolName, GITLAB_MCP_COMPACT_RESULTS, GITLAB_MCP_COMPACT_TOOL_NAMES),
|
|
274
283
|
maxChars: GITLAB_MCP_COMPACT_RESULT_CHARS,
|
|
@@ -276,6 +285,8 @@ function createServer() {
|
|
|
276
285
|
args: readOwnRecord(request.params.arguments),
|
|
277
286
|
inputSchema: allTools.find(tool => tool.name === toolName)?.inputSchema,
|
|
278
287
|
});
|
|
288
|
+
auditor.recordResult(result);
|
|
289
|
+
return finalized;
|
|
279
290
|
};
|
|
280
291
|
const logError = (error) => {
|
|
281
292
|
const durationMs = Date.now() - start;
|
|
@@ -290,6 +301,7 @@ function createServer() {
|
|
|
290
301
|
error: safeError instanceof Error ? safeError.message : String(safeError),
|
|
291
302
|
}, `tool_call_error: ${toolName} (${durationMs}ms)`);
|
|
292
303
|
flushBufferedLogs(logger);
|
|
304
|
+
auditor.recordError(safeError);
|
|
293
305
|
return safeError;
|
|
294
306
|
};
|
|
295
307
|
try {
|
|
@@ -307,6 +319,7 @@ function createServer() {
|
|
|
307
319
|
allowedProjectIds: authData.allowedProjectIds,
|
|
308
320
|
}
|
|
309
321
|
: undefined;
|
|
322
|
+
auditor.setSessionHeader(sessionContext?.header ?? sessionAuthStore.getStore()?.header);
|
|
310
323
|
const selectMaskingPolicy = () => {
|
|
311
324
|
const isToolDiscovery = toolName === "discover_tools";
|
|
312
325
|
const inputSchema = allTools.find(tool => tool.name === toolName)?.inputSchema;
|
|
@@ -8000,14 +8013,18 @@ async function handleToolCall(params) {
|
|
|
8000
8013
|
await handleGitLabError(response);
|
|
8001
8014
|
}
|
|
8002
8015
|
const json = await response.json();
|
|
8003
|
-
|
|
8016
|
+
const graphqlResult = {
|
|
8004
8017
|
content: [{ type: "text", text: JSON.stringify(json) }],
|
|
8005
8018
|
};
|
|
8019
|
+
if (graphqlPayloadHasErrors(json)) {
|
|
8020
|
+
markToolResultAsAuditFailure(graphqlResult, createGraphQLAuditFailure());
|
|
8021
|
+
}
|
|
8022
|
+
return graphqlResult;
|
|
8006
8023
|
}
|
|
8007
8024
|
catch (err) {
|
|
8008
8025
|
// Returned as data, not isError, so the central error redaction does not see it.
|
|
8009
8026
|
const message = describeFetchTransportError(err) ?? redactUrlSecretsInErrorMessage(err);
|
|
8010
|
-
|
|
8027
|
+
const graphqlFailure = {
|
|
8011
8028
|
content: [
|
|
8012
8029
|
{
|
|
8013
8030
|
type: "text",
|
|
@@ -8015,6 +8032,8 @@ async function handleToolCall(params) {
|
|
|
8015
8032
|
},
|
|
8016
8033
|
],
|
|
8017
8034
|
};
|
|
8035
|
+
markToolResultAsAuditFailure(graphqlFailure, err);
|
|
8036
|
+
return graphqlFailure;
|
|
8018
8037
|
}
|
|
8019
8038
|
finally {
|
|
8020
8039
|
clearTimeout(timeout);
|
|
@@ -8068,7 +8087,7 @@ async function handleToolCall(params) {
|
|
|
8068
8087
|
const reason = describeFetchTransportError(forkError) ?? redactUrlSecretsInErrorMessage(forkError);
|
|
8069
8088
|
forkErrorMessage = `${forkErrorMessage}: ${reason}`;
|
|
8070
8089
|
}
|
|
8071
|
-
|
|
8090
|
+
const forkFailure = {
|
|
8072
8091
|
content: [
|
|
8073
8092
|
{
|
|
8074
8093
|
type: "text",
|
|
@@ -8076,6 +8095,8 @@ async function handleToolCall(params) {
|
|
|
8076
8095
|
},
|
|
8077
8096
|
],
|
|
8078
8097
|
};
|
|
8098
|
+
markToolResultAsAuditFailure(forkFailure, forkError);
|
|
8099
|
+
return forkFailure;
|
|
8079
8100
|
}
|
|
8080
8101
|
}
|
|
8081
8102
|
case "create_branch": {
|
|
@@ -0,0 +1,441 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in NDJSON audit log of MCP tool calls for SIEM ingestion.
|
|
3
|
+
*
|
|
4
|
+
* Disabled by default. When enabled, one JSON object is written per tool call
|
|
5
|
+
* using an allowlist of fields. Argument bodies, response bodies, tokens,
|
|
6
|
+
* headers, and free-text error messages are never copied into the record.
|
|
7
|
+
*
|
|
8
|
+
* This is a logging building block. Retention, access control, and any
|
|
9
|
+
* compliance mapping are the operator's responsibility.
|
|
10
|
+
*/
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import { GITLAB_AUDIT_LOG, GITLAB_AUDIT_LOG_FILE, GITLAB_AUTH_COOKIE_PATH, GITLAB_JOB_TOKEN, GITLAB_MCP_OAUTH, GITLAB_PERSONAL_ACCESS_TOKEN, REMOTE_AUTHORIZATION, USE_OAUTH, } from "../config.js";
|
|
13
|
+
import { TransportMode, determineTransportMode } from "../server/transport-mode.js";
|
|
14
|
+
import { createLogger } from "./logger.js";
|
|
15
|
+
export const AUDIT_EVENT_TYPE = "tool_call";
|
|
16
|
+
export const AUDIT_FIELD_ALLOWLIST = [
|
|
17
|
+
"timestamp",
|
|
18
|
+
"event",
|
|
19
|
+
"transport",
|
|
20
|
+
"sessionId",
|
|
21
|
+
"authMethod",
|
|
22
|
+
"gitlabUserId",
|
|
23
|
+
"gitlabUsername",
|
|
24
|
+
"tool",
|
|
25
|
+
"projectId",
|
|
26
|
+
"groupId",
|
|
27
|
+
"outcome",
|
|
28
|
+
"errorClass",
|
|
29
|
+
"httpStatus",
|
|
30
|
+
"durationMs",
|
|
31
|
+
];
|
|
32
|
+
const SAFE_ERROR_CLASS = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
|
|
33
|
+
const DEFAULT_ERROR_CLASS = "Error";
|
|
34
|
+
const TOOL_ERROR_CLASS = "ToolError";
|
|
35
|
+
export const GRAPHQL_AUDIT_ERROR_CLASS = "GraphQLError";
|
|
36
|
+
const STDOUT_PATHS = new Set(["/dev/stdout", "stdout", "1"]);
|
|
37
|
+
const markedAuditFailures = new WeakSet();
|
|
38
|
+
const markedAuditFailureErrors = new WeakMap();
|
|
39
|
+
let writeFailureWarned = false;
|
|
40
|
+
let stderrErrorListenerAttached = false;
|
|
41
|
+
let warningLogger;
|
|
42
|
+
export function resetAuditLogWriteWarningForTests() {
|
|
43
|
+
writeFailureWarned = false;
|
|
44
|
+
}
|
|
45
|
+
export function isAuditLogEnabled(enabled = GITLAB_AUDIT_LOG) {
|
|
46
|
+
return enabled === true;
|
|
47
|
+
}
|
|
48
|
+
export function extractAuditResourceIds(args) {
|
|
49
|
+
if (!isPlainRecord(args)) {
|
|
50
|
+
return {};
|
|
51
|
+
}
|
|
52
|
+
const projectId = readResourceId(ownProperty(args, "project_id"));
|
|
53
|
+
const groupId = readResourceId(ownProperty(args, "group_id"));
|
|
54
|
+
const ids = {};
|
|
55
|
+
if (projectId !== undefined) {
|
|
56
|
+
ids.projectId = projectId;
|
|
57
|
+
}
|
|
58
|
+
if (groupId !== undefined) {
|
|
59
|
+
ids.groupId = groupId;
|
|
60
|
+
}
|
|
61
|
+
return ids;
|
|
62
|
+
}
|
|
63
|
+
export function classifyAuditFailure(error) {
|
|
64
|
+
if (error === undefined) {
|
|
65
|
+
return { errorClass: TOOL_ERROR_CLASS };
|
|
66
|
+
}
|
|
67
|
+
const failure = {
|
|
68
|
+
errorClass: readErrorClass(error),
|
|
69
|
+
};
|
|
70
|
+
const httpStatus = readHttpStatus(error);
|
|
71
|
+
if (httpStatus !== undefined) {
|
|
72
|
+
failure.httpStatus = httpStatus;
|
|
73
|
+
}
|
|
74
|
+
return failure;
|
|
75
|
+
}
|
|
76
|
+
export function resolveAuditAuthMethod(input) {
|
|
77
|
+
if (input.sessionHeader !== undefined) {
|
|
78
|
+
switch (input.sessionHeader) {
|
|
79
|
+
case "JOB-TOKEN":
|
|
80
|
+
return "job-token";
|
|
81
|
+
case "Private-Token":
|
|
82
|
+
return "pat";
|
|
83
|
+
case "Authorization":
|
|
84
|
+
return input.mcpOAuth ? "oauth" : "remote-header";
|
|
85
|
+
default: {
|
|
86
|
+
const exhaustive = input.sessionHeader;
|
|
87
|
+
return exhaustive;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
if (input.mcpOAuth) {
|
|
92
|
+
return "oauth";
|
|
93
|
+
}
|
|
94
|
+
if (input.remoteAuthorization) {
|
|
95
|
+
return "remote-header";
|
|
96
|
+
}
|
|
97
|
+
if (input.useOAuth) {
|
|
98
|
+
return "oauth";
|
|
99
|
+
}
|
|
100
|
+
if (input.hasPat) {
|
|
101
|
+
return "pat";
|
|
102
|
+
}
|
|
103
|
+
if (input.hasJobToken) {
|
|
104
|
+
return "job-token";
|
|
105
|
+
}
|
|
106
|
+
if (input.hasCookie) {
|
|
107
|
+
return "cookie";
|
|
108
|
+
}
|
|
109
|
+
return undefined;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Mark a tools/call result that is returned as data (no `isError`) but is still
|
|
113
|
+
* a failure for audit purposes. The MCP payload is unchanged; only the auditor
|
|
114
|
+
* reads this mark. Do not put the error body on the mark.
|
|
115
|
+
*/
|
|
116
|
+
export function markToolResultAsAuditFailure(result, error) {
|
|
117
|
+
markedAuditFailures.add(result);
|
|
118
|
+
if (error !== undefined) {
|
|
119
|
+
markedAuditFailureErrors.set(result, error);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
export function graphqlPayloadHasErrors(payload) {
|
|
123
|
+
if (!isPlainRecord(payload)) {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
const errors = ownProperty(payload, "errors");
|
|
127
|
+
return Array.isArray(errors) && errors.length > 0;
|
|
128
|
+
}
|
|
129
|
+
export function createGraphQLAuditFailure() {
|
|
130
|
+
const error = new Error();
|
|
131
|
+
error.name = GRAPHQL_AUDIT_ERROR_CLASS;
|
|
132
|
+
return error;
|
|
133
|
+
}
|
|
134
|
+
function takeMarkedAuditFailure(result) {
|
|
135
|
+
if (typeof result !== "object" || result === null || !markedAuditFailures.has(result)) {
|
|
136
|
+
return { marked: false };
|
|
137
|
+
}
|
|
138
|
+
markedAuditFailures.delete(result);
|
|
139
|
+
const error = markedAuditFailureErrors.get(result);
|
|
140
|
+
markedAuditFailureErrors.delete(result);
|
|
141
|
+
return { marked: true, error };
|
|
142
|
+
}
|
|
143
|
+
export function sanitizeAuditSessionId(sessionId) {
|
|
144
|
+
if (typeof sessionId !== "string") {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
const trimmed = sessionId.trim();
|
|
148
|
+
if (trimmed.length === 0) {
|
|
149
|
+
return undefined;
|
|
150
|
+
}
|
|
151
|
+
// Sealed stateless sids are bearer tokens. Correlate without emitting ciphertext.
|
|
152
|
+
if (trimmed.startsWith("v1.sid.")) {
|
|
153
|
+
return "v1.sid.<redacted>";
|
|
154
|
+
}
|
|
155
|
+
return trimmed;
|
|
156
|
+
}
|
|
157
|
+
export function readKnownGitLabUserId(extra) {
|
|
158
|
+
if (!isPlainRecord(extra)) {
|
|
159
|
+
return undefined;
|
|
160
|
+
}
|
|
161
|
+
const value = ownProperty(extra, "resourceOwnerId");
|
|
162
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
|
|
163
|
+
return undefined;
|
|
164
|
+
}
|
|
165
|
+
return value;
|
|
166
|
+
}
|
|
167
|
+
export function readKnownGitLabUsername(extra) {
|
|
168
|
+
if (!isPlainRecord(extra)) {
|
|
169
|
+
return undefined;
|
|
170
|
+
}
|
|
171
|
+
const value = ownProperty(extra, "username");
|
|
172
|
+
if (typeof value !== "string") {
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
const trimmed = value.trim();
|
|
176
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
177
|
+
}
|
|
178
|
+
export function buildAuditRecord(fields) {
|
|
179
|
+
const record = {};
|
|
180
|
+
for (const field of AUDIT_FIELD_ALLOWLIST) {
|
|
181
|
+
const value = readAuditField(fields, field);
|
|
182
|
+
if (value !== undefined) {
|
|
183
|
+
record[field] = value;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return record;
|
|
187
|
+
}
|
|
188
|
+
export function recordToolCallAudit(input, deps = {}) {
|
|
189
|
+
if (!isAuditLogEnabled(deps.enabled ?? GITLAB_AUDIT_LOG)) {
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
try {
|
|
193
|
+
const now = deps.now ?? defaultNow;
|
|
194
|
+
const resources = extractAuditResourceIds(input.args);
|
|
195
|
+
const outcome = input.outcome;
|
|
196
|
+
const failure = outcome === "error" ? classifyAuditFailure(input.error) : undefined;
|
|
197
|
+
const fields = {
|
|
198
|
+
timestamp: now().toISOString(),
|
|
199
|
+
transport: auditTransport(determineTransportMode()),
|
|
200
|
+
sessionId: sanitizeAuditSessionId(input.sessionId),
|
|
201
|
+
authMethod: currentAuditAuthMethod(input.sessionHeader),
|
|
202
|
+
gitlabUserId: readPositiveInteger(input.gitlabUserId),
|
|
203
|
+
gitlabUsername: readOptionalName(input.gitlabUsername),
|
|
204
|
+
tool: readToolName(input.toolName),
|
|
205
|
+
projectId: resources.projectId,
|
|
206
|
+
groupId: resources.groupId,
|
|
207
|
+
outcome,
|
|
208
|
+
errorClass: failure?.errorClass,
|
|
209
|
+
httpStatus: failure?.httpStatus,
|
|
210
|
+
durationMs: readDurationMs(input.startedAtMs, now()),
|
|
211
|
+
};
|
|
212
|
+
const line = JSON.stringify(buildAuditRecord(fields));
|
|
213
|
+
const writeLine = deps.writeLine ?? defaultWriteLine(deps.filePath ?? GITLAB_AUDIT_LOG_FILE);
|
|
214
|
+
writeLine(line);
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
warnAuditWriteFailure(error, deps.warn);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
export function createToolCallAuditor(input, deps) {
|
|
221
|
+
const state = {
|
|
222
|
+
sessionHeader: undefined,
|
|
223
|
+
recorded: false,
|
|
224
|
+
};
|
|
225
|
+
function record(outcome, error) {
|
|
226
|
+
if (state.recorded) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
state.recorded = true;
|
|
230
|
+
recordToolCallAudit({
|
|
231
|
+
toolName: input.toolName,
|
|
232
|
+
sessionId: input.sessionId,
|
|
233
|
+
args: input.args,
|
|
234
|
+
sessionHeader: state.sessionHeader,
|
|
235
|
+
gitlabUserId: input.gitlabUserId,
|
|
236
|
+
gitlabUsername: input.gitlabUsername,
|
|
237
|
+
outcome,
|
|
238
|
+
error,
|
|
239
|
+
startedAtMs: input.startedAtMs,
|
|
240
|
+
}, deps);
|
|
241
|
+
}
|
|
242
|
+
return {
|
|
243
|
+
setSessionHeader(header) {
|
|
244
|
+
state.sessionHeader = header;
|
|
245
|
+
},
|
|
246
|
+
recordResult(result) {
|
|
247
|
+
const marked = takeMarkedAuditFailure(result);
|
|
248
|
+
if (marked.marked) {
|
|
249
|
+
record("error", marked.error);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (isErrorToolResult(result)) {
|
|
253
|
+
record("error");
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
record("success");
|
|
257
|
+
},
|
|
258
|
+
recordError(error) {
|
|
259
|
+
record("error", error);
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
function readAuditField(fields, field) {
|
|
264
|
+
switch (field) {
|
|
265
|
+
case "timestamp":
|
|
266
|
+
return fields.timestamp;
|
|
267
|
+
case "event":
|
|
268
|
+
return AUDIT_EVENT_TYPE;
|
|
269
|
+
case "transport":
|
|
270
|
+
return fields.transport;
|
|
271
|
+
case "sessionId":
|
|
272
|
+
return fields.sessionId;
|
|
273
|
+
case "authMethod":
|
|
274
|
+
return fields.authMethod;
|
|
275
|
+
case "gitlabUserId":
|
|
276
|
+
return fields.gitlabUserId;
|
|
277
|
+
case "gitlabUsername":
|
|
278
|
+
return fields.gitlabUsername;
|
|
279
|
+
case "tool":
|
|
280
|
+
return fields.tool;
|
|
281
|
+
case "projectId":
|
|
282
|
+
return fields.projectId;
|
|
283
|
+
case "groupId":
|
|
284
|
+
return fields.groupId;
|
|
285
|
+
case "outcome":
|
|
286
|
+
return fields.outcome;
|
|
287
|
+
case "errorClass":
|
|
288
|
+
return fields.errorClass;
|
|
289
|
+
case "httpStatus":
|
|
290
|
+
return fields.httpStatus;
|
|
291
|
+
case "durationMs":
|
|
292
|
+
return fields.durationMs;
|
|
293
|
+
default: {
|
|
294
|
+
const exhaustive = field;
|
|
295
|
+
return exhaustive;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
function auditTransport(mode) {
|
|
300
|
+
switch (mode) {
|
|
301
|
+
case TransportMode.STDIO:
|
|
302
|
+
return "stdio";
|
|
303
|
+
case TransportMode.SSE:
|
|
304
|
+
return "sse";
|
|
305
|
+
case TransportMode.STREAMABLE_HTTP:
|
|
306
|
+
return "streamable-http";
|
|
307
|
+
default: {
|
|
308
|
+
const exhaustive = mode;
|
|
309
|
+
return exhaustive;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
function currentAuditAuthMethod(sessionHeader) {
|
|
314
|
+
return resolveAuditAuthMethod({
|
|
315
|
+
remoteAuthorization: REMOTE_AUTHORIZATION,
|
|
316
|
+
mcpOAuth: GITLAB_MCP_OAUTH,
|
|
317
|
+
useOAuth: USE_OAUTH,
|
|
318
|
+
hasPat: Boolean(GITLAB_PERSONAL_ACCESS_TOKEN),
|
|
319
|
+
hasJobToken: Boolean(GITLAB_JOB_TOKEN),
|
|
320
|
+
hasCookie: Boolean(GITLAB_AUTH_COOKIE_PATH),
|
|
321
|
+
sessionHeader,
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
function defaultNow() {
|
|
325
|
+
return new Date();
|
|
326
|
+
}
|
|
327
|
+
function defaultWriteLine(filePath) {
|
|
328
|
+
return function writeAuditLine(line) {
|
|
329
|
+
const payload = `${line}\n`;
|
|
330
|
+
if (!filePath) {
|
|
331
|
+
writeAuditStderr(payload);
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const trimmed = filePath.trim();
|
|
335
|
+
if (trimmed.length === 0) {
|
|
336
|
+
writeAuditStderr(payload);
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (isStdoutPath(trimmed)) {
|
|
340
|
+
throw new Error("GITLAB_AUDIT_LOG_FILE must not target stdout");
|
|
341
|
+
}
|
|
342
|
+
fs.appendFileSync(trimmed, payload);
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
function writeAuditStderr(payload) {
|
|
346
|
+
if (!stderrErrorListenerAttached) {
|
|
347
|
+
stderrErrorListenerAttached = true;
|
|
348
|
+
process.stderr.on("error", error => {
|
|
349
|
+
warnAuditWriteFailure(error);
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
process.stderr.write(payload);
|
|
353
|
+
}
|
|
354
|
+
function warnAuditWriteFailure(error, warn) {
|
|
355
|
+
if (writeFailureWarned) {
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
writeFailureWarned = true;
|
|
359
|
+
if (warn) {
|
|
360
|
+
warn(error);
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
if (warningLogger === undefined) {
|
|
364
|
+
warningLogger = createLogger("audit-log");
|
|
365
|
+
}
|
|
366
|
+
warningLogger.warn({ err: error }, "Failed to write tool-call audit log; further write failures will be silent");
|
|
367
|
+
}
|
|
368
|
+
function isStdoutPath(filePath) {
|
|
369
|
+
return STDOUT_PATHS.has(filePath) || STDOUT_PATHS.has(filePath.toLowerCase());
|
|
370
|
+
}
|
|
371
|
+
function isPlainRecord(value) {
|
|
372
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
373
|
+
}
|
|
374
|
+
function ownProperty(record, key) {
|
|
375
|
+
if (!Object.prototype.hasOwnProperty.call(record, key)) {
|
|
376
|
+
return undefined;
|
|
377
|
+
}
|
|
378
|
+
return Reflect.get(record, key);
|
|
379
|
+
}
|
|
380
|
+
function readResourceId(value) {
|
|
381
|
+
if (typeof value === "string") {
|
|
382
|
+
const trimmed = value.trim();
|
|
383
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
384
|
+
}
|
|
385
|
+
if (typeof value === "number" && Number.isFinite(value)) {
|
|
386
|
+
return String(value);
|
|
387
|
+
}
|
|
388
|
+
return undefined;
|
|
389
|
+
}
|
|
390
|
+
function readErrorClass(error) {
|
|
391
|
+
if (error instanceof Error && SAFE_ERROR_CLASS.test(error.name)) {
|
|
392
|
+
return error.name;
|
|
393
|
+
}
|
|
394
|
+
return DEFAULT_ERROR_CLASS;
|
|
395
|
+
}
|
|
396
|
+
function readHttpStatus(error) {
|
|
397
|
+
if (!isPlainRecord(error) && !(error instanceof Error)) {
|
|
398
|
+
return undefined;
|
|
399
|
+
}
|
|
400
|
+
if (!("status" in error)) {
|
|
401
|
+
return undefined;
|
|
402
|
+
}
|
|
403
|
+
const status = Reflect.get(error, "status");
|
|
404
|
+
if (typeof status !== "number" || !Number.isInteger(status) || status < 100 || status > 599) {
|
|
405
|
+
return undefined;
|
|
406
|
+
}
|
|
407
|
+
return status;
|
|
408
|
+
}
|
|
409
|
+
function readToolName(toolName) {
|
|
410
|
+
if (typeof toolName !== "string") {
|
|
411
|
+
return "unknown";
|
|
412
|
+
}
|
|
413
|
+
const trimmed = toolName.trim();
|
|
414
|
+
return trimmed.length > 0 ? trimmed : "unknown";
|
|
415
|
+
}
|
|
416
|
+
function readPositiveInteger(value) {
|
|
417
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {
|
|
418
|
+
return undefined;
|
|
419
|
+
}
|
|
420
|
+
return value;
|
|
421
|
+
}
|
|
422
|
+
function readOptionalName(value) {
|
|
423
|
+
if (typeof value !== "string") {
|
|
424
|
+
return undefined;
|
|
425
|
+
}
|
|
426
|
+
const trimmed = value.trim();
|
|
427
|
+
return trimmed.length > 0 ? trimmed : undefined;
|
|
428
|
+
}
|
|
429
|
+
function readDurationMs(startedAtMs, now) {
|
|
430
|
+
const durationMs = now.getTime() - startedAtMs;
|
|
431
|
+
if (!Number.isFinite(durationMs) || durationMs < 0) {
|
|
432
|
+
return 0;
|
|
433
|
+
}
|
|
434
|
+
return Math.round(durationMs);
|
|
435
|
+
}
|
|
436
|
+
function isErrorToolResult(result) {
|
|
437
|
+
if (!isPlainRecord(result)) {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
return ownProperty(result, "isError") === true;
|
|
441
|
+
}
|
package/package.json
CHANGED