Compare commits

...

28 Commits

Author SHA1 Message Date
62f0ffff69 chore: bump version to 1.0.63 2025-06-12 21:25:16 +09:00
aed6046022 Merge pull request #97 from huerlisi/feat/paginate-job-logs
feat: add pagination support for CI job logs to prevent context window flooding
2025-06-12 21:20:25 +09:00
2905f30af7 feat: add pagination support for CI job logs to prevent context window flooding
- Add optional `limit` and `offset` parameters to get_pipeline_job_output
- Default limit is 1000 lines when pagination is used
- Returns lines from the end of the log, with configurable offset
- Includes truncation metadata showing what was skipped
- Maintains backward compatibility (no parameters = full log)

This prevents large CI logs from overwhelming AI tooling context windows
while still providing access to the most recent and relevant log output.
2025-06-11 10:48:14 +02:00
3c23675eec [version-update] fix: correct Private-Token header authentication for GitLab API 🔐
🚀 Breaking Changes:
- Removed incorrect `Bearer ` prefix from Private-Token header in legacy authentication mode
- Fixed authentication issues for older GitLab instances with private tokens

📝 Details:
- Ensures proper API authentication for both new and legacy GitLab configurations
2025-06-10 09:51:54 +09:00
8df87c67d2 [version-update] feat: bump version to 1.0.62 🎉
🚀 Breaking Changes:
- Updated version from 1.0.61 to 1.0.62
2025-06-10 09:49:22 +09:00
d318f9ea5e FIX: private token auth (#91)
issue: #88
2025-06-10 09:48:57 +09:00
ed032bad48 feat: bump version to 1.0.61 🎉
🚀 Breaking Changes:
- Updated version number in package.json
2025-06-09 14:22:51 +09:00
5200cc526c FEAT: private token auth (#89)
* FEAT: private token auth

issue: #88

* FIX
2025-06-09 14:21:52 +09:00
1ba54342bc style: format code for consistency and readability
🚀 Breaking Changes:
- None

📝 Details:
- Adjusted import statements for consistency
- Reformatted code for better readability
- Removed unnecessary console.error statements
2025-06-07 10:20:21 +09:00
29659db0b7 [version-update] feat: bump version to 1.0.60 🎉
🚀 Breaking Changes:
- Updated merge request functionality with new options
- Improved handling of assignee usernames in issue listings

📝 Details:
- Added support for `remove_source_branch` and `squash` options for merge requests
- Fixed issue with assignee username handling in issue listing
- Generated RELEASE_NOTES.md from CHANGELOG.md
2025-06-07 09:20:19 +09:00
44d8d11b4a FIX: list issues assginee username (#87) 2025-06-07 08:20:20 +09:00
622c112f7f FEAT: add support for remove_source_branch and squash options for merge requests (#86) 2025-06-07 08:20:07 +09:00
0930ce3636 [version-update] feat: bump version to 1.0.59 🎉
🚀 Breaking Changes:
- Updated package version from 1.0.58 to 1.0.59
2025-06-04 21:37:59 +09:00
061e19d861 Fix for null error (#85)
Co-authored-by: Jean Paul Gatt <jeanpaul.gatt@ballys.com>
2025-06-04 21:37:28 +09:00
511d2d9c06 FIX: bug get issues (#83) 2025-06-04 21:37:14 +09:00
8cb7703aa1 [feat] update: bump version to 1.0.58
🚀 Breaking Changes:
- Updated package version from 1.0.57 to 1.0.58
2025-06-03 19:34:00 +09:00
5e254836e8 Add support for retrieving wiki page content in list_wiki_pages (#82)
Co-authored-by: Vince Liao <vince.liao@nextbank.com.tw>
2025-06-03 19:33:36 +09:00
93710f2846 Merge pull request #81 from zereight/doc/readme
DOC: readme docker image
2025-06-03 14:58:18 +09:00
f3854126ac DOC: readme docker image 2025-06-03 14:40:34 +09:00
c07356bd46 [feat] update: bump version to 1.0.57
🚀 Breaking Changes:
- Updated package version from 1.0.56 to 1.0.57
2025-06-03 14:33:54 +09:00
c82be8c94f Add pagination to merge request discussions, similar to issue discussions (#80) 2025-06-03 14:33:17 +09:00
cd8f0e5525 fix: merge_requests_template can be null (#79) 2025-06-03 14:33:05 +09:00
547b05c88d [feat] update: bump version to 1.0.56
🚀 Breaking Changes:
- Updated package version in package.json and package-lock.json
2025-06-02 21:36:42 +09:00
ed0b3915aa Merge pull request #78 from zereight/feat/issues_api
FIX: issue param
2025-06-02 21:35:45 +09:00
0bcccd95ca Merge pull request #77 from zereight/fix/issue_labels
FIX: get issues labels
2025-06-02 21:35:37 +09:00
0b5453b3fd Merge pull request #76 from zereight/feat/sse
FEAT: MCP SSE
2025-06-02 21:35:26 +09:00
300961f051 FIX: issue param
https://docs.gitlab.com/api/issues/#:~:text=Return%20issues%20for%20the%20given%20scope%3A%20created_by_me%2C%20assigned_to_me%20or%20all.%20Defaults%20to%20created_by_me
2025-06-02 20:48:12 +09:00
2a9b8f1a25 FIX: get issues labels
issue: #

 ### 機能・変更内容(ユーザー観点)

 ### 影響範囲・追加でテストしてほしい内容

 ### tech側でテストした内容
2025-06-02 20:03:54 +09:00
8 changed files with 539 additions and 186 deletions

View File

@ -1,8 +1,40 @@
## [1.0.62] - 2025-06-10
### Fixed
- 🔐 **Private Token Authentication Fix**: Fixed Private-Token header authentication for GitLab API
- Removed incorrect `Bearer ` prefix from Private-Token header in legacy authentication mode
- Fixed authentication issues when using older GitLab instances with private tokens
- Ensures proper API authentication for both new and legacy GitLab configurations
- See: [PR #91](https://github.com/zereight/gitlab-mcp/pull/91), [Issue #88](https://github.com/zereight/gitlab-mcp/issues/88)
---
## [1.0.60] - 2025-06-07
### Added
- 📄 **Merge Request Enhancement**: Added support for `remove_source_branch` and `squash` options for merge requests
- Enhanced merge request functionality with additional configuration options
- Allows automatic source branch removal after merge
- Supports squash commits for cleaner Git history
- See: [PR #86](https://github.com/zereight/gitlab-mcp/pull/86)
### Fixed
- 🔧 **Issue Assignment Fix**: Fixed list issues assignee username handling
- Corrected assignee username field in issue listing functionality
- Improved user assignment data processing for GitLab issues
- See: [PR #87](https://github.com/zereight/gitlab-mcp/pull/87), [Issue #74](https://github.com/zereight/gitlab-mcp/issues/74)
---
## [1.0.54] - 2025-05-31 ## [1.0.54] - 2025-05-31
### Added ### Added
- 🌐 **Multi-Platform Support**: Added support for multiple platforms to improve compatibility across different environments - 🌐 **Multi-Platform Support**: Added support for multiple platforms to improve compatibility across different environments
- Enhanced platform detection and configuration handling - Enhanced platform detection and configuration handling
- Improved cross-platform functionality for GitLab MCP server - Improved cross-platform functionality for GitLab MCP server
- See: [PR #71](https://github.com/zereight/gitlab-mcp/pull/71), [Issue #69](https://github.com/zereight/gitlab-mcp/issues/69) - See: [PR #71](https://github.com/zereight/gitlab-mcp/pull/71), [Issue #69](https://github.com/zereight/gitlab-mcp/issues/69)

View File

@ -84,7 +84,7 @@ docker run -i --rm \
-e USE_PIPELINE=true \ -e USE_PIPELINE=true \
-e SSE=true \ -e SSE=true \
-p 3333:3002 \ -p 3333:3002 \
gitlab-mcp iwakitakuma/gitlab-mcp
``` ```
```json ```json

11
RELEASE_NOTES.md Normal file
View File

@ -0,0 +1,11 @@
## [1.0.62] - 2025-06-10
### Fixed
- 🔐 **Private Token Authentication Fix**: Fixed Private-Token header authentication for GitLab API
- Removed incorrect `Bearer ` prefix from Private-Token header in legacy authentication mode
- Fixed authentication issues when using older GitLab instances with private tokens
- Ensures proper API authentication for both new and legacy GitLab configurations
- See: [PR #91](https://github.com/zereight/gitlab-mcp/pull/91), [Issue #88](https://github.com/zereight/gitlab-mcp/issues/88)
---

264
index.ts
View File

@ -17,7 +17,7 @@ import path from "path";
import express, { Request, Response } from "express"; import express, { Request, Response } from "express";
// Add type imports for proxy agents // Add type imports for proxy agents
import { Agent } from "http"; import { Agent } from "http";
import { Agent as HttpsAgent } from 'https'; import { Agent as HttpsAgent } from "https";
import { URL } from "url"; import { URL } from "url";
import { import {
@ -100,6 +100,7 @@ import {
// Discussion Schemas // Discussion Schemas
GitLabDiscussionNoteSchema, // Added GitLabDiscussionNoteSchema, // Added
GitLabDiscussionSchema, GitLabDiscussionSchema,
PaginatedDiscussionsResponseSchema,
UpdateMergeRequestNoteSchema, // Added UpdateMergeRequestNoteSchema, // Added
CreateMergeRequestNoteSchema, // Added CreateMergeRequestNoteSchema, // Added
ListMergeRequestDiscussionsSchema, ListMergeRequestDiscussionsSchema,
@ -142,8 +143,10 @@ import {
type PromoteProjectMilestoneOptions, type PromoteProjectMilestoneOptions,
type GetMilestoneBurndownEventsOptions, type GetMilestoneBurndownEventsOptions,
// Discussion Types // Discussion Types
type GitLabDiscussionNote, // Added type GitLabDiscussionNote,
type GitLabDiscussion, type GitLabDiscussion,
type PaginatedDiscussionsResponse,
type PaginationOptions,
type MergeRequestThreadPosition, type MergeRequestThreadPosition,
type GetWikiPageOptions, type GetWikiPageOptions,
type CreateWikiPageOptions, type CreateWikiPageOptions,
@ -168,6 +171,7 @@ import {
GitLabCompareResult, GitLabCompareResult,
GitLabCompareResultSchema, GitLabCompareResultSchema,
GetBranchDiffsSchema, GetBranchDiffsSchema,
ListWikiPagesOptions,
} from "./schemas.js"; } from "./schemas.js";
/** /**
@ -183,7 +187,7 @@ try {
SERVER_VERSION = packageJson.version || SERVER_VERSION; SERVER_VERSION = packageJson.version || SERVER_VERSION;
} }
} catch (error) { } catch (error) {
console.error("Warning: Could not read version from package.json:", error); // Warning: Could not read version from package.json - silently continue
} }
const server = new Server( const server = new Server(
@ -199,6 +203,7 @@ const server = new Server(
); );
const GITLAB_PERSONAL_ACCESS_TOKEN = process.env.GITLAB_PERSONAL_ACCESS_TOKEN; const GITLAB_PERSONAL_ACCESS_TOKEN = process.env.GITLAB_PERSONAL_ACCESS_TOKEN;
const IS_OLD = process.env.GITLAB_IS_OLD === "true";
const GITLAB_READ_ONLY_MODE = process.env.GITLAB_READ_ONLY_MODE === "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_GITLAB_WIKI = process.env.USE_GITLAB_WIKI === "true";
const USE_MILESTONE = process.env.USE_MILESTONE === "true"; const USE_MILESTONE = process.env.USE_MILESTONE === "true";
@ -211,8 +216,8 @@ const HTTPS_PROXY = process.env.HTTPS_PROXY;
const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED; const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
const GITLAB_CA_CERT_PATH = process.env.GITLAB_CA_CERT_PATH; const GITLAB_CA_CERT_PATH = process.env.GITLAB_CA_CERT_PATH;
let sslOptions= undefined; let sslOptions = undefined;
if (NODE_TLS_REJECT_UNAUTHORIZED === '0') { if (NODE_TLS_REJECT_UNAUTHORIZED === "0") {
sslOptions = { rejectUnauthorized: false }; sslOptions = { rejectUnauthorized: false };
} else if (GITLAB_CA_CERT_PATH) { } else if (GITLAB_CA_CERT_PATH) {
const ca = fs.readFileSync(GITLAB_CA_CERT_PATH); const ca = fs.readFileSync(GITLAB_CA_CERT_PATH);
@ -241,11 +246,15 @@ httpsAgent = httpsAgent || new HttpsAgent(sslOptions);
httpAgent = httpAgent || new Agent(); httpAgent = httpAgent || new Agent();
// Modify DEFAULT_HEADERS to include agent configuration // Modify DEFAULT_HEADERS to include agent configuration
const DEFAULT_HEADERS = { const DEFAULT_HEADERS: Record<string, string> = {
Accept: "application/json", Accept: "application/json",
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${GITLAB_PERSONAL_ACCESS_TOKEN}`,
}; };
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 // Create a default fetch configuration object that includes proxy agents if set
const DEFAULT_FETCH_CONFIG = { const DEFAULT_FETCH_CONFIG = {
@ -319,8 +328,7 @@ const allTools = [
}, },
{ {
name: "get_branch_diffs", name: "get_branch_diffs",
description: description: "Get the changes/diffs between two branches or commits in a GitLab project",
"Get the changes/diffs between two branches or commits in a GitLab project",
inputSchema: zodToJsonSchema(GetBranchDiffsSchema), inputSchema: zodToJsonSchema(GetBranchDiffsSchema),
}, },
{ {
@ -515,7 +523,7 @@ const allTools = [
}, },
{ {
name: "get_pipeline_job_output", name: "get_pipeline_job_output",
description: "Get the output/trace of a GitLab pipeline job number", description: "Get the output/trace of a GitLab pipeline job with optional pagination to limit context window usage",
inputSchema: zodToJsonSchema(GetPipelineJobOutputSchema), inputSchema: zodToJsonSchema(GetPipelineJobOutputSchema),
}, },
{ {
@ -903,9 +911,16 @@ async function listIssues(
// Add all query parameters // Add all query parameters
Object.entries(options).forEach(([key, value]) => { Object.entries(options).forEach(([key, value]) => {
if (value !== undefined) { if (value !== undefined) {
if (key === "label_name" && Array.isArray(value)) { const keys = ["labels", "assignee_username"];
if (keys.includes(key)) {
if (Array.isArray(value)) {
// Handle array of labels // Handle array of labels
url.searchParams.append(key, value.join(",")); value.forEach(label => {
url.searchParams.append(`${key}[]`, label.toString());
});
} else {
url.searchParams.append(`${key}[]`, value.toString());
}
} else { } else {
url.searchParams.append(key, value.toString()); url.searchParams.append(key, value.toString());
} }
@ -1189,6 +1204,8 @@ async function createMergeRequest(
labels: options.labels?.join(","), labels: options.labels?.join(","),
allow_collaboration: options.allow_collaboration, allow_collaboration: options.allow_collaboration,
draft: options.draft, draft: options.draft,
remove_source_branch: options.remove_source_branch,
squash: options.squash,
}), }),
}); });
@ -1207,55 +1224,26 @@ async function createMergeRequest(
} }
/** /**
* List merge request discussion items * Shared helper function for listing discussions
* 병합 요청 토론 목록 조회 * 토론 목록 조회를 위한 공유 헬퍼 함수
* *
* @param {string} projectId - The ID or URL-encoded path of the project * @param {string} projectId - The ID or URL-encoded path of the project
* @param {number} mergeRequestIid - The IID of a merge request * @param {"issues" | "merge_requests"} resourceType - The type of resource (issues or merge_requests)
* @returns {Promise<GitLabDiscussion[]>} List of discussions * @param {number} resourceIid - The IID of the issue or merge request
* @param {PaginationOptions} options - Pagination and sorting options
* @returns {Promise<PaginatedDiscussionsResponse>} Paginated list of discussions
*/ */
async function listMergeRequestDiscussions( async function listDiscussions(
projectId: string, projectId: string,
mergeRequestIid: number resourceType: "issues" | "merge_requests",
): Promise<GitLabDiscussion[]> { resourceIid: number,
options: PaginationOptions = {}
): Promise<PaginatedDiscussionsResponse> {
projectId = decodeURIComponent(projectId); // Decode project ID projectId = decodeURIComponent(projectId); // Decode project ID
const url = new URL( const url = new URL(
`${GITLAB_API_URL}/projects/${encodeURIComponent( `${GITLAB_API_URL}/projects/${encodeURIComponent(
projectId projectId
)}/merge_requests/${mergeRequestIid}/discussions` )}/${resourceType}/${resourceIid}/discussions`
);
const response = await fetch(url.toString(), {
...DEFAULT_FETCH_CONFIG,
});
await handleGitLabError(response);
const data = await response.json();
// Ensure the response is parsed as an array of discussions
return z.array(GitLabDiscussionSchema).parse(data);
}
/**
* List discussions for an issue
*
* @param {string} projectId - The ID or URL-encoded path of the project
* @param {number} issueIid - The internal ID of the project issue
* @param {Object} options - Pagination and sorting options
* @returns {Promise<GitLabDiscussion[]>} List of issue discussions
*/
async function listIssueDiscussions(
projectId: string,
issueIid: number,
options: {
page?: number;
per_page?: number;
sort?: "asc" | "desc";
order_by?: "created_at" | "updated_at";
} = {}
): Promise<GitLabDiscussion[]> {
projectId = decodeURIComponent(projectId); // Decode project ID
const url = new URL(
`${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/issues/${issueIid}/discussions`
); );
// Add query parameters for pagination and sorting // Add query parameters for pagination and sorting
@ -1265,22 +1253,69 @@ async function listIssueDiscussions(
if (options.per_page) { if (options.per_page) {
url.searchParams.append("per_page", options.per_page.toString()); url.searchParams.append("per_page", options.per_page.toString());
} }
if (options.sort) {
url.searchParams.append("sort", options.sort);
}
if (options.order_by) {
url.searchParams.append("order_by", options.order_by);
}
const response = await fetch(url.toString(), { const response = await fetch(url.toString(), {
...DEFAULT_FETCH_CONFIG, ...DEFAULT_FETCH_CONFIG,
}); });
await handleGitLabError(response); await handleGitLabError(response);
const data = await response.json(); const discussions = await response.json();
// Parse the response as an array of discussions // Extract pagination headers
return z.array(GitLabDiscussionSchema).parse(data); const pagination = {
x_next_page: response.headers.get("x-next-page")
? parseInt(response.headers.get("x-next-page")!)
: null,
x_page: response.headers.get("x-page") ? parseInt(response.headers.get("x-page")!) : undefined,
x_per_page: response.headers.get("x-per-page")
? parseInt(response.headers.get("x-per-page")!)
: undefined,
x_prev_page: response.headers.get("x-prev-page")
? parseInt(response.headers.get("x-prev-page")!)
: null,
x_total: response.headers.get("x-total") ? parseInt(response.headers.get("x-total")!) : null,
x_total_pages: response.headers.get("x-total-pages")
? parseInt(response.headers.get("x-total-pages")!)
: null,
};
return PaginatedDiscussionsResponseSchema.parse({
items: discussions,
pagination: pagination,
});
}
/**
* List merge request discussion items
* 병합 요청 토론 목록 조회
*
* @param {string} projectId - The ID or URL-encoded path of the project
* @param {number} mergeRequestIid - The IID of a merge request
* @param {DiscussionPaginationOptions} options - Pagination and sorting options
* @returns {Promise<GitLabDiscussion[]>} List of discussions
*/
async function listMergeRequestDiscussions(
projectId: string,
mergeRequestIid: number,
options: PaginationOptions = {}
): Promise<PaginatedDiscussionsResponse> {
return listDiscussions(projectId, "merge_requests", mergeRequestIid, options);
}
/**
* List discussions for an issue
*
* @param {string} projectId - The ID or URL-encoded path of the project
* @param {number} issueIid - The internal ID of the project issue
* @param {DiscussionPaginationOptions} options - Pagination and sorting options
* @returns {Promise<GitLabDiscussion[]>} List of issue discussions
*/
async function listIssueDiscussions(
projectId: string,
issueIid: number,
options: PaginationOptions = {}
): Promise<PaginatedDiscussionsResponse> {
return listDiscussions(projectId, "issues", issueIid, options);
} }
/** /**
@ -1836,9 +1871,7 @@ async function getBranchDiffs(
if (!response.ok) { if (!response.ok) {
const errorBody = await response.text(); const errorBody = await response.text();
throw new Error( throw new Error(`GitLab API error: ${response.status} ${response.statusText}\n${errorBody}`);
`GitLab API error: ${response.status} ${response.statusText}\n${errorBody}`
);
} }
const data = await response.json(); const data = await response.json();
@ -2361,12 +2394,14 @@ async function listGroupProjects(
*/ */
async function listWikiPages( async function listWikiPages(
projectId: string, projectId: string,
options: Omit<z.infer<typeof ListWikiPagesSchema>, "project_id"> = {} options: Omit<ListWikiPagesOptions, "project_id"> = {}
): Promise<GitLabWikiPage[]> { ): Promise<GitLabWikiPage[]> {
projectId = decodeURIComponent(projectId); // Decode project ID projectId = decodeURIComponent(projectId); // Decode project ID
const url = new URL(`${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/wikis`); const url = new URL(`${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/wikis`);
if (options.page) url.searchParams.append("page", options.page.toString()); if (options.page) url.searchParams.append("page", options.page.toString());
if (options.per_page) url.searchParams.append("per_page", options.per_page.toString()); if (options.per_page) url.searchParams.append("per_page", options.per_page.toString());
if (options.with_content)
url.searchParams.append("with_content", options.with_content.toString());
const response = await fetch(url.toString(), { const response = await fetch(url.toString(), {
...DEFAULT_FETCH_CONFIG, ...DEFAULT_FETCH_CONFIG,
}); });
@ -2576,9 +2611,11 @@ async function getPipelineJob(projectId: string, jobId: number): Promise<GitLabP
* *
* @param {string} projectId - The ID or URL-encoded path of the project * @param {string} projectId - The ID or URL-encoded path of the project
* @param {number} jobId - The ID of the job * @param {number} jobId - The ID of the job
* @param {number} limit - Maximum number of lines to return from the end (default: 1000)
* @param {number} offset - Number of lines to skip from the end (default: 0)
* @returns {Promise<string>} The job output/trace * @returns {Promise<string>} The job output/trace
*/ */
async function getPipelineJobOutput(projectId: string, jobId: number): Promise<string> { async function getPipelineJobOutput(projectId: string, jobId: number, limit?: number, offset?: number): Promise<string> {
projectId = decodeURIComponent(projectId); // Decode project ID projectId = decodeURIComponent(projectId); // Decode project ID
const url = new URL( const url = new URL(
`${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace` `${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace`
@ -2597,7 +2634,35 @@ async function getPipelineJobOutput(projectId: string, jobId: number): Promise<s
} }
await handleGitLabError(response); await handleGitLabError(response);
return await response.text(); const fullTrace = await response.text();
// Apply client-side pagination to limit context window usage
if (limit !== undefined || offset !== undefined) {
const lines = fullTrace.split('\n');
const startOffset = offset || 0;
const maxLines = limit || 1000;
// Return lines from the end, skipping offset lines and limiting to maxLines
const startIndex = Math.max(0, lines.length - startOffset - maxLines);
const endIndex = lines.length - startOffset;
const selectedLines = lines.slice(startIndex, endIndex);
const result = selectedLines.join('\n');
// Add metadata about truncation
if (startIndex > 0 || endIndex < lines.length) {
const totalLines = lines.length;
const shownLines = selectedLines.length;
const skippedFromStart = startIndex;
const skippedFromEnd = startOffset;
return `[Log truncated: showing ${shownLines} of ${totalLines} lines, skipped ${skippedFromStart} from start, ${skippedFromEnd} from end]\n\n${result}`;
}
return result;
}
return fullTrace;
} }
/** /**
@ -2618,10 +2683,13 @@ async function createPipeline(
const body: any = { ref }; const body: any = { ref };
if (variables && variables.length > 0) { if (variables && variables.length > 0) {
body.variables = variables.reduce((acc, { key, value }) => { body.variables = variables.reduce(
(acc, { key, value }) => {
acc[key] = value; acc[key] = value;
return acc; return acc;
}, {} as Record<string, string>); },
{} as Record<string, string>
);
} }
const response = await fetch(url.toString(), { const response = await fetch(url.toString(), {
@ -2697,15 +2765,20 @@ async function getRepositoryTree(options: GetRepositoryTreeOptions): Promise<Git
if (options.page_token) queryParams.append("page_token", options.page_token); if (options.page_token) queryParams.append("page_token", options.page_token);
if (options.pagination) queryParams.append("pagination", options.pagination); if (options.pagination) queryParams.append("pagination", options.pagination);
const headers: Record<string, string> = {
"Content-Type": "application/json",
};
if (IS_OLD) {
headers["Private-Token"] = `${GITLAB_PERSONAL_ACCESS_TOKEN}`;
} else {
headers["Authorization"] = `Bearer ${GITLAB_PERSONAL_ACCESS_TOKEN}`;
}
const response = await fetch( const response = await fetch(
`${GITLAB_API_URL}/projects/${encodeURIComponent( `${GITLAB_API_URL}/projects/${encodeURIComponent(
options.project_id options.project_id
)}/repository/tree?${queryParams.toString()}`, )}/repository/tree?${queryParams.toString()}`,
{ {
headers: { headers,
Authorization: `Bearer ${GITLAB_PERSONAL_ACCESS_TOKEN}`,
"Content-Type": "application/json",
},
} }
); );
@ -3010,9 +3083,7 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
? tools1 ? tools1
: tools1.filter(tool => !milestoneToolNames.includes(tool.name)); : tools1.filter(tool => !milestoneToolNames.includes(tool.name));
// Toggle pipeline tools by USE_PIPELINE flag // Toggle pipeline tools by USE_PIPELINE flag
let tools = USE_PIPELINE let tools = USE_PIPELINE ? tools2 : tools2.filter(tool => !pipelineToolNames.includes(tool.name));
? tools2
: tools2.filter(tool => !pipelineToolNames.includes(tool.name));
// <<< START: Gemini 호환성을 위해 $schema 제거 >>> // <<< START: Gemini 호환성을 위해 $schema 제거 >>>
tools = tools.map(tool => { tools = tools.map(tool => {
@ -3086,12 +3157,7 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
case "get_branch_diffs": { case "get_branch_diffs": {
const args = GetBranchDiffsSchema.parse(request.params.arguments); const args = GetBranchDiffsSchema.parse(request.params.arguments);
const diffResp = await getBranchDiffs( const diffResp = await getBranchDiffs(args.project_id, args.from, args.to, args.straight);
args.project_id,
args.from,
args.to,
args.straight
);
if (args.excluded_file_patterns?.length) { if (args.excluded_file_patterns?.length) {
const regexPatterns = args.excluded_file_patterns.map(pattern => new RegExp(pattern)); const regexPatterns = args.excluded_file_patterns.map(pattern => new RegExp(pattern));
@ -3103,9 +3169,7 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
}; };
// Filter out files that match any of the regex patterns on new files // Filter out files that match any of the regex patterns on new files
diffResp.diffs = diffResp.diffs.filter(diff => diffResp.diffs = diffResp.diffs.filter(diff => !matchesAnyPattern(diff.new_path));
!matchesAnyPattern(diff.new_path)
);
} }
return { return {
content: [{ type: "text", text: JSON.stringify(diffResp, null, 2) }], content: [{ type: "text", text: JSON.stringify(diffResp, null, 2) }],
@ -3282,9 +3346,11 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
case "mr_discussions": { case "mr_discussions": {
const args = ListMergeRequestDiscussionsSchema.parse(request.params.arguments); const args = ListMergeRequestDiscussionsSchema.parse(request.params.arguments);
const { project_id, merge_request_iid, ...options } = args;
const discussions = await listMergeRequestDiscussions( const discussions = await listMergeRequestDiscussions(
args.project_id, project_id,
args.merge_request_iid merge_request_iid,
options
); );
return { return {
content: [{ type: "text", text: JSON.stringify(discussions, null, 2) }], content: [{ type: "text", text: JSON.stringify(discussions, null, 2) }],
@ -3580,8 +3646,10 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
} }
case "list_wiki_pages": { case "list_wiki_pages": {
const { project_id, page, per_page } = ListWikiPagesSchema.parse(request.params.arguments); const { project_id, page, per_page, with_content } = ListWikiPagesSchema.parse(
const wikiPages = await listWikiPages(project_id, { page, per_page }); request.params.arguments
);
const wikiPages = await listWikiPages(project_id, { page, per_page, with_content });
return { return {
content: [{ type: "text", text: JSON.stringify(wikiPages, null, 2) }], content: [{ type: "text", text: JSON.stringify(wikiPages, null, 2) }],
}; };
@ -3694,8 +3762,8 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
} }
case "get_pipeline_job_output": { case "get_pipeline_job_output": {
const { project_id, job_id } = GetPipelineJobOutputSchema.parse(request.params.arguments); const { project_id, job_id, limit, offset } = GetPipelineJobOutputSchema.parse(request.params.arguments);
const jobOutput = await getPipelineJobOutput(project_id, job_id); const jobOutput = await getPipelineJobOutput(project_id, job_id, limit, offset);
return { return {
content: [ content: [
{ {
@ -3916,12 +3984,11 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
*/ */
async function runServer() { async function runServer() {
try { try {
console.error("========================"); // Server startup banner removed - inappropriate use of console.error for logging
console.error(`GitLab MCP Server v${SERVER_VERSION}`); // Server version banner removed - inappropriate use of console.error for logging
console.error(`API URL: ${GITLAB_API_URL}`); // API URL banner removed - inappropriate use of console.error for logging
console.error("========================"); // Server startup banner removed - inappropriate use of console.error for logging
if ( !SSE ) if (!SSE) {
{
const transport = new StdioServerTransport(); const transport = new StdioServerTransport();
await server.connect(transport); await server.connect(transport);
} else { } else {
@ -3951,7 +4018,6 @@ async function runServer() {
console.log(`Server is running on port ${PORT}`); console.log(`Server is running on port ${PORT}`);
}); });
} }
console.error("GitLab MCP Server running on stdio");
} catch (error) { } catch (error) {
console.error("Error initializing server:", error); console.error("Error initializing server:", error);
process.exit(1); process.exit(1);

201
package-lock.json generated
View File

@ -1,12 +1,12 @@
{ {
"name": "@zereight/mcp-gitlab", "name": "@zereight/mcp-gitlab",
"version": "1.0.55", "version": "1.0.60",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@zereight/mcp-gitlab", "name": "@zereight/mcp-gitlab",
"version": "1.0.55", "version": "1.0.60",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "1.8.0", "@modelcontextprotocol/sdk": "1.8.0",
@ -27,6 +27,7 @@
"@types/node": "^22.13.10", "@types/node": "^22.13.10",
"@typescript-eslint/eslint-plugin": "^8.21.0", "@typescript-eslint/eslint-plugin": "^8.21.0",
"@typescript-eslint/parser": "^8.21.0", "@typescript-eslint/parser": "^8.21.0",
"auto-changelog": "^2.4.0",
"eslint": "^9.18.0", "eslint": "^9.18.0",
"prettier": "^3.4.2", "prettier": "^3.4.2",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
@ -889,6 +890,48 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/auto-changelog": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/auto-changelog/-/auto-changelog-2.5.0.tgz",
"integrity": "sha512-UTnLjT7I9U2U/xkCUH5buDlp8C7g0SGChfib+iDrJkamcj5kaMqNKHNfbKJw1kthJUq8sUo3i3q2S6FzO/l/wA==",
"dev": true,
"license": "MIT",
"dependencies": {
"commander": "^7.2.0",
"handlebars": "^4.7.7",
"import-cwd": "^3.0.0",
"node-fetch": "^2.6.1",
"parse-github-url": "^1.0.3",
"semver": "^7.3.5"
},
"bin": {
"auto-changelog": "src/index.js"
},
"engines": {
"node": ">=8.3"
}
},
"node_modules/auto-changelog/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"dev": true,
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/balanced-match": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@ -1036,6 +1079,16 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
"integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 10"
}
},
"node_modules/concat-map": { "node_modules/concat-map": {
"version": "0.0.1", "version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@ -1894,6 +1947,28 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/handlebars": {
"version": "4.7.8",
"resolved": "https://registry.npmjs.org/handlebars/-/handlebars-4.7.8.tgz",
"integrity": "sha512-vafaFqs8MZkRrSX7sFVUdo3ap/eNiLnb4IakshzvP56X5Nr1iGKAIqdX6tMlm6HcNRIkr6AxO5jFEoJzzpT8aQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"minimist": "^1.2.5",
"neo-async": "^2.6.2",
"source-map": "^0.6.1",
"wordwrap": "^1.0.0"
},
"bin": {
"handlebars": "bin/handlebars"
},
"engines": {
"node": ">=0.4.7"
},
"optionalDependencies": {
"uglify-js": "^3.1.4"
}
},
"node_modules/has-flag": { "node_modules/has-flag": {
"version": "4.0.0", "version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@ -2007,6 +2082,19 @@
"node": ">= 4" "node": ">= 4"
} }
}, },
"node_modules/import-cwd": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/import-cwd/-/import-cwd-3.0.0.tgz",
"integrity": "sha512-4pnzH16plW+hgvRECbDWpQl3cqtvSofHWh44met7ESfZ8UZOWWddm8hEyDTqREJ9RbYHY8gi8DqmaelApoOGMg==",
"dev": true,
"license": "MIT",
"dependencies": {
"import-from": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/import-fresh": { "node_modules/import-fresh": {
"version": "3.3.1", "version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@ -2024,6 +2112,29 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/import-from": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/import-from/-/import-from-3.0.0.tgz",
"integrity": "sha512-CiuXOFFSzkU5x/CR0+z7T91Iht4CXgfCxVOFRhh2Zyhg5wOpWvvDLQUsWl+gcN+QscYBjez8hDCt85O7RLDttQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"resolve-from": "^5.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/import-from/node_modules/resolve-from": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz",
"integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/imurmurhash": { "node_modules/imurmurhash": {
"version": "0.1.4", "version": "0.1.4",
"resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz",
@ -2292,6 +2403,16 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@ -2314,6 +2435,13 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/neo-async": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz",
"integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==",
"dev": true,
"license": "MIT"
},
"node_modules/node-domexception": { "node_modules/node-domexception": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz",
@ -2456,6 +2584,19 @@
"node": ">=6" "node": ">=6"
} }
}, },
"node_modules/parse-github-url": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/parse-github-url/-/parse-github-url-1.0.3.tgz",
"integrity": "sha512-tfalY5/4SqGaV/GIGzWyHnFjlpTPTNpENR9Ea2lLldSJ8EWXMsvacWucqY3m3I4YPtas15IxTLQVQ5NSYXPrww==",
"dev": true,
"license": "MIT",
"bin": {
"parse-github-url": "cli.js"
},
"engines": {
"node": ">= 0.10"
}
},
"node_modules/parseurl": { "node_modules/parseurl": {
"version": "1.3.3", "version": "1.3.3",
"resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
@ -2898,6 +3039,16 @@
"node": ">= 14" "node": ">= 14"
} }
}, },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/sprintf-js": { "node_modules/sprintf-js": {
"version": "1.1.3", "version": "1.1.3",
"resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz",
@ -2961,6 +3112,13 @@
"node": ">=0.6" "node": ">=0.6"
} }
}, },
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"dev": true,
"license": "MIT"
},
"node_modules/ts-api-utils": { "node_modules/ts-api-utils": {
"version": "2.1.0", "version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
@ -3059,6 +3217,20 @@
"node": ">=14.17" "node": ">=14.17"
} }
}, },
"node_modules/uglify-js": {
"version": "3.19.3",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.19.3.tgz",
"integrity": "sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ==",
"dev": true,
"license": "BSD-2-Clause",
"optional": true,
"bin": {
"uglifyjs": "bin/uglifyjs"
},
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "6.20.0", "version": "6.20.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.20.0.tgz",
@ -3109,6 +3281,24 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"dev": true,
"license": "BSD-2-Clause"
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/which": { "node_modules/which": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@ -3134,6 +3324,13 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/wordwrap": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz",
"integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==",
"dev": true,
"license": "MIT"
},
"node_modules/wrappy": { "node_modules/wrappy": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",

View File

@ -1,6 +1,6 @@
{ {
"name": "@zereight/mcp-gitlab", "name": "@zereight/mcp-gitlab",
"version": "1.0.55", "version": "1.0.63",
"description": "MCP server for using the GitLab API", "description": "MCP server for using the GitLab API",
"license": "MIT", "license": "MIT",
"author": "zereight", "author": "zereight",
@ -21,6 +21,7 @@
"watch": "tsc --watch", "watch": "tsc --watch",
"deploy": "npm publish --access public", "deploy": "npm publish --access public",
"generate-tools": "npx ts-node scripts/generate-tools-readme.ts", "generate-tools": "npx ts-node scripts/generate-tools-readme.ts",
"changelog": "auto-changelog -p",
"test": "node test/validate-api.js", "test": "node test/validate-api.js",
"test:integration": "node test/validate-api.js", "test:integration": "node test/validate-api.js",
"lint": "eslint . --ext .ts", "lint": "eslint . --ext .ts",
@ -48,6 +49,7 @@
"prettier": "^3.4.2", "prettier": "^3.4.2",
"ts-node": "^10.9.2", "ts-node": "^10.9.2",
"typescript": "^5.8.2", "typescript": "^5.8.2",
"zod": "^3.24.2" "zod": "^3.24.2",
"auto-changelog": "^2.4.0"
} }
} }

View File

@ -94,6 +94,13 @@ export const GitLabPipelineJobSchema = z.object({
web_url: z.string().optional(), web_url: z.string().optional(),
}); });
// Shared base schema for various pagination options
// See https://docs.gitlab.com/api/rest/#pagination
export const PaginationOptionsSchema = z.object({
page: z.number().optional().describe("Page number for pagination (default: 1)"),
per_page: z.number().optional().describe("Number of items per page (max: 100, default: 20)"),
});
// Schema for listing pipelines // Schema for listing pipelines
export const ListPipelinesSchema = z.object({ export const ListPipelinesSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
@ -134,9 +141,7 @@ export const ListPipelinesSchema = z.object({
.optional() .optional()
.describe("Order pipelines by"), .describe("Order pipelines by"),
sort: z.enum(["asc", "desc"]).optional().describe("Sort pipelines"), sort: z.enum(["asc", "desc"]).optional().describe("Sort pipelines"),
page: z.number().optional().describe("Page number for pagination"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of items per page (max 100)"),
});
// Schema for getting a specific pipeline // Schema for getting a specific pipeline
export const GetPipelineSchema = z.object({ export const GetPipelineSchema = z.object({
@ -153,9 +158,7 @@ export const ListPipelineJobsSchema = z.object({
.optional() .optional()
.describe("The scope of jobs to show"), .describe("The scope of jobs to show"),
include_retried: z.boolean().optional().describe("Whether to include retried jobs"), include_retried: z.boolean().optional().describe("Whether to include retried jobs"),
page: z.number().optional().describe("Page number for pagination"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of items per page (max 100)"),
});
// Schema for creating a new pipeline // Schema for creating a new pipeline
export const CreatePipelineSchema = z.object({ export const CreatePipelineSchema = z.object({
@ -188,6 +191,8 @@ export const CancelPipelineSchema = z.object({
export const GetPipelineJobOutputSchema = z.object({ export const GetPipelineJobOutputSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
job_id: z.number().describe("The ID of the job"), job_id: z.number().describe("The ID of the job"),
limit: z.number().optional().describe("Maximum number of lines to return from the end of the log (default: 1000)"),
offset: z.number().optional().describe("Number of lines to skip from the end of the log (default: 0)"),
}); });
// User schemas // User schemas
@ -209,7 +214,7 @@ export const GitLabUsersResponseSchema = z.record(
id: z.number(), id: z.number(),
username: z.string(), username: z.string(),
name: z.string(), name: z.string(),
avatar_url: z.string(), avatar_url: z.string().nullable(),
web_url: z.string(), web_url: z.string(),
}).nullable() }).nullable()
); );
@ -250,7 +255,7 @@ export const GitLabNamespaceExistsResponseSchema = z.object({
export const GitLabOwnerSchema = z.object({ export const GitLabOwnerSchema = z.object({
username: z.string(), // Changed from login to match GitLab API username: z.string(), // Changed from login to match GitLab API
id: z.number(), id: z.number(),
avatar_url: z.string(), avatar_url: z.string().nullable(),
web_url: z.string(), // Changed from html_url to match GitLab API web_url: z.string(), // Changed from html_url to match GitLab API
name: z.string(), // Added as GitLab includes full name name: z.string(), // Added as GitLab includes full name
state: z.string(), // Added as GitLab includes user state state: z.string(), // Added as GitLab includes user state
@ -310,7 +315,7 @@ export const GitLabRepositorySchema = z.object({
container_registry_access_level: z.string().optional(), container_registry_access_level: z.string().optional(),
issues_enabled: z.boolean().optional(), issues_enabled: z.boolean().optional(),
merge_requests_enabled: z.boolean().optional(), merge_requests_enabled: z.boolean().optional(),
merge_requests_template: z.string().optional(), merge_requests_template: z.string().nullable().optional(),
wiki_enabled: z.boolean().optional(), wiki_enabled: z.boolean().optional(),
jobs_enabled: z.boolean().optional(), jobs_enabled: z.boolean().optional(),
snippets_enabled: z.boolean().optional(), snippets_enabled: z.boolean().optional(),
@ -464,6 +469,8 @@ export const CreateMergeRequestOptionsSchema = z.object({
labels: z.array(z.string()).optional(), labels: z.array(z.string()).optional(),
allow_collaboration: z.boolean().optional(), // Changed from maintainer_can_modify to match GitLab API allow_collaboration: z.boolean().optional(), // Changed from maintainer_can_modify to match GitLab API
draft: z.boolean().optional(), draft: z.boolean().optional(),
remove_source_branch: z.boolean().optional().describe("Flag indicating if a merge request should remove the source branch when merging."),
squash: z.boolean().optional().describe("If true, squash all commits into a single commit on merge.")
}); });
export const GitLabDiffSchema = z.object({ export const GitLabDiffSchema = z.object({
@ -590,7 +597,7 @@ export const GitLabForkParentSchema = z.object({
.object({ .object({
username: z.string(), // Changed from login to match GitLab API username: z.string(), // Changed from login to match GitLab API
id: z.number(), id: z.number(),
avatar_url: z.string(), avatar_url: z.string().nullable(),
}) })
.optional(), // Made optional to handle cases where GitLab API doesn't include it .optional(), // Made optional to handle cases where GitLab API doesn't include it
web_url: z.string(), // Changed from html_url to match GitLab API web_url: z.string(), // Changed from html_url to match GitLab API
@ -698,6 +705,24 @@ export const GitLabDiscussionNoteSchema = z.object({
}); });
export type GitLabDiscussionNote = z.infer<typeof GitLabDiscussionNoteSchema>; export type GitLabDiscussionNote = z.infer<typeof GitLabDiscussionNoteSchema>;
// Reusable pagination schema for GitLab API responses.
// See https://docs.gitlab.com/api/rest/#pagination
export const GitLabPaginationSchema = z.object({
x_next_page: z.number().nullable().optional(),
x_page: z.number().optional(),
x_per_page: z.number().optional(),
x_prev_page: z.number().nullable().optional(),
x_total: z.number().nullable().optional(),
x_total_pages: z.number().nullable().optional(),
});
export type GitLabPagination = z.infer<typeof GitLabPaginationSchema>;
// Base paginated response schema that can be extended.
// See https://docs.gitlab.com/api/rest/#pagination
export const PaginatedResponseSchema = z.object({
pagination: GitLabPaginationSchema.optional(),
});
export const GitLabDiscussionSchema = z.object({ export const GitLabDiscussionSchema = z.object({
id: z.string(), id: z.string(),
individual_note: z.boolean(), individual_note: z.boolean(),
@ -705,10 +730,24 @@ export const GitLabDiscussionSchema = z.object({
}); });
export type GitLabDiscussion = z.infer<typeof GitLabDiscussionSchema>; export type GitLabDiscussion = z.infer<typeof GitLabDiscussionSchema>;
// Create a schema for paginated discussions response
export const PaginatedDiscussionsResponseSchema = z.object({
items: z.array(GitLabDiscussionSchema),
pagination: GitLabPaginationSchema,
});
// Export the paginated response type for discussions
export type PaginatedDiscussionsResponse = z.infer<typeof PaginatedDiscussionsResponseSchema>;
export const ListIssueDiscussionsSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"),
issue_iid: z.number().describe("The internal ID of the project issue"),
}).merge(PaginationOptionsSchema);
// Input schema for listing merge request discussions // Input schema for listing merge request discussions
export const ListMergeRequestDiscussionsSchema = ProjectParamsSchema.extend({ export const ListMergeRequestDiscussionsSchema = ProjectParamsSchema.extend({
merge_request_iid: z.number().describe("The IID of a merge request"), merge_request_iid: z.number().describe("The IID of a merge request"),
}); }).merge(PaginationOptionsSchema);
// Input schema for updating a merge request discussion note // Input schema for updating a merge request discussion note
export const UpdateMergeRequestNoteSchema = ProjectParamsSchema.extend({ export const UpdateMergeRequestNoteSchema = ProjectParamsSchema.extend({
@ -763,9 +802,7 @@ export const CreateOrUpdateFileSchema = ProjectParamsSchema.extend({
export const SearchRepositoriesSchema = z.object({ export const SearchRepositoriesSchema = z.object({
search: z.string().describe("Search query"), // Changed from query to match GitLab API search: z.string().describe("Search query"), // Changed from query to match GitLab API
page: z.number().optional().describe("Page number for pagination (default: 1)"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of results per page (default: 20)"),
});
export const CreateRepositorySchema = z.object({ export const CreateRepositorySchema = z.object({
name: z.string().describe("Repository name"), name: z.string().describe("Repository name"),
@ -883,17 +920,17 @@ export const CreateNoteSchema = z.object({
export const ListIssuesSchema = z.object({ export const ListIssuesSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
assignee_id: z.number().optional().describe("Return issues assigned to the given user ID"), assignee_id: z.number().optional().describe("Return issues assigned to the given user ID"),
assignee_username: z.string().optional().describe("Return issues assigned to the given username"), assignee_username: z.array(z.string()).optional().describe("Return issues assigned to the given username"),
author_id: z.number().optional().describe("Return issues created by the given user ID"), author_id: z.number().optional().describe("Return issues created by the given user ID"),
author_username: z.string().optional().describe("Return issues created by the given username"), author_username: z.string().optional().describe("Return issues created by the given username"),
confidential: z.boolean().optional().describe("Filter confidential or public issues"), confidential: z.boolean().optional().describe("Filter confidential or public issues"),
created_after: z.string().optional().describe("Return issues created after the given time"), created_after: z.string().optional().describe("Return issues created after the given time"),
created_before: z.string().optional().describe("Return issues created before the given time"), created_before: z.string().optional().describe("Return issues created before the given time"),
due_date: z.string().optional().describe("Return issues that have the due date"), due_date: z.string().optional().describe("Return issues that have the due date"),
label_name: z.array(z.string()).optional().describe("Array of label names"), labels: z.array(z.string()).optional().describe("Array of label names"),
milestone: z.string().optional().describe("Milestone title"), milestone: z.string().optional().describe("Milestone title"),
scope: z scope: z
.enum(["created-by-me", "assigned-to-me", "all"]) .enum(["created_by_me", "assigned_to_me", "all"])
.optional() .optional()
.describe("Return issues from a specific scope"), .describe("Return issues from a specific scope"),
search: z.string().optional().describe("Search for specific terms"), search: z.string().optional().describe("Search for specific terms"),
@ -904,9 +941,7 @@ export const ListIssuesSchema = z.object({
updated_after: z.string().optional().describe("Return issues updated after the given time"), updated_after: z.string().optional().describe("Return issues updated after the given time"),
updated_before: z.string().optional().describe("Return issues updated before the given time"), updated_before: z.string().optional().describe("Return issues updated before the given time"),
with_labels_details: z.boolean().optional().describe("Return more details for each label"), with_labels_details: z.boolean().optional().describe("Return more details for each label"),
page: z.number().optional().describe("Page number for pagination"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of items per page"),
});
// Merge Requests API operation schemas // Merge Requests API operation schemas
export const ListMergeRequestsSchema = z.object({ export const ListMergeRequestsSchema = z.object({
@ -977,9 +1012,7 @@ export const ListMergeRequestsSchema = z.object({
.describe("Return merge requests from a specific source branch"), .describe("Return merge requests from a specific source branch"),
wip: z.enum(["yes", "no"]).optional().describe("Filter merge requests against their wip status"), wip: z.enum(["yes", "no"]).optional().describe("Filter merge requests against their wip status"),
with_labels_details: z.boolean().optional().describe("Return more details for each label"), with_labels_details: z.boolean().optional().describe("Return more details for each label"),
page: z.number().optional().describe("Page number for pagination"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of items per page"),
});
export const GetIssueSchema = z.object({ export const GetIssueSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
@ -1018,21 +1051,6 @@ export const ListIssueLinksSchema = z.object({
issue_iid: z.number().describe("The internal ID of a project's issue"), issue_iid: z.number().describe("The internal ID of a project's issue"),
}); });
export const ListIssueDiscussionsSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"),
issue_iid: z.number().describe("The internal ID of the project issue"),
page: z.number().optional().describe("Page number for pagination"),
per_page: z.number().optional().describe("Number of items per page"),
sort: z
.enum(["asc", "desc"])
.optional()
.describe("Return issue discussions sorted in ascending or descending order"),
order_by: z
.enum(["created_at", "updated_at"])
.optional()
.describe("Return issue discussions ordered by created_at or updated_at fields"),
});
export const GetIssueLinkSchema = z.object({ export const GetIssueLinkSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
issue_iid: z.number().describe("The internal ID of a project's issue"), issue_iid: z.number().describe("The internal ID of a project's issue"),
@ -1059,10 +1077,8 @@ export const DeleteIssueLinkSchema = z.object({
// Namespace API operation schemas // Namespace API operation schemas
export const ListNamespacesSchema = z.object({ export const ListNamespacesSchema = z.object({
search: z.string().optional().describe("Search term for namespaces"), search: z.string().optional().describe("Search term for namespaces"),
page: z.number().optional().describe("Page number for pagination"),
per_page: z.number().optional().describe("Number of items per page"),
owned: z.boolean().optional().describe("Filter for namespaces owned by current user"), owned: z.boolean().optional().describe("Filter for namespaces owned by current user"),
}); }).merge(PaginationOptionsSchema);
export const GetNamespaceSchema = z.object({ export const GetNamespaceSchema = z.object({
namespace_id: z.string().describe("Namespace ID or full path"), namespace_id: z.string().describe("Namespace ID or full path"),
@ -1079,8 +1095,6 @@ export const GetProjectSchema = z.object({
export const ListProjectsSchema = z.object({ export const ListProjectsSchema = z.object({
search: z.string().optional().describe("Search term for projects"), search: z.string().optional().describe("Search term for projects"),
page: z.number().optional().describe("Page number for pagination"),
per_page: z.number().optional().describe("Number of items per page"),
search_namespaces: z.boolean().optional().describe("Needs to be true if search is full path"), search_namespaces: z.boolean().optional().describe("Needs to be true if search is full path"),
owned: z.boolean().optional().describe("Filter for projects owned by current user"), owned: z.boolean().optional().describe("Filter for projects owned by current user"),
membership: z.boolean().optional().describe("Filter for projects where current user is a member"), membership: z.boolean().optional().describe("Filter for projects where current user is a member"),
@ -1107,7 +1121,7 @@ export const ListProjectsSchema = z.object({
.optional() .optional()
.describe("Filter projects with merge requests feature enabled"), .describe("Filter projects with merge requests feature enabled"),
min_access_level: z.number().optional().describe("Filter by minimum access level"), min_access_level: z.number().optional().describe("Filter by minimum access level"),
}); }).merge(PaginationOptionsSchema);
// Label operation schemas // Label operation schemas
export const ListLabelsSchema = z.object({ export const ListLabelsSchema = z.object({
@ -1163,8 +1177,6 @@ export const ListGroupProjectsSchema = z.object({
.optional() .optional()
.describe("Field to sort by"), .describe("Field to sort by"),
sort: z.enum(["asc", "desc"]).optional().describe("Sort direction"), sort: z.enum(["asc", "desc"]).optional().describe("Sort direction"),
page: z.number().optional().describe("Page number"),
per_page: z.number().optional().describe("Number of results per page"),
archived: z.boolean().optional().describe("Filter for archived projects"), archived: z.boolean().optional().describe("Filter for archived projects"),
visibility: z visibility: z
.enum(["public", "internal", "private"]) .enum(["public", "internal", "private"])
@ -1184,14 +1196,14 @@ export const ListGroupProjectsSchema = z.object({
statistics: z.boolean().optional().describe("Include project statistics"), statistics: z.boolean().optional().describe("Include project statistics"),
with_custom_attributes: z.boolean().optional().describe("Include custom attributes"), with_custom_attributes: z.boolean().optional().describe("Include custom attributes"),
with_security_reports: z.boolean().optional().describe("Include security reports"), with_security_reports: z.boolean().optional().describe("Include security reports"),
}); }).merge(PaginationOptionsSchema);
// Add wiki operation schemas // Add wiki operation schemas
export const ListWikiPagesSchema = z.object({ export const ListWikiPagesSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
page: z.number().optional().describe("Page number for pagination"), with_content: z.boolean().optional().describe("Include content of the wiki pages"),
per_page: z.number().optional().describe("Number of items per page"), }).merge(PaginationOptionsSchema);
});
export const GetWikiPageSchema = z.object({ export const GetWikiPageSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
slug: z.string().describe("URL-encoded slug of the wiki page"), slug: z.string().describe("URL-encoded slug of the wiki page"),
@ -1209,6 +1221,7 @@ export const UpdateWikiPageSchema = z.object({
content: z.string().optional().describe("New content of the wiki page"), content: z.string().optional().describe("New content of the wiki page"),
format: z.string().optional().describe("Content format, e.g., markdown, rdoc"), format: z.string().optional().describe("Content format, e.g., markdown, rdoc"),
}); });
export const DeleteWikiPageSchema = z.object({ export const DeleteWikiPageSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"), project_id: z.string().describe("Project ID or URL-encoded path"),
slug: z.string().describe("URL-encoded slug of the wiki page"), slug: z.string().describe("URL-encoded slug of the wiki page"),
@ -1219,7 +1232,7 @@ export const GitLabWikiPageSchema = z.object({
title: z.string(), title: z.string(),
slug: z.string(), slug: z.string(),
format: z.string(), format: z.string(),
content: z.string(), content: z.string().optional(),
created_at: z.string().optional(), created_at: z.string().optional(),
updated_at: z.string().optional(), updated_at: z.string().optional(),
}); });
@ -1275,9 +1288,7 @@ export const ListProjectMilestonesSchema = ProjectParamsSchema.extend({
.string() .string()
.optional() .optional()
.describe("Return milestones updated after the specified date (ISO 8601 format)"), .describe("Return milestones updated after the specified date (ISO 8601 format)"),
page: z.number().optional().describe("Page number for pagination"), }).merge(PaginationOptionsSchema);
per_page: z.number().optional().describe("Number of items per page (max 100)"),
});
// Schema for getting a single milestone // Schema for getting a single milestone
export const GetProjectMilestoneSchema = ProjectParamsSchema.extend({ export const GetProjectMilestoneSchema = ProjectParamsSchema.extend({
@ -1311,19 +1322,13 @@ export const DeleteProjectMilestoneSchema = GetProjectMilestoneSchema;
export const GetMilestoneIssuesSchema = GetProjectMilestoneSchema; export const GetMilestoneIssuesSchema = GetProjectMilestoneSchema;
// Schema for getting merge requests assigned to a milestone // Schema for getting merge requests assigned to a milestone
export const GetMilestoneMergeRequestsSchema = GetProjectMilestoneSchema.extend({ export const GetMilestoneMergeRequestsSchema = GetProjectMilestoneSchema.merge(PaginationOptionsSchema);
page: z.number().optional().describe("Page number for pagination"),
per_page: z.number().optional().describe("Number of items per page (max 100)"),
});
// Schema for promoting a project milestone to a group milestone // Schema for promoting a project milestone to a group milestone
export const PromoteProjectMilestoneSchema = GetProjectMilestoneSchema; export const PromoteProjectMilestoneSchema = GetProjectMilestoneSchema;
// Schema for getting burndown chart events for a milestone // Schema for getting burndown chart events for a milestone
export const GetMilestoneBurndownEventsSchema = GetProjectMilestoneSchema.extend({ export const GetMilestoneBurndownEventsSchema = GetProjectMilestoneSchema.merge(PaginationOptionsSchema);
page: z.number().optional().describe("Page number for pagination"),
per_page: z.number().optional().describe("Number of items per page (max 100)"),
});
// Export types // Export types
export type GitLabAuthor = z.infer<typeof GitLabAuthorSchema>; export type GitLabAuthor = z.infer<typeof GitLabAuthorSchema>;
@ -1352,6 +1357,7 @@ export type GitLabMergeRequestDiff = z.infer<
export type CreateNoteOptions = z.infer<typeof CreateNoteSchema>; export type CreateNoteOptions = z.infer<typeof CreateNoteSchema>;
export type GitLabIssueLink = z.infer<typeof GitLabIssueLinkSchema>; export type GitLabIssueLink = z.infer<typeof GitLabIssueLinkSchema>;
export type ListIssueDiscussionsOptions = z.infer<typeof ListIssueDiscussionsSchema>; export type ListIssueDiscussionsOptions = z.infer<typeof ListIssueDiscussionsSchema>;
export type ListMergeRequestDiscussionsOptions = z.infer<typeof ListMergeRequestDiscussionsSchema>;
export type UpdateIssueNoteOptions = z.infer<typeof UpdateIssueNoteSchema>; export type UpdateIssueNoteOptions = z.infer<typeof UpdateIssueNoteSchema>;
export type CreateIssueNoteOptions = z.infer<typeof CreateIssueNoteSchema>; export type CreateIssueNoteOptions = z.infer<typeof CreateIssueNoteSchema>;
export type GitLabNamespace = z.infer<typeof GitLabNamespaceSchema>; export type GitLabNamespace = z.infer<typeof GitLabNamespaceSchema>;
@ -1389,3 +1395,4 @@ export type PromoteProjectMilestoneOptions = z.infer<typeof PromoteProjectMilest
export type GetMilestoneBurndownEventsOptions = z.infer<typeof GetMilestoneBurndownEventsSchema>; export type GetMilestoneBurndownEventsOptions = z.infer<typeof GetMilestoneBurndownEventsSchema>;
export type GitLabUser = z.infer<typeof GitLabUserSchema>; export type GitLabUser = z.infer<typeof GitLabUserSchema>;
export type GitLabUsersResponse = z.infer<typeof GitLabUsersResponseSchema>; export type GitLabUsersResponse = z.infer<typeof GitLabUsersResponseSchema>;
export type PaginationOptions = z.infer<typeof PaginationOptionsSchema>;

View File

@ -0,0 +1,38 @@
#!/bin/bash
set -e
# Extract version from package.json
VERSION=$(jq -r .version package.json)
if [ -z "$VERSION" ]; then
echo "Could not read version from package.json."
exit 1
fi
# Check if release notes file exists
if [ ! -f RELEASE_NOTES.md ]; then
echo "RELEASE_NOTES.md file does not exist."
exit 1
fi
# Generate RELEASE_NOTES.md from CHANGELOG.md for the current version
node <<'EOF'
const fs = require('fs');
const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const version = pkg.version;
const regex = new RegExp(`## \\[${version.replace(/\./g, '\\.')}\\][\\s\\S]*?(?=\\n## |\\n?$)`, 'g');
const match = changelog.match(regex);
if (match && match[0]) {
fs.writeFileSync('RELEASE_NOTES.md', match[0].trim() + '\n');
console.log('RELEASE_NOTES.md generated for version', version);
} else {
console.error('No changelog entry found for version', version);
process.exit(1);
}
EOF
# Create GitHub release using CLI
gh release create "$VERSION" -t "Release $VERSION" -F RELEASE_NOTES.md