@giantswarm-io/pro 1.3.1

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,601 @@
1
+ /**
2
+ * MCP Tools Implementation
3
+ *
4
+ * Exposes 6 tools for managing Giant Swarm project boards:
5
+ * - list_issues: Filter and list project items with generic field filters
6
+ * - get_issue_details: Get full details for a specific item
7
+ * - update_issue_field: Update a single-select field value
8
+ * - create_issue_in_project: Create a new issue and add to a board
9
+ * - add_existing_issue: Add an existing issue to a board
10
+ * - archive_item: Archive a project item
11
+ */
12
+
13
+ import { listItems, getItemByID, updateItemField } from '../items.js';
14
+ import { findFieldByName, findMatchingOption, findMatchingIteration } from '../fields.js';
15
+ import { graphQLWithAuth } from '../api.js';
16
+ import {
17
+ resolveBoardId,
18
+ DEFAULT_BOARD,
19
+ BOARDS,
20
+ REPO_ID_QUERY,
21
+ CREATE_ISSUE_MUTATION,
22
+ ADD_ITEM_TO_PROJECT_MUTATION,
23
+ ARCHIVE_ITEM_MUTATION,
24
+ ISSUE_NODE_ID_QUERY,
25
+ UPDATE_ITEM_FIELD_MUTATION,
26
+ USER_ID_QUERY
27
+ } from '../project.js';
28
+ import { logger } from '../logger.js';
29
+ import { subIssueTools, subIssueToolHandlers } from './sub-issues.js';
30
+
31
+ const BOARD_NAMES = Object.keys(BOARDS);
32
+
33
+ /**
34
+ * Extract the GitHub token from MCP request extra context.
35
+ * Returns the OAuth token if present, otherwise undefined (falls back to env var in api.js).
36
+ * @param {Object} [extra] - MCP request extra context (contains authInfo for HTTP transport)
37
+ * @returns {string|undefined}
38
+ */
39
+ function extractToken(extra) {
40
+ return extra?.authInfo?.token;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Tool: list_issues
45
+ // ---------------------------------------------------------------------------
46
+
47
+ export const listIssuesTool = {
48
+ name: 'list_issues',
49
+ description: 'List and filter issues from a project board (roadmap or customer). Uses generic field filters -- read the board\'s schema resource first (e.g. roadmap://schema or customer://schema) to discover available fields and valid option values. Returns compact items with `repo` (nameWithOwner), `private` flag, and a `fields` map (only non-empty values). The repo URL is always https://github.com/{repo}.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ board: {
54
+ type: 'string',
55
+ enum: BOARD_NAMES,
56
+ description: 'Which board to query. Defaults to "roadmap".'
57
+ },
58
+ repository: {
59
+ type: 'string',
60
+ description: 'Filter by repository. Accepts short name (e.g. "myrepo") which resolves to "giantswarm/myrepo", or full "owner/name" format. On the customer board each customer has their own repo (e.g. "giantswarm/<customer-name>"). On the roadmap board the repos are "giantswarm/roadmap" (public) and "giantswarm/giantswarm" (internal).'
61
+ },
62
+ filters: {
63
+ type: 'object',
64
+ description: 'Field filter map: keys are field names (e.g. "Status", "Team", "Kind"), values are the desired option value. Read the board schema resource first to discover available fields and valid options.',
65
+ additionalProperties: { type: 'string' }
66
+ },
67
+ emptyFields: {
68
+ type: 'array',
69
+ items: { type: 'string' },
70
+ description: 'Return only items where these fields have no value set. Works for single-select, text, date, and iteration fields (e.g. ["Team", "Kind"]).'
71
+ },
72
+ assignee: {
73
+ type: 'string',
74
+ description: 'Filter by assignee GitHub username (e.g. "octocat"). Supports comma-separated values for OR matching (e.g. "octocat,stevecat").'
75
+ },
76
+ label: {
77
+ type: 'string',
78
+ description: 'Filter by label name (e.g. "bug"). Supports comma-separated values for OR matching (e.g. "bug,enhancement").'
79
+ },
80
+ state: {
81
+ type: 'string',
82
+ enum: ['open', 'closed'],
83
+ description: 'Filter by issue state: "open" or "closed".'
84
+ },
85
+ keyword: {
86
+ type: 'string',
87
+ description: 'Free text search matching issue titles and text fields. Matches are based on the beginning of words (e.g. "API" matches "API endpoints" but "PI" does not).'
88
+ },
89
+ updated: {
90
+ type: 'string',
91
+ description: 'Filter by last-updated date using GitHub Projects syntax. Examples: ">@today-7d" (updated in last 7 days), "<@today-30d" (not updated in last 30 days), "@today" (updated today), ">2025-01-01" (updated after a specific date).'
92
+ },
93
+ reason: {
94
+ type: 'string',
95
+ enum: ['completed', 'not planned', 'reopened'],
96
+ description: 'Filter by close reason. Only applies to closed items.'
97
+ }
98
+ }
99
+ }
100
+ };
101
+
102
+ const KNOWN_LIST_PARAMS = new Set([
103
+ 'board', 'project', 'repository', 'filters', 'emptyFields',
104
+ 'assignee', 'label', 'state', 'keyword', 'updated', 'reason'
105
+ ]);
106
+
107
+ // Board field names are single words (Team, Kind, Status), so simple
108
+ // word-boundary capitalization is sufficient here.
109
+ function titleCase(str) {
110
+ return str.replace(/\b\w/g, c => c.toUpperCase());
111
+ }
112
+
113
+ export async function handleListIssues(args, extra) {
114
+ try {
115
+ const token = extractToken(extra);
116
+ const board = args.board || args.project || DEFAULT_BOARD;
117
+ const boardId = resolveBoardId(board);
118
+
119
+ const filters = { ...(args.filters || {}) };
120
+ for (const [key, value] of Object.entries(args)) {
121
+ if (KNOWN_LIST_PARAMS.has(key) || typeof value !== 'string') continue;
122
+ const fieldName = titleCase(key);
123
+ logger.warn(`MCP: list_issues auto-forwarding top-level param "${key}" to filters["${fieldName}"]`);
124
+ filters[fieldName] = value;
125
+ }
126
+
127
+ logger.info('MCP: Listing issues', {
128
+ board, repository: args.repository, filters,
129
+ emptyFields: args.emptyFields, assignee: args.assignee,
130
+ label: args.label, state: args.state, keyword: args.keyword,
131
+ updated: args.updated, reason: args.reason
132
+ });
133
+
134
+ const result = await listItems({
135
+ boardId,
136
+ repository: args.repository || null,
137
+ filters,
138
+ emptyFields: args.emptyFields || [],
139
+ assignee: args.assignee || null,
140
+ label: args.label || null,
141
+ state: args.state || null,
142
+ keyword: args.keyword || null,
143
+ updated: args.updated || null,
144
+ reason: args.reason || null,
145
+ token
146
+ });
147
+
148
+ if (result.status === 'error') {
149
+ return { error: result.error };
150
+ }
151
+
152
+ return {
153
+ content: [{
154
+ type: 'text',
155
+ text: JSON.stringify({
156
+ count: result.data.length,
157
+ issues: result.data
158
+ })
159
+ }]
160
+ };
161
+ } catch (error) {
162
+ logger.error('MCP: Error listing issues', { error: error.message });
163
+ return { error: error.message };
164
+ }
165
+ }
166
+
167
+ // ---------------------------------------------------------------------------
168
+ // Tool: get_issue_details
169
+ // ---------------------------------------------------------------------------
170
+
171
+ export const getIssueDetailsTool = {
172
+ name: 'get_issue_details',
173
+ description: 'Get detailed information about a specific issue including repository metadata, title, description, comments, assignees, labels, and field values.',
174
+ inputSchema: {
175
+ type: 'object',
176
+ properties: {
177
+ itemId: {
178
+ type: 'string',
179
+ description: 'The ID of the project item to retrieve'
180
+ }
181
+ },
182
+ required: ['itemId']
183
+ }
184
+ };
185
+
186
+ export async function handleGetIssueDetails(args, extra) {
187
+ try {
188
+ const token = extractToken(extra);
189
+ logger.info('MCP: Getting issue details', { itemId: args.itemId });
190
+ const issue = await getItemByID(args.itemId, token);
191
+
192
+ return {
193
+ content: [{
194
+ type: 'text',
195
+ text: JSON.stringify(issue)
196
+ }]
197
+ };
198
+ } catch (error) {
199
+ logger.error('MCP: Error getting issue details', { error: error.message });
200
+ return { error: error.message };
201
+ }
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // Tool: update_issue_field
206
+ // ---------------------------------------------------------------------------
207
+
208
+ export const updateIssueFieldTool = {
209
+ name: 'update_issue_field',
210
+ description: 'Update a field value for an issue on a project board. Supports single-select fields (Status, Kind, Team, etc.) and iteration fields (Quarter). Also supports date fields (Start Date, Target Date) when a specific date is known. The server resolves field and option names to internal IDs automatically.',
211
+ inputSchema: {
212
+ type: 'object',
213
+ properties: {
214
+ itemId: {
215
+ type: 'string',
216
+ description: 'The ID of the project item to update'
217
+ },
218
+ fieldName: {
219
+ type: 'string',
220
+ description: 'The field name (e.g., Team, Status, Kind, Stage, Impact, Quarter). Read the board schema resource to see available fields.'
221
+ },
222
+ value: {
223
+ type: 'string',
224
+ description: 'The value to set. For single-select/iteration fields: option name with case-insensitive matching (e.g. "Q2 2026"). For date fields: "YYYY-MM-DD" format.'
225
+ },
226
+ board: {
227
+ type: 'string',
228
+ enum: BOARD_NAMES,
229
+ description: 'Which board the item belongs to. Defaults to "roadmap".'
230
+ }
231
+ },
232
+ required: ['itemId', 'fieldName', 'value']
233
+ }
234
+ };
235
+
236
+ export async function handleUpdateIssueField(args, extra) {
237
+ try {
238
+ const token = extractToken(extra);
239
+ const board = args.board || DEFAULT_BOARD;
240
+ const boardId = resolveBoardId(board);
241
+ logger.info('MCP: Updating issue field', { ...args, board });
242
+
243
+ const field = await findFieldByName(args.fieldName, boardId, token);
244
+ if (!field) {
245
+ return {
246
+ error: `Field '${args.fieldName}' not found on the ${board} board. Only single-select, iteration, and date fields can be updated.`
247
+ };
248
+ }
249
+
250
+ let value;
251
+ let resolvedName;
252
+
253
+ if (field.__typename === 'ProjectV2SingleSelectField') {
254
+ const option = findMatchingOption(field.options, args.value);
255
+ if (!option) {
256
+ return {
257
+ error: `Value '${args.value}' not found in ${args.fieldName} options. Available: ${field.options.map(o => o.name).join(', ')}`
258
+ };
259
+ }
260
+ value = { singleSelectOptionId: option.id };
261
+ resolvedName = option.name;
262
+
263
+ } else if (field.__typename === 'ProjectV2IterationField') {
264
+ const iteration = findMatchingIteration(field, args.value);
265
+ if (!iteration) {
266
+ const available = (field.configuration?.iterations || []).map(i => i.title);
267
+ return {
268
+ error: `Value '${args.value}' not found in ${args.fieldName} iterations. Available: ${available.join(', ')}`
269
+ };
270
+ }
271
+ value = { iterationId: iteration.id };
272
+ resolvedName = iteration.title;
273
+
274
+ } else if (field.dataType === 'DATE') {
275
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(args.value)) {
276
+ return {
277
+ error: `Invalid date format '${args.value}' for field '${args.fieldName}'. Expected YYYY-MM-DD (e.g. "2026-06-30").`
278
+ };
279
+ }
280
+ value = { date: args.value };
281
+ resolvedName = args.value;
282
+
283
+ } else {
284
+ return {
285
+ error: `Field '${args.fieldName}' has unsupported type '${field.__typename}' for updates.`
286
+ };
287
+ }
288
+
289
+ await updateItemField(args.itemId, field.id, value, boardId, token);
290
+
291
+ return {
292
+ content: [{
293
+ type: 'text',
294
+ text: JSON.stringify({
295
+ success: true,
296
+ itemId: args.itemId,
297
+ field: args.fieldName,
298
+ value: resolvedName
299
+ })
300
+ }]
301
+ };
302
+ } catch (error) {
303
+ logger.error('MCP: Error updating issue field', { error: error.message });
304
+ return { error: error.message };
305
+ }
306
+ }
307
+
308
+ // ---------------------------------------------------------------------------
309
+ // Tool: create_issue_in_project
310
+ // ---------------------------------------------------------------------------
311
+
312
+ export const createIssueInProjectTool = {
313
+ name: 'create_issue_in_project',
314
+ description: 'Create a new GitHub Issue in a specified repository and add it to a project board. Supports optional initial status and assignees. For public repos, only create sanitized, non-customer-specific content.',
315
+ inputSchema: {
316
+ type: 'object',
317
+ properties: {
318
+ repository: {
319
+ type: 'string',
320
+ description: 'Repository name (e.g., "my-app") within the giantswarm org, or full "owner/name" format. Use giantswarm/roadmap for public-safe issues and giantswarm/giantswarm for internal/customer-specific issues.'
321
+ },
322
+ title: {
323
+ type: 'string',
324
+ description: 'The title of the issue'
325
+ },
326
+ body: {
327
+ type: 'string',
328
+ description: 'The markdown body content of the issue'
329
+ },
330
+ assignees: {
331
+ type: 'array',
332
+ description: 'Optional GitHub usernames to assign to the new issue',
333
+ items: { type: 'string' }
334
+ },
335
+ confirmPublicSafe: {
336
+ type: 'boolean',
337
+ description: 'Required when repository resolves to giantswarm/roadmap. Must be true to confirm the title/body are sanitized and safe for public visibility.'
338
+ },
339
+ initialStatus: {
340
+ type: 'string',
341
+ description: 'The status to set after adding to the board (e.g., "Todo")'
342
+ },
343
+ board: {
344
+ type: 'string',
345
+ enum: BOARD_NAMES,
346
+ description: 'Which board to add the issue to. Defaults to "roadmap".'
347
+ }
348
+ },
349
+ required: ['repository', 'title']
350
+ }
351
+ };
352
+
353
+ export async function handleCreateIssueInProject(args, extra) {
354
+ try {
355
+ const token = extractToken(extra);
356
+ const board = args.board || DEFAULT_BOARD;
357
+ const boardId = resolveBoardId(board);
358
+ logger.info('MCP: Creating issue in project', { repository: args.repository, title: args.title, board });
359
+
360
+ // Parse repository into owner/name
361
+ let owner, repo;
362
+ if (args.repository.includes('/')) {
363
+ [owner, repo] = args.repository.split('/');
364
+ } else {
365
+ owner = 'giantswarm';
366
+ repo = args.repository;
367
+ }
368
+
369
+ if (owner.toLowerCase() === 'giantswarm' && repo.toLowerCase() === 'roadmap' && args.confirmPublicSafe !== true) {
370
+ return {
371
+ error: 'Creating issues in giantswarm/roadmap requires confirmPublicSafe=true to reduce accidental disclosure of internal or customer-specific information.'
372
+ };
373
+ }
374
+
375
+ // Get repository node ID
376
+ const repoResult = await graphQLWithAuth(REPO_ID_QUERY, { owner, repo }, token);
377
+ if (!repoResult?.repository?.id) {
378
+ return { error: `Repository '${owner}/${repo}' not found` };
379
+ }
380
+ const repositoryId = repoResult.repository.id;
381
+
382
+ const assigneeLogins = Array.isArray(args.assignees)
383
+ ? args.assignees
384
+ .map(login => String(login || '').trim())
385
+ .filter(login => login !== '')
386
+ : [];
387
+
388
+ const assigneeIds = [];
389
+ for (const login of assigneeLogins) {
390
+ const userResult = await graphQLWithAuth(USER_ID_QUERY, { login }, token);
391
+ if (!userResult?.user?.id) {
392
+ return { error: `Assignee '${login}' not found` };
393
+ }
394
+ assigneeIds.push(userResult.user.id);
395
+ }
396
+
397
+ // Create the issue
398
+ const createResult = await graphQLWithAuth(CREATE_ISSUE_MUTATION, {
399
+ repositoryId,
400
+ title: args.title,
401
+ body: args.body || '',
402
+ assigneeIds: assigneeIds.length > 0 ? assigneeIds : undefined
403
+ }, token);
404
+
405
+ const issue = createResult.createIssue.issue;
406
+
407
+ // Add the issue to the project board
408
+ const addResult = await graphQLWithAuth(ADD_ITEM_TO_PROJECT_MUTATION, {
409
+ projectId: boardId,
410
+ contentId: issue.id
411
+ }, token);
412
+
413
+ const projectItemId = addResult.addProjectV2ItemById.item.id;
414
+
415
+ // Set initial status if provided
416
+ if (args.initialStatus) {
417
+ const statusField = await findFieldByName('status', boardId, token);
418
+ if (statusField) {
419
+ const statusOption = findMatchingOption(statusField.options, args.initialStatus);
420
+ if (statusOption) {
421
+ await graphQLWithAuth(UPDATE_ITEM_FIELD_MUTATION, {
422
+ projectId: boardId,
423
+ itemId: projectItemId,
424
+ fieldId: statusField.id,
425
+ value: { singleSelectOptionId: statusOption.id }
426
+ }, token);
427
+ }
428
+ }
429
+ }
430
+
431
+ return {
432
+ content: [{
433
+ type: 'text',
434
+ text: JSON.stringify({
435
+ success: true,
436
+ issueUrl: issue.url,
437
+ issueNumber: issue.number,
438
+ projectItemId
439
+ })
440
+ }]
441
+ };
442
+ } catch (error) {
443
+ logger.error('MCP: Error creating issue in project', { error: error.message });
444
+ return { error: error.message };
445
+ }
446
+ }
447
+
448
+ // ---------------------------------------------------------------------------
449
+ // Tool: add_existing_issue
450
+ // ---------------------------------------------------------------------------
451
+
452
+ export const addExistingIssueTool = {
453
+ name: 'add_existing_issue',
454
+ description: 'Add an existing GitHub issue to a project board. At least one of issueUrl or issueNodeId must be provided.',
455
+ inputSchema: {
456
+ type: 'object',
457
+ properties: {
458
+ issueUrl: {
459
+ type: 'string',
460
+ description: 'Full URL of the issue (e.g., "https://github.com/giantswarm/roadmap/issues/123")'
461
+ },
462
+ issueNodeId: {
463
+ type: 'string',
464
+ description: 'The global node ID of the issue (starts with "I_")'
465
+ },
466
+ board: {
467
+ type: 'string',
468
+ enum: BOARD_NAMES,
469
+ description: 'Which board to add the issue to. Defaults to "roadmap".'
470
+ }
471
+ }
472
+ }
473
+ };
474
+
475
+ export async function handleAddExistingIssue(args, extra) {
476
+ try {
477
+ const token = extractToken(extra);
478
+ const board = args.board || DEFAULT_BOARD;
479
+ const boardId = resolveBoardId(board);
480
+ logger.info('MCP: Adding existing issue to project', { ...args, board });
481
+
482
+ let contentId = args.issueNodeId;
483
+
484
+ // If URL is provided, resolve it to a node ID
485
+ if (!contentId && args.issueUrl) {
486
+ const urlMatch = args.issueUrl.match(/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+)/);
487
+ if (!urlMatch) {
488
+ return { error: `Could not parse issue URL: ${args.issueUrl}` };
489
+ }
490
+ const [, owner, repo, numberStr] = urlMatch;
491
+ const result = await graphQLWithAuth(ISSUE_NODE_ID_QUERY, {
492
+ owner,
493
+ repo,
494
+ number: parseInt(numberStr, 10)
495
+ }, token);
496
+
497
+ if (!result?.repository?.issue?.id) {
498
+ return { error: `Issue not found: ${args.issueUrl}` };
499
+ }
500
+ contentId = result.repository.issue.id;
501
+ }
502
+
503
+ if (!contentId) {
504
+ return { error: 'Either issueUrl or issueNodeId is required' };
505
+ }
506
+
507
+ const addResult = await graphQLWithAuth(ADD_ITEM_TO_PROJECT_MUTATION, {
508
+ projectId: boardId,
509
+ contentId
510
+ }, token);
511
+
512
+ return {
513
+ content: [{
514
+ type: 'text',
515
+ text: JSON.stringify({
516
+ success: true,
517
+ projectItemId: addResult.addProjectV2ItemById.item.id
518
+ })
519
+ }]
520
+ };
521
+ } catch (error) {
522
+ logger.error('MCP: Error adding existing issue', { error: error.message });
523
+ return { error: error.message };
524
+ }
525
+ }
526
+
527
+ // ---------------------------------------------------------------------------
528
+ // Tool: archive_item
529
+ // ---------------------------------------------------------------------------
530
+
531
+ export const archiveItemTool = {
532
+ name: 'archive_item',
533
+ description: 'Archive a project item, removing it from the active board view without deleting the underlying issue.',
534
+ inputSchema: {
535
+ type: 'object',
536
+ properties: {
537
+ itemId: {
538
+ type: 'string',
539
+ description: 'The project item ID to archive'
540
+ },
541
+ board: {
542
+ type: 'string',
543
+ enum: BOARD_NAMES,
544
+ description: 'Which board the item belongs to. Defaults to "roadmap".'
545
+ }
546
+ },
547
+ required: ['itemId']
548
+ }
549
+ };
550
+
551
+ export async function handleArchiveItem(args, extra) {
552
+ try {
553
+ const token = extractToken(extra);
554
+ const board = args.board || DEFAULT_BOARD;
555
+ const boardId = resolveBoardId(board);
556
+ logger.info('MCP: Archiving item', { itemId: args.itemId, board });
557
+
558
+ await graphQLWithAuth(ARCHIVE_ITEM_MUTATION, {
559
+ projectId: boardId,
560
+ itemId: args.itemId
561
+ }, token);
562
+
563
+ return {
564
+ content: [{
565
+ type: 'text',
566
+ text: JSON.stringify({
567
+ success: true,
568
+ itemId: args.itemId,
569
+ archived: true
570
+ })
571
+ }]
572
+ };
573
+ } catch (error) {
574
+ logger.error('MCP: Error archiving item', { error: error.message });
575
+ return { error: error.message };
576
+ }
577
+ }
578
+
579
+ // ---------------------------------------------------------------------------
580
+ // Exports
581
+ // ---------------------------------------------------------------------------
582
+
583
+ export const tools = [
584
+ listIssuesTool,
585
+ getIssueDetailsTool,
586
+ updateIssueFieldTool,
587
+ createIssueInProjectTool,
588
+ addExistingIssueTool,
589
+ archiveItemTool,
590
+ ...subIssueTools
591
+ ];
592
+
593
+ export const toolHandlers = {
594
+ list_issues: handleListIssues,
595
+ get_issue_details: handleGetIssueDetails,
596
+ update_issue_field: handleUpdateIssueField,
597
+ create_issue_in_project: handleCreateIssueInProject,
598
+ add_existing_issue: handleAddExistingIssue,
599
+ archive_item: handleArchiveItem,
600
+ ...subIssueToolHandlers
601
+ };