@cepharum/mcp-gitlab 0.0.0-stage → 0.1.0

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.
Files changed (44) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +170 -2
  4. package/package.json +50 -5
  5. package/src/audit.js +185 -0
  6. package/src/cli.js +411 -0
  7. package/src/connect.js +335 -0
  8. package/src/consent.js +115 -0
  9. package/src/downloads.js +94 -0
  10. package/src/errors.js +13 -0
  11. package/src/git.js +94 -0
  12. package/src/gitlab/client.js +406 -0
  13. package/src/gitlab/diff.js +79 -0
  14. package/src/hosts.js +228 -0
  15. package/src/paths.js +71 -0
  16. package/src/permissions/catalog.js +75 -0
  17. package/src/permissions/policy.js +230 -0
  18. package/src/permissions/profiles.js +66 -0
  19. package/src/pins.js +36 -0
  20. package/src/platform/index.js +76 -0
  21. package/src/platform/macos.js +129 -0
  22. package/src/platform/service.js +2 -0
  23. package/src/process.js +56 -0
  24. package/src/refs.js +146 -0
  25. package/src/secrets.js +51 -0
  26. package/src/server.js +146 -0
  27. package/src/session.js +140 -0
  28. package/src/text.js +68 -0
  29. package/src/tools/artifacts.js +288 -0
  30. package/src/tools/audit.js +53 -0
  31. package/src/tools/environments.js +147 -0
  32. package/src/tools/files.js +101 -0
  33. package/src/tools/index.js +33 -0
  34. package/src/tools/issues.js +465 -0
  35. package/src/tools/merge-requests.js +698 -0
  36. package/src/tools/packages.js +322 -0
  37. package/src/tools/pipelines.js +415 -0
  38. package/src/tools/registry.js +107 -0
  39. package/src/tools/repositories.js +174 -0
  40. package/src/tools/schedules.js +521 -0
  41. package/src/tools/shared.js +93 -0
  42. package/src/tools/variables.js +294 -0
  43. package/src/tools/wikis.js +168 -0
  44. package/src/zip.js +178 -0
