Compare commits

..

1 Commits

Author SHA1 Message Date
011efbdd4b FIX: private token auth
issue: #88
2025-06-10 09:46:32 +09:00
7 changed files with 24 additions and 216 deletions

View File

@ -1,29 +1,3 @@
## [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

View File

@ -111,7 +111,6 @@ $ 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_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.
- `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 🛠️

View File

@ -1,11 +1,18 @@
## [1.0.62] - 2025-06-10
## [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
- 🔐 **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)
- 🔧 **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)
---

132
index.ts
View File

@ -4,9 +4,7 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
import nodeFetch from "node-fetch";
import fetchCookie from "fetch-cookie";
import { CookieJar, parse as parseCookie } from "tough-cookie";
import fetch from "node-fetch";
import { SocksProxyAgent } from "socks-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";
import { HttpProxyAgent } from "http-proxy-agent";
@ -205,7 +203,6 @@ const server = new Server(
);
const GITLAB_PERSONAL_ACCESS_TOKEN = process.env.GITLAB_PERSONAL_ACCESS_TOKEN;
const GITLAB_AUTH_COOKIE_PATH = process.env.GITLAB_AUTH_COOKIE_PATH;
const IS_OLD = process.env.GITLAB_IS_OLD === "true";
const GITLAB_READ_ONLY_MODE = process.env.GITLAB_READ_ONLY_MODE === "true";
const USE_GITLAB_WIKI = process.env.USE_GITLAB_WIKI === "true";
@ -248,88 +245,6 @@ if (HTTPS_PROXY) {
httpsAgent = httpsAgent || new HttpsAgent(sslOptions);
httpAgent = httpAgent || new Agent();
// Create cookie jar with clean Netscape file parsing
const createCookieJar = (): CookieJar | null => {
if (!GITLAB_AUTH_COOKIE_PATH) return null;
try {
const cookiePath = GITLAB_AUTH_COOKIE_PATH.startsWith("~/")
? path.join(process.env.HOME || "", GITLAB_AUTH_COOKIE_PATH.slice(2))
: GITLAB_AUTH_COOKIE_PATH;
const jar = new CookieJar();
const cookieContent = fs.readFileSync(cookiePath, "utf8");
cookieContent.split("\n").forEach(line => {
// Handle #HttpOnly_ prefix
if (line.startsWith("#HttpOnly_")) {
line = line.slice(10);
}
// Skip comments and empty lines
if (line.startsWith("#") || !line.trim()) {
return;
}
// Parse Netscape format: domain, flag, path, secure, expires, name, value
const parts = line.split("\t");
if (parts.length >= 7) {
const [domain, , path, secure, expires, name, value] = parts;
// Build cookie string in standard format
const cookieStr = `${name}=${value}; Domain=${domain}; Path=${path}${secure === "TRUE" ? "; Secure" : ""}${expires !== "0" ? `; Expires=${new Date(parseInt(expires) * 1000).toUTCString()}` : ""}`;
// Use tough-cookie's parse function for robust parsing
const cookie = parseCookie(cookieStr);
if (cookie) {
const url = `${secure === "TRUE" ? "https" : "http"}://${domain.startsWith(".") ? domain.slice(1) : domain}`;
jar.setCookieSync(cookie, url);
}
}
});
return jar;
} catch (error) {
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
const DEFAULT_HEADERS: Record<string, string> = {
Accept: "application/json",
@ -608,7 +523,7 @@ const allTools = [
},
{
name: "get_pipeline_job_output",
description: "Get the output/trace of a GitLab pipeline job with optional pagination to limit context window usage",
description: "Get the output/trace of a GitLab pipeline job number",
inputSchema: zodToJsonSchema(GetPipelineJobOutputSchema),
},
{
@ -2696,11 +2611,9 @@ async function getPipelineJob(projectId: string, jobId: number): Promise<GitLabP
*
* @param {string} projectId - The ID or URL-encoded path of the project
* @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
*/
async function getPipelineJobOutput(projectId: string, jobId: number, limit?: number, offset?: number): Promise<string> {
async function getPipelineJobOutput(projectId: string, jobId: number): Promise<string> {
projectId = decodeURIComponent(projectId); // Decode project ID
const url = new URL(
`${GITLAB_API_URL}/projects/${encodeURIComponent(projectId)}/jobs/${jobId}/trace`
@ -2719,35 +2632,7 @@ async function getPipelineJobOutput(projectId: string, jobId: number, limit?: nu
}
await handleGitLabError(response);
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;
return await response.text();
}
/**
@ -3197,11 +3082,6 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
if (!request.params.arguments) {
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) {
case "fork_repository": {
@ -3852,8 +3732,8 @@ server.setRequestHandler(CallToolRequestSchema, async request => {
}
case "get_pipeline_job_output": {
const { project_id, job_id, limit, offset } = GetPipelineJobOutputSchema.parse(request.params.arguments);
const jobOutput = await getPipelineJobOutput(project_id, job_id, limit, offset);
const { project_id, job_id } = GetPipelineJobOutputSchema.parse(request.params.arguments);
const jobOutput = await getPipelineJobOutput(project_id, job_id);
return {
content: [
{

52
package-lock.json generated
View File

@ -1,24 +1,22 @@
{
"name": "@zereight/mcp-gitlab",
"version": "1.0.62",
"version": "1.0.60",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@zereight/mcp-gitlab",
"version": "1.0.62",
"version": "1.0.60",
"license": "MIT",
"dependencies": {
"@modelcontextprotocol/sdk": "1.8.0",
"@types/node-fetch": "^2.6.12",
"express": "^5.1.0",
"fetch-cookie": "^3.1.0",
"form-data": "^4.0.0",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"node-fetch": "^3.3.2",
"socks-proxy-agent": "^8.0.5",
"tough-cookie": "^5.1.2",
"zod-to-json-schema": "^3.23.5"
},
"bin": {
@ -1711,16 +1709,6 @@
"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": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@ -2914,12 +2902,6 @@
"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": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@ -3108,24 +3090,6 @@
"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": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@ -3148,18 +3112,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",

View File

@ -1,6 +1,6 @@
{
"name": "@zereight/mcp-gitlab",
"version": "1.0.63",
"version": "1.0.61",
"description": "MCP server for using the GitLab API",
"license": "MIT",
"author": "zereight",
@ -33,13 +33,11 @@
"@modelcontextprotocol/sdk": "1.8.0",
"@types/node-fetch": "^2.6.12",
"express": "^5.1.0",
"fetch-cookie": "^3.1.0",
"form-data": "^4.0.0",
"http-proxy-agent": "^7.0.2",
"https-proxy-agent": "^7.0.6",
"node-fetch": "^3.3.2",
"socks-proxy-agent": "^8.0.5",
"tough-cookie": "^5.1.2",
"zod-to-json-schema": "^3.23.5"
},
"devDependencies": {

View File

@ -191,8 +191,6 @@ export const CancelPipelineSchema = z.object({
export const GetPipelineJobOutputSchema = z.object({
project_id: z.string().describe("Project ID or URL-encoded path"),
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
@ -298,14 +296,14 @@ export const GitLabRepositorySchema = z.object({
project_access: z
.object({
access_level: z.number(),
notification_level: z.number().nullable().optional(),
notification_level: z.number().optional(),
})
.optional()
.nullable(),
group_access: z
.object({
access_level: z.number(),
notification_level: z.number().nullable().optional(),
notification_level: z.number().optional(),
})
.optional()
.nullable(),