Compare commits

...

18 Commits

Author SHA1 Message Date
402f068470 feat: add cookie-based authentication support for enterprise GitLab (#101)
* feat: add cookie-based authentication support for GitLab instances 🍪

- Add GITLAB_AUTH_COOKIE_PATH environment variable support
- Handle #HttpOnly_ prefix in cookie files properly
- Enable redirect following when cookies are present
- Maintain compatibility with existing token-based auth

* chore: prepare fork for npm publishing as @mattweg/gitlab-mcp

- Update package name to @mattweg/gitlab-mcp
- Bump version to 1.0.63-fork.1
- Add attribution to original author zereight
- Add deprecation notice referencing upstream PR #100
- Add repository and homepage URLs for fork

* fix: remove duplicate documentation line

 - removed the duplicate GITLAB_AUTH_COOKIE_PATH from README.md

* fix: move cookie header outside conditional block for universal auth support

- Move cookie header setting outside if/else block to ensure it applies
  to both old (Private-Token) and new (Bearer) GitLab authentication
- Fixes issue where cookies were only set for Bearer token auth
- Maintains backward compatibility with existing authentication methods
- Enables cookie-based authentication for all GitLab instance types

Resolves authentication failures when using GITLAB_AUTH_COOKIE_PATH
with GitLab instances that require cookie-based authentication.

* 1.0.63

* fix: add support for macOS cookie format in auth cookie parsing 🍪

- Add fallback parsing for macOS cookie format
- Handle cookie files with different structure than standard Netscape format
- Maintain compatibility with existing Linux cookie parsing
- Extract cookie name and value from space-separated format

Resolves authentication failures when using GITLAB_AUTH_COOKIE_PATH on macOS systems.

* 1.0.64

* chore: update version to 1.0.63-fork.3

* fix: implement proper cookie jar authentication for macOS

- Replace static cookie string with fetch-cookie + tough-cookie
- Add proper Netscape cookie format parsing with domain context
- Enable automatic cookie handling during OAuth2 redirects
- Fixes authentication issues on macOS with enterprise SSO

* chore: update version to 1.0.63-fork.4

* feat: add cookie-based authentication support for enterprise GitLab instances

Add support for Netscape cookie file authentication to enable access to
enterprise GitLab instances that use SSO/OAuth2 redirects.

- Add GITLAB_AUTH_COOKIE_PATH environment variable
- Implement cookie jar with proper domain handling for redirects
- Use conditional fetch assignment: cookie-enabled when path configured
- Maintains backward compatibility: no cookies = original behavior
- Zero changes to existing fetch() calls throughout codebase

Enables authentication flows like: curl -L -b ~/.midway/cookie
Useful for enterprise environments with federated authentication.

* chore: update to fork version 1.0.63-fork.5 with cookie auth support

* feat: add cookie-based authentication support for enterprise GitLab instances

Add support for Netscape cookie file authentication to enable access to
enterprise GitLab instances that use SSO/OAuth2 redirects.

- Add GITLAB_AUTH_COOKIE_PATH environment variable
- Implement cookie jar with proper domain handling for redirects
- Use conditional fetch assignment: cookie-enabled when path configured
- Maintains backward compatibility: no cookies = original behavior
- Zero changes to existing fetch() calls throughout codebase

Enables authentication flows like: curl -L -b ~/.midway/cookie
Useful for enterprise environments with federated authentication.

* feat: implement robust cookie-based authentication with hybrid parsing

- Add support for Netscape cookie file format with #HttpOnly_ prefix handling
- Implement hybrid approach using tough-cookie's parse() for robust cookie parsing
- Add automatic session establishment for enterprise GitLab authentication
- Support cookie file path via GITLAB_AUTH_COOKIE_PATH environment variable
- Integrate with fetch-cookie for automatic redirect handling and session persistence
- Ensure compatibility with Midway enterprise authentication flow

This enables seamless authentication with enterprise GitLab instances that require
cookie-based authentication while maintaining clean, maintainable code using
widely-supported packages (tough-cookie + fetch-cookie).

* chore: bump version to 1.0.63-fork.6 with ultra-clean cookie auth

* fix: correct package name to @mattweg/gitlab-mcp for proper npx dependency resolution

- Fix package name mismatch that prevented npx from installing dependencies
- Bump version to 1.0.63-fork.7
- This resolves cookie authentication issues by ensuring fetch-cookie and tough-cookie are properly installed

* Improve cookie authentication with robust session establishment

* feat: add cookie-based authentication support

This feature adds support for cookie-based authentication with GitLab instances by:
- Adding a new GITLAB_AUTH_COOKIE_PATH environment variable to specify the path to a Netscape-format cookie file
- Implementing a cookie jar parser that handles standard Netscape cookie format
- Adding session establishment logic that checks for GitLab session cookies
- Ensuring all API requests use the authenticated session

This allows the MCP server to authenticate with GitLab instances that use cookie-based authentication, which is particularly useful for instances that require SSO or other authentication methods that don't support personal access tokens.

---------

Co-authored-by: Moon (mattweg's AI assistant) <moon+ai-assistant@mattweg.dev>
Co-authored-by: Matt Weg <mattweg@amazon.com>
2025-06-16 12:38:14 +09:00
83a8aa8fc2 Fix notification_level null handling for GitLab group owners (#99)
GitLab API returns null for notification_level when users are group owners,
instead of a numeric value. This change updates the Zod schema to accept
both number and null values for notification_level in both project_access
and group_access permission objects.

Fixes TypeError when parsing repository permissions for group owners.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-13 07:16:29 +09:00
8d706275e6 docs: add CHANGELOG entry for v1.0.63 2025-06-12 21:26:22 +09:00
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
8 changed files with 565 additions and 82 deletions

View File

@ -1,8 +1,54 @@
## [1.0.63] - 2025-06-12
### Added
- 📊 **CI Job Log Pagination**: Added pagination support for CI job logs to prevent context window flooding
- `get_pipeline_job_output` now supports optional `limit` and `offset` parameters
- 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)
- See: [PR #97](https://github.com/zereight/gitlab-mcp/pull/97)
---
## [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

@ -111,6 +111,7 @@ $ sh scripts/image_push.sh docker_user_name
- `USE_GITLAB_WIKI`: When set to 'true', enables the wiki-related tools (list_wiki_pages, get_wiki_page, create_wiki_page, update_wiki_page, delete_wiki_page). By default, wiki features are disabled. - `USE_GITLAB_WIKI`: When set to 'true', enables the wiki-related tools (list_wiki_pages, get_wiki_page, create_wiki_page, update_wiki_page, delete_wiki_page). By default, wiki features are disabled.
- `USE_MILESTONE`: When set to 'true', enables the milestone-related tools (list_milestones, get_milestone, create_milestone, edit_milestone, delete_milestone, get_milestone_issue, get_milestone_merge_requests, promote_milestone, get_milestone_burndown_events). By default, milestone features are disabled. - `USE_MILESTONE`: When set to 'true', enables the milestone-related tools (list_milestones, get_milestone, create_milestone, edit_milestone, delete_milestone, get_milestone_issue, get_milestone_merge_requests, promote_milestone, get_milestone_burndown_events). By default, milestone features are disabled.
- `USE_PIPELINE`: When set to 'true', enables the pipeline-related tools (list_pipelines, get_pipeline, list_pipeline_jobs, get_pipeline_job, get_pipeline_job_output, create_pipeline, retry_pipeline, cancel_pipeline). By default, pipeline features are disabled. - `USE_PIPELINE`: When set to 'true', enables the pipeline-related tools (list_pipelines, get_pipeline, list_pipeline_jobs, get_pipeline_job, get_pipeline_job_output, create_pipeline, retry_pipeline, cancel_pipeline). By default, pipeline features are disabled.
- `GITLAB_AUTH_COOKIE_PATH`: Path to an authentication cookie file for GitLab instances that require cookie-based authentication. When provided, the cookie will be included in all GitLab API requests.
## Tools 🛠️ ## Tools 🛠️

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)
---

232
index.ts
View File

@ -4,7 +4,9 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js"; import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js"; import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import fetch from "node-fetch"; import nodeFetch from "node-fetch";
import fetchCookie from "fetch-cookie";
import { CookieJar, parse as parseCookie } from "tough-cookie";
import { SocksProxyAgent } from "socks-proxy-agent"; import { SocksProxyAgent } from "socks-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent"; import { HttpsProxyAgent } from "https-proxy-agent";
import { HttpProxyAgent } from "http-proxy-agent"; import { HttpProxyAgent } from "http-proxy-agent";
@ -17,7 +19,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 {
@ -187,7 +189,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(
@ -203,6 +205,8 @@ 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 GITLAB_AUTH_COOKIE_PATH = process.env.GITLAB_AUTH_COOKIE_PATH;
const IS_OLD = process.env.GITLAB_IS_OLD === "true";
const GITLAB_READ_ONLY_MODE = process.env.GITLAB_READ_ONLY_MODE === "true"; const 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";
@ -215,8 +219,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);
@ -244,12 +248,98 @@ if (HTTPS_PROXY) {
httpsAgent = httpsAgent || new HttpsAgent(sslOptions); httpsAgent = httpsAgent || new HttpsAgent(sslOptions);
httpAgent = httpAgent || new Agent(); httpAgent = httpAgent || new Agent();
// Create cookie jar with clean Netscape file parsing
const createCookieJar = (): CookieJar | null => {
if (!GITLAB_AUTH_COOKIE_PATH) return null;
try {
const cookiePath = GITLAB_AUTH_COOKIE_PATH.startsWith("~/")
? path.join(process.env.HOME || "", GITLAB_AUTH_COOKIE_PATH.slice(2))
: GITLAB_AUTH_COOKIE_PATH;
const jar = new CookieJar();
const cookieContent = fs.readFileSync(cookiePath, "utf8");
cookieContent.split("\n").forEach(line => {
// Handle #HttpOnly_ prefix
if (line.startsWith("#HttpOnly_")) {
line = line.slice(10);
}
// Skip comments and empty lines
if (line.startsWith("#") || !line.trim()) {
return;
}
// Parse Netscape format: domain, flag, path, secure, expires, name, value
const parts = line.split("\t");
if (parts.length >= 7) {
const [domain, , path, secure, expires, name, value] = parts;
// Build cookie string in standard format
const cookieStr = `${name}=${value}; Domain=${domain}; Path=${path}${secure === "TRUE" ? "; Secure" : ""}${expires !== "0" ? `; Expires=${new Date(parseInt(expires) * 1000).toUTCString()}` : ""}`;
// Use tough-cookie's parse function for robust parsing
const cookie = parseCookie(cookieStr);
if (cookie) {
const url = `${secure === "TRUE" ? "https" : "http"}://${domain.startsWith(".") ? domain.slice(1) : domain}`;
jar.setCookieSync(cookie, url);
}
}
});
return jar;
} catch (error) {
console.error("Error loading cookie file:", error);
return null;
}
};
// Initialize cookie jar and fetch
const cookieJar = createCookieJar();
const fetch = cookieJar ? fetchCookie(nodeFetch, cookieJar) : nodeFetch;
// Ensure session is established for the current request
async function ensureSessionForRequest(): Promise<void> {
if (!cookieJar || !GITLAB_AUTH_COOKIE_PATH) return;
// Extract the base URL from GITLAB_API_URL
const apiUrl = new URL(GITLAB_API_URL);
const baseUrl = `${apiUrl.protocol}//${apiUrl.hostname}`;
// Check if we already have GitLab session cookies
const gitlabCookies = cookieJar.getCookiesSync(baseUrl);
const hasSessionCookie = gitlabCookies.some(cookie =>
cookie.key === '_gitlab_session' || cookie.key === 'remember_user_token'
);
if (!hasSessionCookie) {
try {
// Establish session with a lightweight request
await fetch(`${GITLAB_API_URL}/user`, {
...DEFAULT_FETCH_CONFIG,
redirect: 'follow'
}).catch(() => {
// Ignore errors - the important thing is that cookies get set during redirects
});
// Small delay to ensure cookies are fully processed
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
// Ignore session establishment errors
}
}
}
// Modify DEFAULT_HEADERS to include agent configuration // 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 = {
@ -323,8 +413,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),
}, },
{ {
@ -519,7 +608,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),
}, },
{ {
@ -907,13 +996,18 @@ 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 === "labels" && Array.isArray(value)) { const keys = ["labels", "assignee_username"];
if (keys.includes(key)) {
if (Array.isArray(value)) {
// Handle array of labels // Handle array of labels
value.forEach(label => { value.forEach(label => {
url.searchParams.append("labels[]", label.toString()); url.searchParams.append(`${key}[]`, label.toString());
}); });
} else { } else {
url.searchParams.append("labels[]", value.toString()); url.searchParams.append(`${key}[]`, value.toString());
}
} else {
url.searchParams.append(key, value.toString());
} }
} }
}); });
@ -1195,6 +1289,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,
}), }),
}); });
@ -1252,12 +1348,20 @@ async function listDiscussions(
// Extract pagination headers // Extract pagination headers
const pagination = { const pagination = {
x_next_page: response.headers.get("x-next-page") ? parseInt(response.headers.get("x-next-page")!) : null, 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_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_per_page: response.headers.get("x-per-page")
x_prev_page: response.headers.get("x-prev-page") ? parseInt(response.headers.get("x-prev-page")!) : null, ? 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: 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, x_total_pages: response.headers.get("x-total-pages")
? parseInt(response.headers.get("x-total-pages")!)
: null,
}; };
return PaginatedDiscussionsResponseSchema.parse({ return PaginatedDiscussionsResponseSchema.parse({
@ -1852,9 +1956,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();
@ -2594,9 +2696,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`
@ -2615,7 +2719,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;
} }
/** /**
@ -2636,10 +2768,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(), {
@ -2715,15 +2850,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",
},
} }
); );
@ -3028,9 +3168,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 => {
@ -3060,6 +3198,11 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
throw new Error("Arguments are required"); throw new Error("Arguments are required");
} }
// Ensure session is established for every request if cookie authentication is enabled
if (GITLAB_AUTH_COOKIE_PATH) {
await ensureSessionForRequest();
}
switch (request.params.name) { switch (request.params.name) {
case "fork_repository": { case "fork_repository": {
const forkArgs = ForkRepositorySchema.parse(request.params.arguments); const forkArgs = ForkRepositorySchema.parse(request.params.arguments);
@ -3104,12 +3247,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));
@ -3121,9 +3259,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) }],
@ -3716,8 +3852,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: [
{ {
@ -3938,12 +4074,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 {
@ -3973,7 +4108,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);

249
package-lock.json generated
View File

@ -1,22 +1,24 @@
{ {
"name": "@zereight/mcp-gitlab", "name": "@zereight/mcp-gitlab",
"version": "1.0.56", "version": "1.0.62",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@zereight/mcp-gitlab", "name": "@zereight/mcp-gitlab",
"version": "1.0.56", "version": "1.0.62",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@modelcontextprotocol/sdk": "1.8.0", "@modelcontextprotocol/sdk": "1.8.0",
"@types/node-fetch": "^2.6.12", "@types/node-fetch": "^2.6.12",
"express": "^5.1.0", "express": "^5.1.0",
"fetch-cookie": "^3.1.0",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"http-proxy-agent": "^7.0.2", "http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6", "https-proxy-agent": "^7.0.6",
"node-fetch": "^3.3.2", "node-fetch": "^3.3.2",
"socks-proxy-agent": "^8.0.5", "socks-proxy-agent": "^8.0.5",
"tough-cookie": "^5.1.2",
"zod-to-json-schema": "^3.23.5" "zod-to-json-schema": "^3.23.5"
}, },
"bin": { "bin": {
@ -27,6 +29,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 +892,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 +1081,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",
@ -1656,6 +1711,16 @@
"node": "^12.20 || >= 14.13" "node": "^12.20 || >= 14.13"
} }
}, },
"node_modules/fetch-cookie": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-3.1.0.tgz",
"integrity": "sha512-s/XhhreJpqH0ftkGVcQt8JE9bqk+zRn4jF5mPJXWZeQMCI5odV9K+wEWYbnzFPHgQZlvPSMjS4n4yawWE8RINw==",
"license": "Unlicense",
"dependencies": {
"set-cookie-parser": "^2.4.8",
"tough-cookie": "^5.0.0"
}
},
"node_modules/file-entry-cache": { "node_modules/file-entry-cache": {
"version": "8.0.0", "version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@ -1894,6 +1959,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 +2094,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 +2124,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 +2415,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 +2447,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 +2596,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",
@ -2761,6 +2914,12 @@
"node": ">= 18" "node": ">= 18"
} }
}, },
"node_modules/set-cookie-parser": {
"version": "2.7.1",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
"integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
"license": "MIT"
},
"node_modules/setprototypeof": { "node_modules/setprototypeof": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@ -2898,6 +3057,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",
@ -2939,6 +3108,24 @@
"node": ">=8" "node": ">=8"
} }
}, },
"node_modules/tldts": {
"version": "6.1.86",
"resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
"integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
"license": "MIT",
"dependencies": {
"tldts-core": "^6.1.86"
},
"bin": {
"tldts": "bin/cli.js"
}
},
"node_modules/tldts-core": {
"version": "6.1.86",
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
"integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
"license": "MIT"
},
"node_modules/to-regex-range": { "node_modules/to-regex-range": {
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@ -2961,6 +3148,25 @@
"node": ">=0.6" "node": ">=0.6"
} }
}, },
"node_modules/tough-cookie": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
"integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
"license": "BSD-3-Clause",
"dependencies": {
"tldts": "^6.1.32"
},
"engines": {
"node": ">=16"
}
},
"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 +3265,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 +3329,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 +3372,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.58", "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",
@ -32,11 +33,13 @@
"@modelcontextprotocol/sdk": "1.8.0", "@modelcontextprotocol/sdk": "1.8.0",
"@types/node-fetch": "^2.6.12", "@types/node-fetch": "^2.6.12",
"express": "^5.1.0", "express": "^5.1.0",
"fetch-cookie": "^3.1.0",
"form-data": "^4.0.0", "form-data": "^4.0.0",
"http-proxy-agent": "^7.0.2", "http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6", "https-proxy-agent": "^7.0.6",
"node-fetch": "^3.3.2", "node-fetch": "^3.3.2",
"socks-proxy-agent": "^8.0.5", "socks-proxy-agent": "^8.0.5",
"tough-cookie": "^5.1.2",
"zod-to-json-schema": "^3.23.5" "zod-to-json-schema": "^3.23.5"
}, },
"devDependencies": { "devDependencies": {
@ -48,6 +51,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

@ -191,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
@ -212,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()
); );
@ -253,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
@ -296,14 +298,14 @@ export const GitLabRepositorySchema = z.object({
project_access: z project_access: z
.object({ .object({
access_level: z.number(), access_level: z.number(),
notification_level: z.number().optional(), notification_level: z.number().nullable().optional(),
}) })
.optional() .optional()
.nullable(), .nullable(),
group_access: z group_access: z
.object({ .object({
access_level: z.number(), access_level: z.number(),
notification_level: z.number().optional(), notification_level: z.number().nullable().optional(),
}) })
.optional() .optional()
.nullable(), .nullable(),
@ -467,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({
@ -593,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
@ -916,7 +920,7 @@ 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"),

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