-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcursor_tools.py
More file actions
464 lines (387 loc) · 12.9 KB
/
cursor_tools.py
File metadata and controls
464 lines (387 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
"""
GitLab Tools for Cursor IDE
Wrapper functions for easy integration with Cursor.
Compatible with polymcp and GitLab MCP Server.
"""
import os
import asyncio
from typing import Optional, Dict, Any, List
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import the MCP server
from gitlab_mcp_server import create_gitlab_mcp_server_inprocess
# Global server instance
_server = None
def _get_server():
"""Get or create the server instance."""
global _server
if _server is None:
_server = create_gitlab_mcp_server_inprocess(verbose=False)
return _server
def _run_async(coro):
"""Run async function in sync context."""
try:
loop = asyncio.get_event_loop()
if loop.is_running():
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(asyncio.run, coro)
return future.result()
else:
return loop.run_until_complete(coro)
except RuntimeError:
return asyncio.run(coro)
def _get_project_id(project_id: Optional[str] = None) -> str:
"""Get project ID from argument or environment."""
pid = project_id or os.getenv("GITLAB_PROJECT_ID", "")
if not pid:
raise ValueError("project_id is required. Set GITLAB_PROJECT_ID in .env or pass it as argument.")
return pid
# Merge Request Functions
def list_open_merge_requests(project_id: str = None) -> Dict[str, Any]:
"""
List all open merge requests for a project.
Args:
project_id: GitLab project ID or path. Uses GITLAB_PROJECT_ID env var if not provided.
Returns:
Dictionary with merge request list and count.
Example:
>>> mrs = list_open_merge_requests("mygroup/myproject")
>>> print(f"Found {mrs['count']} open MRs")
"""
server = _get_server()
return _run_async(server.invoke(
"list_merge_requests",
{"project_id": _get_project_id(project_id), "state": "opened"}
))
def list_all_merge_requests(
project_id: str = None,
state: str = "all",
author: str = None
) -> Dict[str, Any]:
"""
List merge requests with filters.
Args:
project_id: GitLab project ID or path.
state: Filter by state (opened, closed, merged, all).
author: Filter by author username.
Returns:
Dictionary with filtered merge request list.
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"state": state
}
if author:
params["author_username"] = author
return _run_async(server.invoke("list_merge_requests", params))
def get_merge_request(
mr_iid: int,
project_id: str = None,
include_changes: bool = False,
include_discussions: bool = False
) -> Dict[str, Any]:
"""
Get detailed information about a specific merge request.
Args:
mr_iid: Merge request internal ID (the number shown in GitLab).
project_id: GitLab project ID or path.
include_changes: Include file diffs.
include_discussions: Include comments and discussions.
Returns:
Dictionary with merge request details.
Example:
>>> mr = get_merge_request(42, include_changes=True)
>>> print(mr['merge_request']['title'])
"""
server = _get_server()
return _run_async(server.invoke(
"get_merge_request_details",
{
"project_id": _get_project_id(project_id),
"mr_iid": mr_iid,
"include_changes": include_changes,
"include_discussions": include_discussions
}
))
def approve_merge_request(
mr_iid: int,
project_id: str = None,
comment: str = None
) -> Dict[str, Any]:
"""
Approve a merge request.
Args:
mr_iid: Merge request internal ID.
project_id: GitLab project ID or path.
comment: Optional approval comment.
Returns:
Approval status.
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"mr_iid": mr_iid
}
if comment:
params["approval_comment"] = comment
return _run_async(server.invoke("approve_merge_request", params))
def merge_merge_request(
mr_iid: int,
project_id: str = None,
squash: bool = False,
remove_source_branch: bool = True,
message: str = None
) -> Dict[str, Any]:
"""
Merge a merge request.
Args:
mr_iid: Merge request internal ID.
project_id: GitLab project ID or path.
squash: Squash commits when merging.
remove_source_branch: Delete source branch after merge.
message: Custom merge commit message.
Returns:
Merge status.
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"mr_iid": mr_iid,
"squash": squash,
"remove_source_branch": remove_source_branch
}
if message:
params["merge_commit_message"] = message
return _run_async(server.invoke("merge_merge_request", params))
# Pipeline and Job Functions
def list_pipeline_jobs(project_id: str = None, pipeline_id: int = None) -> Dict[str, Any]:
"""
List jobs in a pipeline.
Args:
project_id: GitLab project ID or path.
pipeline_id: Specific pipeline ID. Uses latest if not provided.
Returns:
Dictionary with job list grouped by status.
Example:
>>> jobs = list_pipeline_jobs()
>>> print(f"Failed: {jobs['summary']['failed']}, Success: {jobs['summary']['success']}")
"""
server = _get_server()
params = {"project_id": _get_project_id(project_id)}
if pipeline_id:
params["pipeline_id"] = pipeline_id
return _run_async(server.invoke("list_pipeline_jobs", params))
def analyze_pipeline_failures(project_id: str = None, pipeline_id: int = None) -> Dict[str, Any]:
"""
Analyze failed jobs in a pipeline and get fix suggestions.
Args:
project_id: GitLab project ID or path.
pipeline_id: Specific pipeline ID. Uses latest if not provided.
Returns:
Dictionary with failure analysis and fix suggestions.
Example:
>>> analysis = analyze_pipeline_failures()
>>> for job in analysis['analyses']:
... print(f"{job['job_name']}: {job['suggestions']}")
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"suggest_fixes": True
}
if pipeline_id:
params["pipeline_id"] = pipeline_id
return _run_async(server.invoke("analyze_failed_jobs", params))
def get_job_log(job_id: int, project_id: str = None, lines: int = None) -> Dict[str, Any]:
"""
Get the log output of a specific job.
Args:
job_id: The job ID.
project_id: GitLab project ID or path.
lines: Number of lines to return. Returns all if not specified.
Returns:
Dictionary with job info and log content.
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"job_id": job_id
}
if lines:
params["lines"] = lines
return _run_async(server.invoke("get_job_log", params))
def retry_job(job_id: int, project_id: str = None) -> Dict[str, Any]:
"""
Retry a failed job.
Args:
job_id: The job ID to retry.
project_id: GitLab project ID or path.
Returns:
Status of the retry operation with new job details.
"""
server = _get_server()
return _run_async(server.invoke(
"retry_failed_job",
{
"project_id": _get_project_id(project_id),
"job_id": job_id
}
))
def trigger_pipeline(
project_id: str = None,
ref: str = "main",
variables: Dict[str, str] = None
) -> Dict[str, Any]:
"""
Trigger a new pipeline run.
Args:
project_id: GitLab project ID or path.
ref: Branch, tag, or commit to run pipeline on.
variables: Pipeline variables to set.
Returns:
Details of the triggered pipeline.
"""
server = _get_server()
params = {
"project_id": _get_project_id(project_id),
"ref": ref
}
if variables:
params["variables"] = variables
return _run_async(server.invoke("trigger_pipeline", params))
# ADR Functions
def create_architecture_decision(
title: str,
context: str,
decision: str,
consequences: str,
status: str = "proposed",
alternatives: str = None,
participants: List[str] = None
) -> Dict[str, Any]:
"""
Create an Architecture Decision Record document.
Args:
title: Title of the ADR.
context: Context and problem statement.
decision: The decision that was made.
consequences: Positive and negative consequences.
status: Decision status (proposed, accepted, deprecated, superseded).
alternatives: Alternative solutions that were considered.
participants: List of people involved in the decision.
Returns:
Dictionary with ADR content in markdown format.
Example:
>>> adr = create_architecture_decision(
... title="Use PostgreSQL for primary database",
... context="We need a reliable relational database",
... decision="We will use PostgreSQL 15",
... consequences="Good performance, need DBA expertise"
... )
>>> print(adr['content'])
"""
server = _get_server()
params = {
"title": title,
"status": status,
"context": context,
"decision": decision,
"consequences": consequences
}
if alternatives:
params["alternatives"] = alternatives
if participants:
params["participants"] = participants
return _run_async(server.invoke("create_adr_document", params))
def commit_adr(
project_id: str,
adr_content: str,
adr_title: str,
branch: str = "main",
create_mr: bool = True
) -> Dict[str, Any]:
"""
Commit an ADR document to a GitLab repository.
Args:
project_id: GitLab project ID or path.
adr_content: The ADR markdown content.
adr_title: Title for the ADR.
branch: Target branch for the commit.
create_mr: Create a merge request for the ADR.
Returns:
Commit and MR details.
"""
server = _get_server()
return _run_async(server.invoke(
"commit_adr_to_gitlab",
{
"project_id": _get_project_id(project_id),
"adr_content": adr_content,
"adr_title": adr_title,
"branch": branch,
"create_mr": create_mr
}
))
# Utility Functions
def get_server_stats() -> Dict[str, Any]:
"""
Get server execution statistics.
Returns:
Dictionary with execution count, error count, and success rate.
"""
server = _get_server()
return server.get_stats()
def list_available_tools() -> List[str]:
"""
List all available GitLab tools.
Returns:
List of tool names.
"""
server = _get_server()
result = _run_async(server.list_tools())
return [tool['name'] for tool in result['tools']]
def show_help():
"""Print available commands and usage examples."""
print("""
GitLab Tools for Cursor
=======================
Merge Request Commands:
list_open_merge_requests() - List open MRs
list_all_merge_requests(state='all') - List MRs with filters
get_merge_request(mr_iid) - Get MR details
approve_merge_request(mr_iid) - Approve an MR
merge_merge_request(mr_iid) - Merge an MR
Pipeline Commands:
list_pipeline_jobs() - List jobs in latest pipeline
analyze_pipeline_failures() - Analyze failed jobs with suggestions
get_job_log(job_id) - Get job log output
retry_job(job_id) - Retry a failed job
trigger_pipeline(ref='main') - Trigger new pipeline
ADR Commands:
create_architecture_decision(...) - Create ADR document
commit_adr(...) - Commit ADR to GitLab
Utility Commands:
list_available_tools() - List all tools
get_server_stats() - Get execution stats
show_help() - Show this help
Configuration:
Set GITLAB_TOKEN and GITLAB_PROJECT_ID in .env file.
Examples:
>>> mrs = list_open_merge_requests()
>>> analysis = analyze_pipeline_failures()
>>> adr = create_architecture_decision(
... title="Use Redis for caching",
... context="Need faster response times",
... decision="Implement Redis caching layer",
... consequences="Added infrastructure complexity"
... )
""")
# Validate configuration on import
_token = os.getenv("GITLAB_TOKEN")
if not _token:
print("[GitLab Tools] WARNING: GITLAB_TOKEN not set in .env file")
else:
print("[GitLab Tools] Ready. Type show_help() for available commands")