gitlab-ci-mcp 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """MCP server for self-hosted GitLab."""
2
+
3
+ __version__ = "0.5.0"
gitlab_ci_mcp/_mcp.py ADDED
@@ -0,0 +1,110 @@
1
+ """Shared FastMCP instance, lifespan, and per-project manager cache.
2
+
3
+ Every tool module imports ``mcp`` from here to attach decorators to the
4
+ same server. Kept separate from ``server.py`` so the tool packages don't
5
+ import from a module that also defines the entry point.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import warnings
12
+ from collections.abc import AsyncIterator
13
+ from contextlib import asynccontextmanager
14
+ from typing import Annotated, Any
15
+
16
+ import urllib3
17
+ import urllib3.exceptions
18
+ from mcp.server.fastmcp import FastMCP
19
+ from pydantic import Field
20
+
21
+ from gitlab_ci_mcp.ci_manager import GitLabCIManager
22
+
23
+ # Only silence urllib3's InsecureRequestWarning (raised when
24
+ # GITLAB_SSL_VERIFY=false against self-signed corp certs). Every other
25
+ # warning stays audible so deprecations/misuse surface.
26
+ warnings.filterwarnings("ignore", category=urllib3.exceptions.InsecureRequestWarning)
27
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ _managers: dict[str, GitLabCIManager] = {}
32
+
33
+
34
+ @asynccontextmanager
35
+ async def app_lifespan(_app: FastMCP) -> AsyncIterator[dict[str, Any]]:
36
+ """Server lifespan: managers are lazy-loaded per project; close their
37
+ python-gitlab HTTP sessions on shutdown to avoid leaked sockets."""
38
+ logger.debug("gitlab_ci_mcp: startup — managers lazy-loaded per project")
39
+ try:
40
+ yield {"managers": _managers}
41
+ finally:
42
+ for m in _managers.values():
43
+ try:
44
+ m.gl.session.close()
45
+ except Exception:
46
+ pass
47
+ _managers.clear()
48
+ logger.debug("gitlab_ci_mcp: shutdown — all python-gitlab sessions closed")
49
+
50
+
51
+ mcp = FastMCP("gitlab_ci_mcp", lifespan=app_lifespan)
52
+
53
+
54
+ # ── Shared parameter annotation ─────────────────────────────────────────────
55
+
56
+ ProjectPath = Annotated[
57
+ str | None,
58
+ Field(
59
+ default=None,
60
+ description=(
61
+ "GitLab project path (e.g. 'my-org/my-repo'). When omitted, the "
62
+ "default from GITLAB_PROJECT_PATH env var is used."
63
+ ),
64
+ ),
65
+ ]
66
+
67
+
68
+ # ── Utilities ───────────────────────────────────────────────────────────────
69
+
70
+
71
+ def get_ci(project_path: str | None) -> GitLabCIManager:
72
+ """Return a cached ``GitLabCIManager`` for the given project path.
73
+
74
+ ``None`` uses the default from env. Managers are cached per path so the
75
+ python-gitlab HTTP session is reused across tool calls.
76
+ """
77
+ key = project_path or ""
78
+ if key not in _managers:
79
+ _managers[key] = GitLabCIManager(project_path=project_path or None)
80
+ return _managers[key]
81
+
82
+
83
+ def ts(dt_str: str | None) -> str | None:
84
+ """Trim an ISO timestamp to second-precision, space-separated form."""
85
+ if not dt_str:
86
+ return None
87
+ return dt_str[:19].replace("T", " ")
88
+
89
+
90
+ _SECRET_PATTERNS = ("TOKEN", "PASSWORD", "SECRET", "CREDENTIAL", "PRIVATE_KEY", "API_KEY")
91
+
92
+
93
+ def is_secret_key(key: str) -> bool:
94
+ """Heuristic: CI-variable keys that look like they hold secrets.
95
+
96
+ Matches substrings (case-insensitive) against a curated list so common
97
+ names like ``*_TOKEN``, ``GITHUB_API_KEY``, ``AWS_SECRET_ACCESS_KEY``
98
+ are caught without flagging unrelated names that merely contain the
99
+ word ``KEY`` (``MONKEY_REPO`` stays visible).
100
+ """
101
+ k = key.upper()
102
+ return any(p in k for p in _SECRET_PATTERNS)
103
+
104
+
105
+ def mask_variables(variables: dict[str, str]) -> dict[str, str]:
106
+ """Return a copy of ``variables`` with secret-looking values replaced by ``***``.
107
+
108
+ Keeps the keys visible so the agent knows which variables exist.
109
+ """
110
+ return {k: ("***" if is_secret_key(k) else v) for k, v in variables.items()}
@@ -0,0 +1,236 @@
1
+ """GitLab CI/CD manager — thin wrapper around python-gitlab for CI operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ import gitlab
11
+ from gitlab.v4.objects import Project
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ @dataclass
17
+ class PipelineResult:
18
+ pipeline_id: int
19
+ status: str
20
+ web_url: str
21
+ ref: str
22
+ created_at: str
23
+
24
+
25
+ @dataclass
26
+ class ScheduleInfo:
27
+ id: int
28
+ description: str
29
+ cron: str
30
+ cron_timezone: str
31
+ ref: str
32
+ active: bool
33
+ variables: dict[str, str]
34
+ next_run_at: str | None
35
+ web_url: str
36
+
37
+
38
+ class GitLabCIManager:
39
+ """GitLab CI/CD operations wrapper."""
40
+
41
+ def __init__(
42
+ self,
43
+ token: str | None = None,
44
+ gitlab_url: str | None = None,
45
+ project_path: str | None = None,
46
+ ssl_verify: bool | None = None,
47
+ no_proxy_domains: list[str] | None = None,
48
+ ) -> None:
49
+ """Initialize manager.
50
+
51
+ Args:
52
+ token: GitLab Personal Access Token. Falls back to ``GITLAB_TOKEN`` env.
53
+ gitlab_url: Base URL of GitLab server. Falls back to ``GITLAB_URL`` env.
54
+ project_path: ``namespace/project`` path. Falls back to ``GITLAB_PROJECT_PATH`` env.
55
+ ssl_verify: Verify SSL certs. Falls back to ``GITLAB_SSL_VERIFY`` env (default ``true``).
56
+ no_proxy_domains: Domains to add to ``NO_PROXY`` (e.g. self-hosted corp domains).
57
+ Falls back to comma-separated ``GITLAB_NO_PROXY_DOMAINS`` env.
58
+ """
59
+ token = token or os.environ.get("GITLAB_TOKEN")
60
+ gitlab_url = gitlab_url or os.environ.get("GITLAB_URL")
61
+ project_path = project_path or os.environ.get("GITLAB_PROJECT_PATH")
62
+
63
+ if not token:
64
+ raise ValueError("GitLab token is required (pass token= or set GITLAB_TOKEN env)")
65
+ if not gitlab_url:
66
+ raise ValueError("GitLab URL is required (pass gitlab_url= or set GITLAB_URL env)")
67
+ if not project_path:
68
+ raise ValueError(
69
+ "Default project path is required (pass project_path= or set GITLAB_PROJECT_PATH env). "
70
+ "Individual tools can still override it per call."
71
+ )
72
+
73
+ if ssl_verify is None:
74
+ env_val = os.environ.get("GITLAB_SSL_VERIFY", "true").lower()
75
+ ssl_verify = env_val not in ("false", "0", "no")
76
+
77
+ if no_proxy_domains is None:
78
+ env_domains = os.environ.get("GITLAB_NO_PROXY_DOMAINS", "")
79
+ no_proxy_domains = [d.strip() for d in env_domains.split(",") if d.strip()]
80
+
81
+ self.token = token
82
+ self.gitlab_url = gitlab_url
83
+ self.project_path = project_path
84
+
85
+ self._configure_no_proxy(no_proxy_domains)
86
+
87
+ self.gl = gitlab.Gitlab(gitlab_url, private_token=token, ssl_verify=ssl_verify)
88
+ self._project: Project | None = None
89
+
90
+ logger.debug("GitLabCIManager initialised for %s", project_path)
91
+
92
+ @staticmethod
93
+ def _configure_no_proxy(domains: list[str]) -> None:
94
+ """Add domains to ``NO_PROXY`` env and clear ``HTTP(S)_PROXY``.
95
+
96
+ Useful when the GitLab instance is inside a corporate network behind a
97
+ local proxy that would otherwise intercept internal traffic.
98
+ """
99
+ if not domains:
100
+ return
101
+
102
+ current = os.environ.get("NO_PROXY", os.environ.get("no_proxy", ""))
103
+ items = {s.strip() for s in current.split(",") if s.strip()}
104
+ items.update(domains)
105
+ joined = ",".join(sorted(items))
106
+ os.environ["NO_PROXY"] = joined
107
+ os.environ["no_proxy"] = joined
108
+
109
+ for var in ("HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"):
110
+ os.environ.pop(var, None)
111
+
112
+ @property
113
+ def project(self) -> Project:
114
+ if self._project is None:
115
+ self._project = self.gl.projects.get(self.project_path)
116
+ logger.debug("Loaded project: %s", self._project.name)
117
+ return self._project
118
+
119
+ # ─── Pipelines ───
120
+
121
+ def trigger_pipeline(
122
+ self,
123
+ ref: str = "master",
124
+ variables: dict[str, str] | None = None,
125
+ ) -> PipelineResult:
126
+ vars_list = [{"key": k, "value": v} for k, v in (variables or {}).items()]
127
+ pipeline = self.project.pipelines.create({"ref": ref, "variables": vars_list})
128
+ return PipelineResult(
129
+ pipeline_id=pipeline.id,
130
+ status=pipeline.status,
131
+ web_url=pipeline.web_url,
132
+ ref=pipeline.ref,
133
+ created_at=pipeline.created_at,
134
+ )
135
+
136
+ def get_pipeline_status(self, pipeline_id: int) -> str:
137
+ return self.project.pipelines.get(pipeline_id).status
138
+
139
+ def get_pipeline_jobs(self, pipeline_id: int) -> list[dict[str, Any]]:
140
+ pipeline = self.project.pipelines.get(pipeline_id)
141
+ jobs = pipeline.jobs.list(all=True)
142
+ return [
143
+ {
144
+ "id": job.id,
145
+ "name": job.name,
146
+ "stage": job.stage,
147
+ "status": job.status,
148
+ "duration": job.duration,
149
+ "web_url": job.web_url,
150
+ }
151
+ for job in jobs
152
+ ]
153
+
154
+ def get_job_log(self, job_id: int) -> str:
155
+ job = self.project.jobs.get(job_id)
156
+ return job.trace().decode("utf-8")
157
+
158
+ # ─── Schedules ───
159
+
160
+ def list_schedules(self) -> list[ScheduleInfo]:
161
+ schedules = self.project.pipelineschedules.list(all=True)
162
+ result: list[ScheduleInfo] = []
163
+ for schedule in schedules:
164
+ detail = self.project.pipelineschedules.get(schedule.id)
165
+ variables: dict[str, str] = {}
166
+ if hasattr(detail, "variables"):
167
+ try:
168
+ variables = {v.key: v.value for v in detail.variables.list()}
169
+ except Exception:
170
+ pass
171
+ result.append(
172
+ ScheduleInfo(
173
+ id=schedule.id,
174
+ description=schedule.description,
175
+ cron=schedule.cron,
176
+ cron_timezone=getattr(schedule, "cron_timezone", "UTC"),
177
+ ref=schedule.ref,
178
+ active=schedule.active,
179
+ variables=variables,
180
+ next_run_at=getattr(schedule, "next_run_at", None),
181
+ web_url=f"{self.gitlab_url}/{self.project_path}/-/pipeline_schedules/{schedule.id}/edit",
182
+ )
183
+ )
184
+ return result
185
+
186
+ def create_schedule(
187
+ self,
188
+ description: str,
189
+ cron: str,
190
+ variables: dict[str, str],
191
+ ref: str = "master",
192
+ timezone: str = "UTC",
193
+ active: bool = True,
194
+ ) -> int:
195
+ schedule = self.project.pipelineschedules.create(
196
+ {
197
+ "description": description,
198
+ "ref": ref,
199
+ "cron": cron,
200
+ "cron_timezone": timezone,
201
+ "active": active,
202
+ }
203
+ )
204
+ for key, value in variables.items():
205
+ schedule.variables.create({"key": key, "value": value})
206
+ return schedule.id
207
+
208
+ def update_schedule(
209
+ self,
210
+ schedule_id: int,
211
+ description: str | None = None,
212
+ cron: str | None = None,
213
+ ref: str | None = None,
214
+ active: bool | None = None,
215
+ variables: dict[str, str] | None = None,
216
+ ) -> None:
217
+ schedule = self.project.pipelineschedules.get(schedule_id)
218
+ if description is not None:
219
+ schedule.description = description
220
+ if cron is not None:
221
+ schedule.cron = cron
222
+ if ref is not None:
223
+ schedule.ref = ref
224
+ if active is not None:
225
+ schedule.active = active
226
+ schedule.save()
227
+
228
+ if variables is not None:
229
+ for var in schedule.variables.list():
230
+ var.delete()
231
+ for key, value in variables.items():
232
+ schedule.variables.create({"key": key, "value": value})
233
+
234
+ def delete_schedule(self, schedule_id: int) -> None:
235
+ schedule = self.project.pipelineschedules.get(schedule_id)
236
+ schedule.delete()
@@ -0,0 +1,81 @@
1
+ """Actionable error messages for python-gitlab exceptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import gitlab.exceptions as gle
6
+
7
+
8
+ def _rate_limited(action: str) -> str:
9
+ return (
10
+ f"Error: rate-limited (HTTP 429) while {action}. "
11
+ "GitLab is throttling requests — wait ~60s before retrying, reduce "
12
+ "`per_page`, or make fewer calls. See your instance's "
13
+ "`/admin/application_settings/network` for the per-user hourly limit."
14
+ )
15
+
16
+
17
+ def _server_error(code: int, action: str, exc: Exception) -> str:
18
+ return (
19
+ f"Error: GitLab server error (HTTP {code}) while {action}. "
20
+ f"The server reported: {getattr(exc, 'error_message', exc)}. "
21
+ "This is usually transient — retry in a few seconds."
22
+ )
23
+
24
+
25
+ def handle(exc: Exception, action: str) -> str:
26
+ """Convert an exception raised while performing ``action`` into an
27
+ LLM-readable string with a suggested next step.
28
+
29
+ The goal is that the agent sees *why* the call failed and *what it could
30
+ do about it* without needing to inspect the Python traceback.
31
+ """
32
+ if isinstance(exc, gle.GitlabAuthenticationError):
33
+ return (
34
+ f"Error: GitLab authentication failed while {action}. "
35
+ "Verify that `GITLAB_TOKEN` is set, not expired, and has the `api` scope. "
36
+ f"Server response: {exc}"
37
+ )
38
+
39
+ # Rate-limit and 5xx are shared across Get/Create/Update/Delete, so check
40
+ # the response_code up front (available on all GitlabError subclasses that
41
+ # carry an HTTP response).
42
+ code = getattr(exc, "response_code", None) if isinstance(exc, gle.GitlabError) else None
43
+ if code == 429:
44
+ return _rate_limited(action)
45
+ if isinstance(code, int) and 500 <= code < 600:
46
+ return _server_error(code, action, exc)
47
+
48
+ if isinstance(exc, gle.GitlabGetError):
49
+ if code == 404:
50
+ return (
51
+ f"Error: resource not found (HTTP 404) while {action}. "
52
+ "Check that the IDs and `project_path` are correct."
53
+ )
54
+ if code == 403:
55
+ return (
56
+ f"Error: forbidden (HTTP 403) while {action}. "
57
+ "Your token does not have permission for this operation. "
58
+ "Try a token with broader scope or make sure you are a project member."
59
+ )
60
+ return f"Error: GitLab returned HTTP {code} while {action}: {getattr(exc, 'error_message', exc)}"
61
+ if isinstance(exc, gle.GitlabCreateError):
62
+ return (
63
+ f"Error: could not create resource while {action}: "
64
+ f"{getattr(exc, 'error_message', exc)}. Check required fields and uniqueness constraints."
65
+ )
66
+ if isinstance(exc, gle.GitlabUpdateError):
67
+ return (
68
+ f"Error: could not update resource while {action}: "
69
+ f"{getattr(exc, 'error_message', exc)}. The resource may have been modified or deleted."
70
+ )
71
+ if isinstance(exc, gle.GitlabDeleteError):
72
+ return (
73
+ f"Error: could not delete resource while {action}: "
74
+ f"{getattr(exc, 'error_message', exc)}. Verify the resource still exists."
75
+ )
76
+ if isinstance(exc, gle.GitlabError):
77
+ return f"Error: GitLab API error while {action}: {exc}"
78
+ if isinstance(exc, ValueError):
79
+ # Raised by GitLabCIManager.__init__ when config env vars are missing.
80
+ return f"Error: configuration problem — {exc}"
81
+ return f"Error: unexpected {type(exc).__name__} while {action}: {exc}"