@@ -0,0 +1,465 @@
1
+ import { z } from "zod";
2
+ import { projectId } from "../gitlab/client.js";
3
+ import { DeniedError } from "../errors.js";
4
+ import { allowsRepo } from "../permissions/policy.js";
5
+ import { formatRef, parseRef } from "../refs.js";
6
+ import { parseTime } from "./audit.js";
7
+ import { PAGE_INPUT, UNTRUSTED, pick } from "./shared.js";
8
+
9
+ const ISSUE_INPUT = z.union( [ z.number().int().min( 1 ), z.string().regex( /^#?\d{1,9}$/ ) ] )
10
+ .describe( "Number of the issue in its project, e.g. 12 or \"#12\"" );
11
+
12
+ const USER_INPUT = z.string().min( 1 ).max( 255 ).regex( /^(?:[\w.]|-)+$/ );
13
+
14
+ const DATE_INPUT = z.string().regex( /^\d{4}-\d{2}-\d{2}$/, "expected YYYY-MM-DD" );
15
+
16
+ const MILESTONE_DESCRIPTION = "Title of a milestone, or \"current\" for the active milestone whose dates include today";
17
+
18
+ /**
19
+ * @param {number|string} value
20
+ * @returns {number}
21
+ */
22
+ function iidOf( value ) {
23
+ return Number( String( value ).replace( /^#/, "" ) );
24
+ }
25
+
26
+ /**
27
+ * @param {import("../refs.js").RepoRef} repo
28
+ * @param {number|string} issue
29
+ * @param {string} [suffix]
30
+ * @returns {string}
31
+ */
32
+ function issueEndpoint( repo, issue, suffix = "" ) {
33
+ return `projects/${projectId( repo )}/issues/${iidOf( issue )}${suffix}`;
34
+ }
35
+
36
+ /**
37
+ * @param {any} user
38
+ * @returns {string|undefined}
39
+ */
40
+ const username = user => user?.username;
41
+
42
+ /**
43
+ * @returns {string} today as YYYY-MM-DD
44
+ */
45
+ const today = () => new Date().toISOString().slice( 0, 10 );
46
+
47
+ /**
48
+ * Basic properties of an issue, as lists show them.
49
+ *
50
+ * @param {any} issue
51
+ * @returns {Record<string, unknown>}
52
+ */
53
+ function summary( issue ) {
54
+ return pick( issue, {
55
+ issue: "iid",
56
+ title: "title",
57
+ state: "state",
58
+ type: source => ( source.issue_type && source.issue_type !== "issue" ? source.issue_type : undefined ),
59
+ labels: source => ( source.labels?.length ? source.labels : undefined ),
60
+ assignees: source => ( source.assignees?.length ? source.assignees.map( username ) : undefined ),
61
+ milestone: source => source.milestone?.title,
62
+ due: "due_date",
63
+ updated: "updated_at",
64
+ } );
65
+ }
66
+
67
+ /**
68
+ * All properties of an issue an agent needs to work with it.
69
+ *
70
+ * @param {any} issue
71
+ * @returns {Record<string, unknown>}
72
+ */
73
+ function details( issue ) {
74
+ return {
75
+ ...summary( issue ),
76
+ ...pick( issue, {
77
+ description: "description",
78
+ author: source => username( source.author ),
79
+ weight: "weight",
80
+ confidential: source => source.confidential || undefined,
81
+ tasks: source => ( source.task_completion_status?.count ? `${source.task_completion_status.completed_count} of ${source.task_completion_status.count} done` : undefined ),
82
+ comments: "user_notes_count",
83
+ created: "created_at",
84
+ closed: "closed_at",
85
+ closedBy: source => username( source.closed_by ),
86
+ webUrl: "web_url",
87
+ } ),
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Lists the milestones of a project, including those of its groups.
93
+ *
94
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
95
+ * @param {import("../refs.js").RepoRef} repo
96
+ * @param {{ state?: string, title?: string, page?: number }} [options]
97
+ * @returns {Promise<import("../gitlab/client.js").Page>}
98
+ */
99
+ function milestones( gitlab, repo, { state, title, page = 1 } = {} ) {
100
+ return gitlab.list( repo.host, `projects/${projectId( repo )}/milestones`, {
101
+ query: { state, title, include_ancestors: true },
102
+ page,
103
+ perPage: 100,
104
+ } );
105
+ }
106
+
107
+ /**
108
+ * Tells whether a milestone is the one in progress today.
109
+ *
110
+ * @param {any} milestone
111
+ * @param {string} day YYYY-MM-DD
112
+ * @returns {boolean}
113
+ */
114
+ function isCurrent( milestone, day ) {
115
+ return milestone.state === "active" && Boolean( milestone.start_date || milestone.due_date ) &&
116
+ ( !milestone.start_date || milestone.start_date <= day ) && ( !milestone.due_date || milestone.due_date >= day );
117
+ }
118
+
119
+ /**
120
+ * Finds a milestone by title, "current" being the active one whose dates include today.
121
+ *
122
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
123
+ * @param {import("../refs.js").RepoRef} repo
124
+ * @param {string} name
125
+ * @returns {Promise<any>}
126
+ */
127
+ async function findMilestone( gitlab, repo, name ) {
128
+ if ( name === "current" ) {
129
+ const day = today();
130
+ const { items } = await milestones( gitlab, repo, { state: "active" } );
131
+ const [found] = items.filter( milestone => isCurrent( milestone, day ) ).sort( ( a, b ) => String( a.due_date ?? "9999" ).localeCompare( String( b.due_date ?? "9999" ) ) );
132
+
133
+ if ( !found ) {
134
+ throw new Error( `there is no milestone of ${formatRef( repo )} whose dates include today, see milestone_list` );
135
+ }
136
+
137
+ return found;
138
+ }
139
+
140
+ const { items } = await milestones( gitlab, repo, { title: name } );
141
+ const found = items.find( milestone => milestone.title === name );
142
+
143
+ if ( !found ) {
144
+ throw new Error( `there is no milestone "${name}" in ${formatRef( repo )}, see milestone_list` );
145
+ }
146
+
147
+ return found;
148
+ }
149
+
150
+ /**
151
+ * Converts user names into the IDs GitLab takes, "me" being the user of the token.
152
+ *
153
+ * @param {import("../gitlab/client.js").GitLabClient} gitlab
154
+ * @param {import("../hosts.js").Host} host
155
+ * @param {string[]} names
156
+ * @returns {Promise<number[]>}
157
+ */
158
+ function userIds( gitlab, host, names ) {
159
+ return Promise.all( names.map( async name => {
160
+ if ( name === "me" ) {
161
+ return ( await gitlab.currentUser( host ) ).id;
162
+ }
163
+
164
+ const [user] = await gitlab.get( host, "users", { username: name } );
165
+
166
+ if ( !user ) {
167
+ throw new Error( `there is no user "${name}" at ${host.name}` );
168
+ }
169
+
170
+ return user.id;
171
+ } ) );
172
+ }
173
+
174
+ /** @type {import("./shared.js").ToolDefinition[]} */
175
+ export const issueTools = [
176
+ {
177
+ name: "issue_list",
178
+ title: "List issues",
179
+ description: "Lists issues of a repository, most recently updated first: open ones by default, optionally by assignee (\"me\", \"none\", \"any\" or a user name), author, labels, milestone, type, text or last change.",
180
+ permission: "issue.read",
181
+ usesRepo: true,
182
+ input: {
183
+ state: z.enum( [ "opened", "closed", "all" ] ).optional().describe( "Default: opened" ),
184
+ assignee: USER_INPUT.optional().describe( "\"me\", \"none\", \"any\" or a user name" ),
185
+ author: USER_INPUT.optional().describe( "\"me\" or a user name" ),
186
+ labels: z.array( z.string().min( 1 ).max( 255 ) ).max( 20 ).optional().describe( "Issues having all of these labels" ),
187
+ milestone: z.string().min( 1 ).max( 255 ).optional().describe( `${MILESTONE_DESCRIPTION}, \"none\" or \"any\"` ),
188
+ type: z.enum( [ "issue", "incident", "task" ] ).optional(),
189
+ search: z.string().min( 2 ).max( 100 ).optional().describe( "Text in title or description" ),
190
+ changedSince: z.string().max( 40 ).optional().describe( "ISO date or time, or a span back from now such as \"3d\", \"2w\"" ),
191
+ orderBy: z.enum( [ "updated", "created", "priority", "due" ] ).optional().describe( "Default: updated" ),
192
+ page: PAGE_INPUT,
193
+ },
194
+ async handler( { state = "opened", assignee, author, labels, milestone, type, search, changedSince, orderBy = "updated", page = 1 }, { repo, gitlab } ) {
195
+ const me = async name => ( name === "me" ? ( await gitlab.currentUser( repo.host ) ).username : name );
196
+ const query = {
197
+ state,
198
+ author_username: author && await me( author ),
199
+ labels: labels?.join( "," ),
200
+ issue_type: type,
201
+ search,
202
+ updated_after: parseTime( changedSince )?.toISOString(),
203
+ order_by: { updated: "updated_at", created: "created_at", priority: "priority", due: "due_date" }[orderBy],
204
+ sort: orderBy === "due" ? "asc" : "desc",
205
+ };
206
+
207
+ if ( assignee === "none" || assignee === "any" ) {
208
+ query.assignee_id = assignee === "none" ? "None" : "Any";
209
+ } else if ( assignee ) {
210
+ query.assignee_username = await me( assignee );
211
+ }
212
+
213
+ if ( milestone === "none" || milestone === "any" ) {
214
+ query.milestone = milestone === "none" ? "None" : "Any";
215
+ } else if ( milestone ) {
216
+ query.milestone = ( await findMilestone( gitlab, repo, milestone ) ).title;
217
+ }
218
+
219
+ const { items, nextPage } = await gitlab.list( repo.host, `projects/${projectId( repo )}/issues`, { query, page, perPage: 30 } );
220
+
221
+ return {
222
+ repo: formatRef( repo ),
223
+ ...query.milestone && milestone === "current" ? { milestone: query.milestone } : {},
224
+ issues: items.map( summary ),
225
+ ...nextPage ? { nextPage } : {},
226
+ };
227
+ },
228
+ },
229
+ {
230
+ name: "issue_get",
231
+ title: "Read an issue",
232
+ description: `Returns an issue with description, labels, assignees, milestone, linked issues and related merge requests. ${UNTRUSTED}`,
233
+ permission: "issue.read",
234
+ usesRepo: true,
235
+ input: { issue: ISSUE_INPUT },
236
+ async handler( { issue }, { repo, gitlab } ) {
237
+ const [ data, links, mergeRequests ] = await Promise.all( [
238
+ gitlab.get( repo.host, issueEndpoint( repo, issue ) ),
239
+ gitlab.get( repo.host, issueEndpoint( repo, issue, "/links" ) ).catch( () => [] ),
240
+ gitlab.get( repo.host, issueEndpoint( repo, issue, "/related_merge_requests" ) ).catch( () => [] ),
241
+ ] );
242
+
243
+ return {
244
+ repo: formatRef( repo ),
245
+ ...details( data ),
246
+ ...links.length ? {
247
+ links: links.map( link => ( {
248
+ issue: link.references?.full ?? `#${link.iid}`,
249
+ title: link.title,
250
+ state: link.state,
251
+ type: link.link_type,
252
+ } ) ),
253
+ } : {},
254
+ ...mergeRequests.length ? {
255
+ mergeRequests: mergeRequests.map( mr => ( { mr: mr.references?.full ?? `!${mr.iid}`, title: mr.title, state: mr.state } ) ),
256
+ } : {},
257
+ };
258
+ },
259
+ },
260
+ {
261
+ name: "issue_comment_list",
262
+ title: "List comments of an issue",
263
+ description: `Lists the comments of an issue, oldest first, marking those of the user as "mine". ${UNTRUSTED}`,
264
+ permission: "issue.read",
265
+ usesRepo: true,
266
+ input: { issue: ISSUE_INPUT, page: PAGE_INPUT },
267
+ async handler( { issue, page = 1 }, { repo, gitlab } ) {
268
+ const [ { items, nextPage }, me ] = await Promise.all( [
269
+ gitlab.list( repo.host, issueEndpoint( repo, issue, "/notes" ), { query: { sort: "asc", order_by: "created_at" }, page, perPage: 50 } ),
270
+ gitlab.currentUser( repo.host ),
271
+ ] );
272
+
273
+ return {
274
+ repo: formatRef( repo ),
275
+ issue: iidOf( issue ),
276
+ comments: items.filter( note => !note.system ).map( note => ( {
277
+ id: note.id,
278
+ author: username( note.author ),
279
+ ...note.author?.id === me.id ? { mine: true } : {},
280
+ created: note.created_at,
281
+ body: note.body,
282
+ } ) ),
283
+ ...nextPage ? { nextPage } : {},
284
+ };
285
+ },
286
+ },
287
+ {
288
+ name: "issue_comment",
289
+ title: "Comment on an issue",
290
+ description: "Adds a comment to an issue, or changes one of the user's own comments.",
291
+ permission: "issue.comment",
292
+ usesRepo: true,
293
+ mutates: true,
294
+ input: {
295
+ issue: ISSUE_INPUT,
296
+ body: z.string().min( 1 ).max( 100_000 ).describe( "Markdown" ),
297
+ comment: z.number().int().min( 1 ).optional().describe( "ID of an own comment to replace, as issue_comment_list returns it" ),
298
+ },
299
+ async handler( { issue, body, comment }, { repo, gitlab } ) {
300
+ if ( comment ) {
301
+ const [ note, me ] = await Promise.all( [
302
+ gitlab.get( repo.host, issueEndpoint( repo, issue, `/notes/${comment}` ) ),
303
+ gitlab.currentUser( repo.host ),
304
+ ] );
305
+
306
+ if ( note.author?.id !== me.id ) {
307
+ throw new DeniedError( "only comments of the user can be changed" );
308
+ }
309
+
310
+ await gitlab.put( repo.host, issueEndpoint( repo, issue, `/notes/${comment}` ), { body } );
311
+
312
+ return { repo: formatRef( repo ), issue: iidOf( issue ), comment, changed: true };
313
+ }
314
+
315
+ const note = await gitlab.post( repo.host, issueEndpoint( repo, issue, "/notes" ), { body } );
316
+
317
+ return { repo: formatRef( repo ), issue: iidOf( issue ), comment: note.id };
318
+ },
319
+ },
320
+ {
321
+ name: "issue_create",
322
+ title: "Create an issue",
323
+ description: "Creates an issue, incident or task with labels, assignees, milestone, due date and weight.",
324
+ permission: "issue.create",
325
+ usesRepo: true,
326
+ mutates: true,
327
+ input: {
328
+ title: z.string().min( 1 ).max( 255 ),
329
+ description: z.string().max( 100_000 ).optional().describe( "Markdown" ),
330
+ type: z.enum( [ "issue", "incident", "task" ] ).optional().describe( "Default: issue" ),
331
+ labels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
332
+ assignees: z.array( USER_INPUT ).max( 20 ).optional().describe( "User names, \"me\" for the user" ),
333
+ milestone: z.string().min( 1 ).max( 255 ).optional().describe( MILESTONE_DESCRIPTION ),
334
+ due: DATE_INPUT.optional(),
335
+ weight: z.number().int().min( 0 ).max( 10_000 ).optional(),
336
+ confidential: z.boolean().optional(),
337
+ },
338
+ async handler( { title, description, type, labels, assignees, milestone, due, weight, confidential }, { repo, gitlab } ) {
339
+ const created = await gitlab.post( repo.host, `projects/${projectId( repo )}/issues`, {
340
+ title,
341
+ description,
342
+ issue_type: type,
343
+ labels: labels?.join( "," ),
344
+ assignee_ids: assignees?.length ? await userIds( gitlab, repo.host, assignees ) : undefined,
345
+ milestone_id: milestone ? ( await findMilestone( gitlab, repo, milestone ) ).id : undefined,
346
+ due_date: due,
347
+ weight,
348
+ confidential,
349
+ } );
350
+
351
+ return { repo: formatRef( repo ), ...details( created ) };
352
+ },
353
+ },
354
+ {
355
+ name: "issue_update",
356
+ title: "Change an issue",
357
+ description: "Closes or reopens an issue, or changes title, description, labels, assignees, milestone, due date, weight or confidentiality. Assignees given replace the current ones.",
358
+ permission: "issue.update",
359
+ usesRepo: true,
360
+ mutates: true,
361
+ input: {
362
+ issue: ISSUE_INPUT,
363
+ state: z.enum( [ "close", "reopen" ] ).optional(),
364
+ title: z.string().min( 1 ).max( 255 ).optional(),
365
+ description: z.string().max( 100_000 ).optional().describe( "Markdown, replaces the description" ),
366
+ addLabels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
367
+ removeLabels: z.array( z.string().min( 1 ).max( 255 ) ).max( 50 ).optional(),
368
+ assignees: z.array( USER_INPUT ).max( 20 ).optional().describe( "User names, \"me\" for the user, empty to remove all" ),
369
+ milestone: z.string().min( 1 ).max( 255 ).optional().describe( `${MILESTONE_DESCRIPTION}, or \"none\" to remove it` ),
370
+ due: z.union( [ DATE_INPUT, z.literal( "none" ) ] ).optional().describe( "YYYY-MM-DD, or \"none\" to remove it" ),
371
+ weight: z.number().int().min( 0 ).max( 10_000 ).optional(),
372
+ confidential: z.boolean().optional(),
373
+ },
374
+ async handler( { issue, state, title, description, addLabels, removeLabels, assignees, milestone, due, weight, confidential }, { repo, gitlab } ) {
375
+ const body = {
376
+ state_event: state,
377
+ title,
378
+ description,
379
+ add_labels: addLabels?.join( "," ),
380
+ remove_labels: removeLabels?.join( "," ),
381
+ // GitLab ignores empty lists, 0 removes everybody
382
+ assignee_ids: assignees && ( assignees.length ? await userIds( gitlab, repo.host, assignees ) : [0] ),
383
+ milestone_id: milestone && ( milestone === "none" ? 0 : ( await findMilestone( gitlab, repo, milestone ) ).id ),
384
+ due_date: due && ( due === "none" ? null : due ),
385
+ weight,
386
+ confidential,
387
+ };
388
+
389
+ if ( Object.values( body ).every( value => value === undefined ) ) {
390
+ throw new Error( "nothing to change" );
391
+ }
392
+
393
+ return { repo: formatRef( repo ), ...details( await gitlab.put( repo.host, issueEndpoint( repo, issue ), body ) ) };
394
+ },
395
+ },
396
+ {
397
+ name: "issue_link",
398
+ title: "Link issues",
399
+ description: "Links an issue to another one, of the same or another repository of the same host: related, blocks, or is blocked by (the latter two need GitLab Premium). Links aren't removed.",
400
+ permission: "issue.link",
401
+ usesRepo: true,
402
+ mutates: true,
403
+ input: {
404
+ issue: ISSUE_INPUT,
405
+ target: z.string().min( 1 ).max( 320 ).regex( /^(?:\S*#)?\d{1,9}$/ ).describe( "The other issue: \"12\", \"#12\", or \"<repo>#12\" for one of another repository" ),
406
+ type: z.enum( [ "relates_to", "blocks", "is_blocked_by" ] ).optional().describe( "Default: relates_to" ),
407
+ },
408
+ async handler( { issue, target, type = "relates_to" }, { repo, gitlab, hosts, profile } ) {
409
+ const hash = target.lastIndexOf( "#" );
410
+ const other = hash > 0 ? parseRef( target.slice( 0, hash ), hosts ) : repo;
411
+
412
+ if ( other.host.name !== repo.host.name ) {
413
+ throw new Error( "issues can only be linked within one GitLab host" );
414
+ }
415
+
416
+ if ( !allowsRepo( profile, formatRef( other ) ) ) {
417
+ throw new DeniedError( `profile "${profile.name}" doesn't allow access to ${formatRef( other )}` );
418
+ }
419
+
420
+ const project = await gitlab.get( repo.host, `projects/${projectId( other )}` );
421
+ const targetIid = Number( target.slice( hash + 1 ) );
422
+
423
+ await gitlab.post( repo.host, issueEndpoint( repo, issue, "/links" ), {
424
+ target_project_id: project.id,
425
+ target_issue_iid: targetIid,
426
+ link_type: type,
427
+ } );
428
+
429
+ return { repo: formatRef( repo ), issue: iidOf( issue ), linked: `${formatRef( other )}#${targetIid}`, type };
430
+ },
431
+ },
432
+ {
433
+ name: "milestone_list",
434
+ title: "List milestones",
435
+ description: "Lists the milestones of a repository and its groups, which serve as sprints, marking the current one whose dates include today.",
436
+ permission: "issue.read",
437
+ usesRepo: true,
438
+ input: {
439
+ state: z.enum( [ "active", "closed", "all" ] ).optional().describe( "Default: active" ),
440
+ page: PAGE_INPUT,
441
+ },
442
+ async handler( { state = "active", page = 1 }, { repo, gitlab } ) {
443
+ const day = today();
444
+ const { items, nextPage } = await milestones( gitlab, repo, { state: state === "all" ? undefined : state, page } );
445
+
446
+ return {
447
+ repo: formatRef( repo ),
448
+ milestones: items
449
+ .sort( ( a, b ) => String( a.due_date ?? "9999" ).localeCompare( String( b.due_date ?? "9999" ) ) )
450
+ .map( milestone => ( {
451
+ ...pick( milestone, {
452
+ title: "title",
453
+ state: "state",
454
+ start: "start_date",
455
+ due: "due_date",
456
+ group: source => ( source.group_id ? true : undefined ),
457
+ webUrl: "web_url",
458
+ } ),
459
+ ...isCurrent( milestone, day ) ? { current: true } : {},
460
+ } ) ),
461
+ ...nextPage ? { nextPage } : {},
462
+ };
463
+ },
464
+ },
465
+ ];