@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
package/src/cli.js ADDED
@@ -0,0 +1,411 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { createAudit } from "./audit.js";
5
+ import { checkConnections, CLIENTS, connectCode, connectDesktop, serverEntry, stableNodePath } from "./connect.js";
6
+ import { createGitLabClient } from "./gitlab/client.js";
7
+ import { addHost, findHost, loadHosts, removeHost, setDefaultHost } from "./hosts.js";
8
+ import { PERMISSIONS } from "./permissions/catalog.js";
9
+ import { availableProfiles, loadSettings, resolveProfile, saveSettings, selectedProfileName } from "./permissions/policy.js";
10
+ import { selectPlatform } from "./platform/index.js";
11
+ import { createSecrets } from "./secrets.js";
12
+ import { serve, VERSION } from "./server.js";
13
+ import { createSessionStore, formatUntil, parseDuration } from "./session.js";
14
+ import { configDirectory } from "./paths.js";
15
+
16
+ const HELP = `mcp-gitlab ${VERSION}: MCP server for gitlab.com and self-managed GitLab instances
17
+
18
+ Usage:
19
+ mcp-gitlab serve run the MCP server on stdio (what agents start)
20
+
21
+ mcp-gitlab host list list registered GitLab hosts
22
+ mcp-gitlab host add <url> [options] register a host or change its registration
23
+ --name <name> name used in references (default: host name of the URL)
24
+ --ssh-host <host> host name of SSH clone URLs, if it differs (repeatable)
25
+ --storage-host <pattern> host downloads may be redirected to, e.g. "*.s3.example.com" (repeatable)
26
+ --default use for references without host name
27
+ mcp-gitlab host default <name> use a host for references without host name
28
+ mcp-gitlab host remove <name> unregister a host and remove its token
29
+
30
+ mcp-gitlab token set <host> store the access token of a host in the keychain
31
+ mcp-gitlab token check [<host>] check the tokens of one or all hosts
32
+ mcp-gitlab token remove <host> remove the token of a host
33
+
34
+ mcp-gitlab profile list list profiles
35
+ mcp-gitlab profile show [<name>] show permissions of a profile (default: the active one)
36
+ mcp-gitlab profile use <name> make a profile the default one
37
+
38
+ mcp-gitlab session <duration> start a session of e.g. "8h" (24h at most): approvals granted
39
+ "for this session" last until it ends, beyond restarts of the server
40
+ mcp-gitlab session [status] show when the session ends and what was approved for it
41
+ mcp-gitlab session end end the session, revoking its approvals
42
+
43
+ mcp-gitlab audit [--limit <n>] show the latest entries of the audit log
44
+
45
+ mcp-gitlab connect <client> [options] add this server to an agent: ${CLIENTS.join( ", " )}
46
+ --profile <name> profile of that agent (default: the one selected by "profile use")
47
+ --name <name> name of the server in the agent (default: gitlab)
48
+ --yes don't ask before changing the agent's configuration
49
+ mcp-gitlab connect --check check whether the agents still find this server, e.g. after upgrading Node.js
50
+
51
+ Settings, pins and the audit log are kept in ${configDirectory()}.
52
+ Tokens are kept in the credential store of the operating system only.`;
53
+
54
+ /**
55
+ * Writes lines of output to stdout.
56
+ *
57
+ * @param {...string} parts joined with a space
58
+ * @returns {void}
59
+ */
60
+ function print( ...parts ) {
61
+ process.stdout.write( `${parts.join( " " )}\n` );
62
+ }
63
+
64
+ /**
65
+ * @param {string} message
66
+ * @returns {never}
67
+ */
68
+ function fail( message ) {
69
+ throw Object.assign( new Error( message ), { usage: true } );
70
+ }
71
+
72
+ /**
73
+ * @param {string|undefined} name
74
+ * @returns {Promise<import("./hosts.js").Host>}
75
+ */
76
+ async function requireHost( name ) {
77
+ if ( !name ) {
78
+ fail( "name the host" );
79
+ }
80
+
81
+ const host = findHost( await loadHosts(), name );
82
+
83
+ if ( !host ) {
84
+ fail( `there is no host "${name}", see "mcp-gitlab host list"` );
85
+ }
86
+
87
+ return /** @type {import("./hosts.js").Host} */ host;
88
+ }
89
+
90
+ /**
91
+ * Asks GitLab whom a token belongs to and what it may do. The user runs this
92
+ * in a terminal, so no dialog asks for approval.
93
+ *
94
+ * @param {import("./platform/index.js").Platform} platform
95
+ * @param {import("./hosts.js").Host} host
96
+ * @returns {Promise<string>} a line describing the result
97
+ */
98
+ async function checkToken( platform, host ) {
99
+ const gitlab = createGitLabClient( { secrets: createSecrets( platform ), consent: { approveHost: () => Promise.resolve() } } );
100
+
101
+ try {
102
+ const user = await gitlab.get( host, "user" );
103
+ let details = "";
104
+
105
+ try {
106
+ const token = await gitlab.get( host, "personal_access_tokens/self" );
107
+
108
+ details = `, scopes: ${token.scopes?.join( ", " ) || "none"}${token.expires_at ? `, expires ${token.expires_at}` : ", never expires"}`;
109
+ } catch {
110
+ // not a personal access token, or an older GitLab
111
+ }
112
+
113
+ return `${host.name}: ok, user ${user.username}${details}`;
114
+ } catch ( error ) {
115
+ return `${host.name}: ${error.message}`;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Asks the user a yes/no question in the terminal.
121
+ *
122
+ * @param {string} question
123
+ * @returns {Promise<boolean>}
124
+ */
125
+ async function ask( question ) {
126
+ if ( !process.stdin.isTTY ) {
127
+ fail( "can't ask for confirmation without a terminal, add --yes to proceed anyway" );
128
+ }
129
+
130
+ const prompt = createInterface( { input: process.stdin, output: process.stdout } );
131
+
132
+ try {
133
+ return /^y(?:es)?$/i.test( ( await prompt.question( `${question} [y/N] ` ) ).trim() );
134
+ } finally {
135
+ prompt.close();
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Adds the server to an agent, or checks the agents it was added to.
141
+ *
142
+ * @param {string|undefined} client
143
+ * @param {{ name?: string, profile?: string, yes?: boolean, check?: boolean }} options
144
+ * @returns {Promise<void>}
145
+ */
146
+ async function connect( client, { name = "gitlab", profile, yes, check } ) {
147
+ if ( !/^[\w.-]{1,64}$/.test( name ) ) {
148
+ fail( "the name of the server may contain letters, digits, \".\", \"_\" and \"-\" only" );
149
+ }
150
+
151
+ const io = { print, confirm: yes ? () => Promise.resolve( true ) : ask };
152
+
153
+ if ( check ) {
154
+ if ( !await checkConnections( { name }, io ) ) {
155
+ process.exitCode = 1;
156
+ }
157
+
158
+ return;
159
+ }
160
+
161
+ if ( !CLIENTS.includes( client ) ) {
162
+ fail( `name the agent: ${CLIENTS.join( ", " )}` );
163
+ }
164
+
165
+ if ( profile ) {
166
+ // refuses unknown profiles
167
+ resolveProfile( profile, await loadSettings() );
168
+ }
169
+
170
+ const entry = serverEntry( { profile, node: await stableNodePath() } );
171
+
172
+ await ( client === "claude-code" ? connectCode( { name, entry }, io ) : connectDesktop( { name, entry }, io ) );
173
+ }
174
+
175
+ /**
176
+ * Starts, shows or ends the session started by the user.
177
+ *
178
+ * @param {string} [action] a duration such as "8h", "status" or "end"
179
+ * @returns {Promise<void>}
180
+ */
181
+ async function session( action = "status" ) {
182
+ const sessions = createSessionStore();
183
+
184
+ switch ( action ) {
185
+ case "status" : {
186
+ const running = await sessions.current();
187
+
188
+ if ( !running ) {
189
+ print( "no session is running: approvals for the session last as long as the server runs" );
190
+ return;
191
+ }
192
+
193
+ print( `session until ${formatUntil( running.expires )} (${running.expires})` );
194
+ print( running.grants.length > 0 ? `approved: ${running.grants.join( ", " )}` : "nothing approved yet" );
195
+ return;
196
+ }
197
+
198
+ case "end" :
199
+ print( await sessions.end() ? "session ended, its approvals are revoked" : "no session was running" );
200
+ return;
201
+
202
+ default : {
203
+ const replaced = await sessions.current();
204
+ const started = await sessions.start( parseDuration( action ) );
205
+
206
+ print( `session until ${formatUntil( started.expires )}${replaced ? ", replacing the previous one and its approvals" : ""}` );
207
+ print( "approvals granted \"for this session\" in dialogs now last until then, beyond restarts of the server" );
208
+ }
209
+ }
210
+ }
211
+
212
+ /**
213
+ * @param {string[]} argv
214
+ * @returns {Promise<void>}
215
+ */
216
+ async function main( argv ) {
217
+ const { values, positionals } = parseArgs( {
218
+ args: argv,
219
+ allowPositionals: true,
220
+ options: {
221
+ name: { type: "string" },
222
+ "ssh-host": { type: "string", multiple: true },
223
+ "storage-host": { type: "string", multiple: true },
224
+ default: { type: "boolean" },
225
+ limit: { type: "string" },
226
+ profile: { type: "string" },
227
+ yes: { type: "boolean" },
228
+ check: { type: "boolean" },
229
+ help: { type: "boolean", short: "h" },
230
+ },
231
+ } );
232
+
233
+ const [ command, action, argument ] = positionals;
234
+ const platform = selectPlatform();
235
+
236
+ if ( values.help || !command || command === "help" ) {
237
+ print( HELP );
238
+ return;
239
+ }
240
+
241
+ if ( command === "connect" ) {
242
+ await connect( action, values );
243
+ return;
244
+ }
245
+
246
+ if ( command === "session" ) {
247
+ await session( action );
248
+ return;
249
+ }
250
+
251
+ switch ( `${command} ${action ?? ""}`.trim() ) {
252
+ case "serve" :
253
+ await serve();
254
+ return;
255
+
256
+ case "host list" : {
257
+ const hosts = await loadHosts();
258
+
259
+ if ( hosts.length === 0 ) {
260
+ print( "no hosts registered, add one with \"mcp-gitlab host add <url>\"" );
261
+ }
262
+
263
+ for ( const host of hosts ) {
264
+ const extras = [
265
+ host.default || hosts.length === 1 ? "default" : "",
266
+ host.sshHosts.length ? `ssh: ${host.sshHosts.join( ", " )}` : "",
267
+ host.storageHosts.length ? `storage: ${host.storageHosts.join( ", " )}` : "",
268
+ ].filter( Boolean );
269
+
270
+ print( `${host.name}\t${host.url}${extras.length ? `\t(${extras.join( "; " )})` : ""}` );
271
+ }
272
+
273
+ return;
274
+ }
275
+
276
+ case "host add" : {
277
+ if ( !argument ) {
278
+ fail( "name the URL of the GitLab instance, e.g. https://gitlab.com" );
279
+ }
280
+
281
+ const host = await addHost( {
282
+ url: argument,
283
+ name: values.name,
284
+ sshHosts: values["ssh-host"],
285
+ storageHosts: values["storage-host"],
286
+ makeDefault: values.default,
287
+ } );
288
+
289
+ print( `registered ${host.name} (${host.url}), store its token with "mcp-gitlab token set ${host.name}"` );
290
+ return;
291
+ }
292
+
293
+ case "host default" :
294
+ await setDefaultHost( ( await requireHost( argument ) ).name );
295
+ print( `${argument} is the default host now` );
296
+ return;
297
+
298
+ case "host remove" : {
299
+ const host = await requireHost( argument );
300
+
301
+ await removeHost( host.name );
302
+ await platform.deleteSecret( host.name );
303
+ print( `removed ${host.name} and its token` );
304
+ return;
305
+ }
306
+
307
+ case "token set" : {
308
+ const host = await requireHost( argument );
309
+
310
+ print( `Create a personal access token at ${host.url}/-/user_settings/personal_access_tokens`, "with scope \"read_api\" for reading only, or \"api\" for profiles that change things." );
311
+ print( "Enter it below, it is passed to the keychain directly and isn't shown." );
312
+
313
+ if ( !await platform.storeSecretInteractively( host.name ) ) {
314
+ fail( "the token wasn't stored" );
315
+ }
316
+
317
+ print( await checkToken( platform, host ) );
318
+ return;
319
+ }
320
+
321
+ case "token check" : {
322
+ const hosts = argument ? [await requireHost( argument )] : await loadHosts();
323
+
324
+ for ( const host of hosts ) {
325
+ print( await checkToken( platform, host ) );
326
+ }
327
+
328
+ return;
329
+ }
330
+
331
+ case "token remove" : {
332
+ const host = await requireHost( argument );
333
+
334
+ print( await platform.deleteSecret( host.name ) ? `removed the token of ${host.name}` : `there was no token for ${host.name}` );
335
+ return;
336
+ }
337
+
338
+ case "profile list" : {
339
+ const settings = await loadSettings();
340
+ const active = selectedProfileName( settings );
341
+
342
+ for ( const [ name, definition ] of Object.entries( availableProfiles( settings ) ) ) {
343
+ print( `${name === active ? "*" : " "} ${name}${definition.description ? `\t${definition.description}` : ""}` );
344
+ }
345
+
346
+ return;
347
+ }
348
+
349
+ case "profile show" : {
350
+ const settings = await loadSettings();
351
+ const profile = resolveProfile( argument ?? selectedProfileName( settings ), settings );
352
+
353
+ print( `profile ${profile.name}${profile.description ? `: ${profile.description}` : ""}` );
354
+
355
+ for ( const permission of Object.keys( PERMISSIONS ) ) {
356
+ const confirm = profile.confirm.get( permission );
357
+
358
+ if ( profile.permissions.has( permission ) ) {
359
+ print( ` ${permission.padEnd( 18 )} ${PERMISSIONS[permission]}${confirm ? ` (confirmed ${confirm === "always" ? "every time" : "once per session"})` : ""}` );
360
+ }
361
+ }
362
+
363
+ for ( const patterns of profile.scopes ) {
364
+ const included = patterns.filter( pattern => !pattern.startsWith( "!" ) );
365
+ const excluded = patterns.filter( pattern => pattern.startsWith( "!" ) ).map( pattern => pattern.slice( 1 ) );
366
+ const scope = included.length > 0 ? `only repositories matching ${included.join( ", " )}` : excluded.length > 0 ? "all repositories" : "no repositories";
367
+
368
+ print( ` ${scope}${excluded.length > 0 ? `, except ${excluded.join( ", " )}` : ""}` );
369
+ }
370
+
371
+ return;
372
+ }
373
+
374
+ case "profile use" : {
375
+ if ( !argument ) {
376
+ fail( "name the profile" );
377
+ }
378
+
379
+ const settings = await loadSettings();
380
+
381
+ resolveProfile( argument, settings );
382
+ await saveSettings( { ...settings, profile: argument } );
383
+ print( `agents get profile "${argument}" after restarting the server, unless MCP_GITLAB_PROFILE selects another one` );
384
+ return;
385
+ }
386
+
387
+ case "audit" : {
388
+ const limit = Number( values.limit ?? 20 );
389
+ const { entries } = await createAudit().list( { limit: Number.isInteger( limit ) && limit > 0 ? limit : 20 } );
390
+
391
+ for ( const entry of entries.reverse() ) {
392
+ print( `${entry.time} ${entry.outcome.padEnd( 6 )} ${entry.tool.padEnd( 16 )} ${entry.repo ?? ""}${entry.error ? ` ${entry.error}` : ""}` );
393
+ }
394
+
395
+ return;
396
+ }
397
+
398
+ default :
399
+ fail( `unknown command "${positionals.join( " " )}"` );
400
+ }
401
+ }
402
+
403
+ main( process.argv.slice( 2 ) ).catch( error => {
404
+ console.error( `mcp-gitlab: ${error.message}` );
405
+
406
+ if ( error.usage ) {
407
+ console.error( "see \"mcp-gitlab help\"" );
408
+ }
409
+
410
+ process.exitCode = 1;
411
+ } );