@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.
- package/LICENSE +201 -0
- package/README.md +317 -0
- package/bin/index.js +65 -0
- package/package.json +40 -0
- package/src/index.js +49 -0
- package/src/lib/api.js +87 -0
- package/src/lib/auth/provider.js +395 -0
- package/src/lib/fields.js +111 -0
- package/src/lib/items.js +426 -0
- package/src/lib/logger.js +40 -0
- package/src/lib/mcp/http.js +233 -0
- package/src/lib/mcp/resources.js +304 -0
- package/src/lib/mcp/server.js +156 -0
- package/src/lib/mcp/sub-issues.js +580 -0
- package/src/lib/mcp/tools.js +601 -0
- package/src/lib/project.js +406 -0
- package/src/lib/rest-api.js +141 -0
- package/src/lib/selfupdate.js +107 -0
- package/src/lib/sub-issues.js +100 -0
- package/src/lib/utils.js +23 -0
- package/src/lib/version.js +19 -0
package/src/lib/items.js
ADDED
|
@@ -0,0 +1,426 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Items Management Module
|
|
3
|
+
*
|
|
4
|
+
* Provides functions to list, filter, and update GitHub Project V2 items
|
|
5
|
+
* on a given project board. All functions return data directly
|
|
6
|
+
* without console output.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { fetchPaginated, graphQLWithAuth } from './api.js';
|
|
10
|
+
import {
|
|
11
|
+
LIST_ITEMS_QUERY,
|
|
12
|
+
ISSUE_DETAIL_QUERY,
|
|
13
|
+
UPDATE_ITEM_FIELD_MUTATION
|
|
14
|
+
} from './project.js';
|
|
15
|
+
import { listFields, findMatchingOption } from './fields.js';
|
|
16
|
+
import { logger } from './logger.js';
|
|
17
|
+
|
|
18
|
+
function escapeProjectQueryValue(value) {
|
|
19
|
+
return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Get detailed information about an item by its project item ID
|
|
24
|
+
* @param {string} itemId - The project item ID
|
|
25
|
+
* @param {string} [token] - Optional per-request GitHub token
|
|
26
|
+
* @returns {Promise<Object>} - Extracted item data
|
|
27
|
+
*/
|
|
28
|
+
export async function getItemByID(itemId, token) {
|
|
29
|
+
let item = {
|
|
30
|
+
number: '',
|
|
31
|
+
title: '',
|
|
32
|
+
url: '',
|
|
33
|
+
repository: null,
|
|
34
|
+
body: '',
|
|
35
|
+
author: '',
|
|
36
|
+
assignees: [],
|
|
37
|
+
comments: [],
|
|
38
|
+
labels: [],
|
|
39
|
+
projects: [],
|
|
40
|
+
fields: [],
|
|
41
|
+
createdAt: null,
|
|
42
|
+
updatedAt: null,
|
|
43
|
+
closedAt: null
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const issueDetails = await graphQLWithAuth(ISSUE_DETAIL_QUERY, { id: itemId }, token);
|
|
48
|
+
if (!issueDetails?.node) {
|
|
49
|
+
throw new Error('Project item not found');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (issueDetails.node.fieldValues?.nodes) {
|
|
53
|
+
item.fields = issueDetails.node.fieldValues.nodes
|
|
54
|
+
.filter(fieldValue => fieldValue?.field?.name)
|
|
55
|
+
.map(fieldValue => ({
|
|
56
|
+
name: fieldValue.field.name,
|
|
57
|
+
value:
|
|
58
|
+
fieldValue.name ??
|
|
59
|
+
fieldValue.text ??
|
|
60
|
+
fieldValue.date ??
|
|
61
|
+
fieldValue.title ??
|
|
62
|
+
fieldValue.milestone?.title ??
|
|
63
|
+
''
|
|
64
|
+
}));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (issueDetails.node.content) {
|
|
68
|
+
item.number = issueDetails.node.content.number || '';
|
|
69
|
+
item.title = issueDetails.node.content.title || '';
|
|
70
|
+
item.url = issueDetails.node.content.url || '';
|
|
71
|
+
item.repository = issueDetails.node.content.repository
|
|
72
|
+
? {
|
|
73
|
+
nameWithOwner: issueDetails.node.content.repository.nameWithOwner,
|
|
74
|
+
isPrivate: issueDetails.node.content.repository.isPrivate,
|
|
75
|
+
url: issueDetails.node.content.repository.url
|
|
76
|
+
}
|
|
77
|
+
: null;
|
|
78
|
+
item.author = issueDetails.node.content.author?.login || '';
|
|
79
|
+
item.body = issueDetails.node.content.body || '';
|
|
80
|
+
|
|
81
|
+
item.createdAt = issueDetails.node.content.createdAt || null;
|
|
82
|
+
item.updatedAt = issueDetails.node.content.updatedAt || null;
|
|
83
|
+
item.closedAt = issueDetails.node.content.closedAt || null;
|
|
84
|
+
|
|
85
|
+
if (issueDetails.node.content.assignees?.nodes) {
|
|
86
|
+
item.assignees = issueDetails.node.content.assignees.nodes.map(a => a.login);
|
|
87
|
+
}
|
|
88
|
+
if (issueDetails.node.content.comments?.nodes) {
|
|
89
|
+
item.comments = issueDetails.node.content.comments.nodes.map(c => ({
|
|
90
|
+
body: c.body,
|
|
91
|
+
createdAt: c.createdAt,
|
|
92
|
+
author: c.author?.login || ''
|
|
93
|
+
}));
|
|
94
|
+
}
|
|
95
|
+
if (issueDetails.node.content.labels?.nodes) {
|
|
96
|
+
item.labels = issueDetails.node.content.labels.nodes.map(l => l.name);
|
|
97
|
+
}
|
|
98
|
+
if (issueDetails.node.content.projectsV2?.nodes) {
|
|
99
|
+
item.projects = issueDetails.node.content.projectsV2.nodes.map(p => p.title);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} catch (err) {
|
|
103
|
+
logger.error(`Error fetching issue details: ${err.message}`);
|
|
104
|
+
throw new Error(`Failed to fetch issue details for item '${itemId}': ${err.message}`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return item;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Derive a GitHub Projects query key from a field name.
|
|
112
|
+
* E.g. "Working Group" -> "working-group", "SIG" -> "sig", "Team" -> "team"
|
|
113
|
+
*
|
|
114
|
+
* NOTE: This heuristic assumes GitHub Projects accepts query keys that are the
|
|
115
|
+
* lowercased, hyphenated form of the field display name. This holds for all
|
|
116
|
+
* known fields on the roadmap and customer boards. If a board introduces fields
|
|
117
|
+
* where this convention doesn't hold, the server-side filter will silently
|
|
118
|
+
* return no results and the items will need to be filtered client-side instead.
|
|
119
|
+
*
|
|
120
|
+
* @param {string} fieldName - The display name of the field
|
|
121
|
+
* @returns {string} - The query key for server-side filtering
|
|
122
|
+
*/
|
|
123
|
+
function fieldNameToQueryKey(fieldName) {
|
|
124
|
+
return fieldName.toLowerCase().replace(/\s+/g, '-');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Resolve a short or full repository name to "owner/name" format.
|
|
129
|
+
* Accepts "myrepo" -> "giantswarm/myrepo" or "giantswarm/myrepo" -> "giantswarm/myrepo".
|
|
130
|
+
*
|
|
131
|
+
* @param {string} repository - Short name or full "owner/name" format
|
|
132
|
+
* @returns {string} - Full "owner/name" format
|
|
133
|
+
*/
|
|
134
|
+
function resolveRepositoryName(repository) {
|
|
135
|
+
const trimmed = repository.trim();
|
|
136
|
+
if (trimmed.includes('/')) {
|
|
137
|
+
return trimmed;
|
|
138
|
+
}
|
|
139
|
+
return `giantswarm/${trimmed}`;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* List and filter items in a project board
|
|
144
|
+
* @param {Object} options - Filtering options
|
|
145
|
+
* @param {string} options.boardId - The GitHub project node ID (required)
|
|
146
|
+
* @param {string} [options.repository] - Filter by repository (short name or "owner/name")
|
|
147
|
+
* @param {Object} [options.filters] - Field name to value map for filtering (single-select fields)
|
|
148
|
+
* @param {string[]} [options.emptyFields] - Return only items where these fields have no value set
|
|
149
|
+
* @param {string} [options.assignee] - Filter by assignee GitHub username (comma-separated for OR)
|
|
150
|
+
* @param {string} [options.label] - Filter by label name (comma-separated for OR)
|
|
151
|
+
* @param {string} [options.state] - Filter by issue state: "open" or "closed"
|
|
152
|
+
* @param {string} [options.keyword] - Free text search matching titles and text fields
|
|
153
|
+
* @param {string} [options.updated] - Filter by last-updated date (e.g. ">@today-7d")
|
|
154
|
+
* @param {string} [options.reason] - Filter by close reason: "completed", "not planned", or "reopened"
|
|
155
|
+
* @param {string} [options.token] - Optional per-request GitHub token
|
|
156
|
+
* @returns {Promise<Object>} - Result with status and data
|
|
157
|
+
*/
|
|
158
|
+
export async function listItems(options) {
|
|
159
|
+
const first = 100;
|
|
160
|
+
try {
|
|
161
|
+
const {
|
|
162
|
+
boardId, repository = null, filters = {}, emptyFields = [],
|
|
163
|
+
assignee = null, label = null, state = null, keyword = null,
|
|
164
|
+
updated = null, reason = null, token
|
|
165
|
+
} = options;
|
|
166
|
+
|
|
167
|
+
if (!boardId) {
|
|
168
|
+
throw new Error('boardId is required');
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Build server-side filter query
|
|
172
|
+
const queryTerms = [];
|
|
173
|
+
|
|
174
|
+
// Repository filter uses GitHub Projects built-in repo: prefix
|
|
175
|
+
if (repository) {
|
|
176
|
+
const fullRepo = resolveRepositoryName(repository);
|
|
177
|
+
queryTerms.push(`repo:${fullRepo}`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// Assignee filter — supports comma-separated usernames for OR matching
|
|
181
|
+
if (assignee) {
|
|
182
|
+
const trimmed = assignee.trim();
|
|
183
|
+
if (trimmed) {
|
|
184
|
+
queryTerms.push(`assignee:${trimmed}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Label filter — supports comma-separated labels for OR matching.
|
|
189
|
+
// Each individual label that contains spaces is quoted separately so that
|
|
190
|
+
// e.g. "bug fix,enhancement" becomes label:"bug fix",enhancement.
|
|
191
|
+
if (label) {
|
|
192
|
+
const trimmed = label.trim();
|
|
193
|
+
if (trimmed) {
|
|
194
|
+
if (trimmed.includes(',')) {
|
|
195
|
+
const parts = trimmed.split(',').map(p => {
|
|
196
|
+
const s = p.trim();
|
|
197
|
+
return s.includes(' ') ? `"${escapeProjectQueryValue(s)}"` : s;
|
|
198
|
+
});
|
|
199
|
+
queryTerms.push(`label:${parts.join(',')}`);
|
|
200
|
+
} else if (trimmed.includes(' ')) {
|
|
201
|
+
queryTerms.push(`label:"${escapeProjectQueryValue(trimmed)}"`);
|
|
202
|
+
} else {
|
|
203
|
+
queryTerms.push(`label:${trimmed}`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Issue state filter (is:open, is:closed)
|
|
209
|
+
if (state) {
|
|
210
|
+
const trimmed = state.trim().toLowerCase();
|
|
211
|
+
if (trimmed === 'open' || trimmed === 'closed') {
|
|
212
|
+
queryTerms.push(`is:${trimmed}`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// Last-updated date filter — passed through using GitHub's query syntax.
|
|
217
|
+
// Examples: ">@today-7d", "<@today-30d", "@today", ">2025-01-01"
|
|
218
|
+
if (updated) {
|
|
219
|
+
const trimmed = updated.trim();
|
|
220
|
+
if (trimmed) {
|
|
221
|
+
queryTerms.push(`updated:${trimmed}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Close reason filter
|
|
226
|
+
if (reason) {
|
|
227
|
+
const trimmed = reason.trim();
|
|
228
|
+
if (trimmed) {
|
|
229
|
+
if (trimmed.includes(' ')) {
|
|
230
|
+
queryTerms.push(`reason:"${escapeProjectQueryValue(trimmed)}"`);
|
|
231
|
+
} else {
|
|
232
|
+
queryTerms.push(`reason:${trimmed}`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Free text keyword search — appended as bare text to the query string.
|
|
238
|
+
// GitHub Projects matches on word-prefix against titles and text fields.
|
|
239
|
+
// NOTE: Because the keyword is injected as bare text, values resembling
|
|
240
|
+
// query operators (e.g. "is:closed") will be interpreted as such by the
|
|
241
|
+
// GitHub Projects query engine rather than as literal search terms. This
|
|
242
|
+
// is acceptable since the MCP tool schema documents keyword as free text
|
|
243
|
+
// and the calling LLM should use the dedicated parameters for operators.
|
|
244
|
+
if (keyword) {
|
|
245
|
+
const trimmed = keyword.trim();
|
|
246
|
+
if (trimmed) {
|
|
247
|
+
queryTerms.push(trimmed);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Generic field filters
|
|
252
|
+
const filterEntries = Object.entries(filters).filter(
|
|
253
|
+
([, value]) => typeof value === 'string' && value.trim() !== ''
|
|
254
|
+
);
|
|
255
|
+
|
|
256
|
+
// Fetch board fields once if needed for filter validation or emptyFields validation
|
|
257
|
+
const needFields = filterEntries.length > 0 || emptyFields.length > 0;
|
|
258
|
+
const allFields = needFields ? await listFields(boardId, token) : [];
|
|
259
|
+
|
|
260
|
+
// Validate emptyFields names against actual board fields
|
|
261
|
+
if (emptyFields.length > 0) {
|
|
262
|
+
const allFieldNames = allFields.map(f => f.name.toLowerCase());
|
|
263
|
+
for (const fn of emptyFields) {
|
|
264
|
+
if (!allFieldNames.some(n => n === fn.toLowerCase())) {
|
|
265
|
+
const available = allFields.map(f => f.name);
|
|
266
|
+
return {
|
|
267
|
+
status: 'error',
|
|
268
|
+
error: `emptyFields: field '${fn}' not found. Available fields: ${available.join(', ')}`
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (filterEntries.length > 0) {
|
|
275
|
+
for (const [fieldName, requestedValue] of filterEntries) {
|
|
276
|
+
const trimmedValue = requestedValue.trim();
|
|
277
|
+
if (trimmedValue.toLowerCase() === 'all') {
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const field = allFields.find(fieldNode =>
|
|
282
|
+
fieldNode.__typename === 'ProjectV2SingleSelectField' &&
|
|
283
|
+
fieldNode.name.toLowerCase() === fieldName.toLowerCase()
|
|
284
|
+
);
|
|
285
|
+
|
|
286
|
+
if (!field) {
|
|
287
|
+
const availableFields = allFields
|
|
288
|
+
.filter(f => f.__typename === 'ProjectV2SingleSelectField')
|
|
289
|
+
.map(f => f.name);
|
|
290
|
+
return {
|
|
291
|
+
status: 'error',
|
|
292
|
+
error: `Field '${fieldName}' not found. Available single-select fields: ${availableFields.join(', ')}`
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const matchingOption = findMatchingOption(field.options || [], trimmedValue);
|
|
297
|
+
if (!matchingOption) {
|
|
298
|
+
const availableOptions = (field.options || []).map(o => o.name);
|
|
299
|
+
return {
|
|
300
|
+
status: 'error',
|
|
301
|
+
error: `Value '${trimmedValue}' not found for field '${field.name}'. Available options: ${availableOptions.join(', ')}`
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const escapedValue = escapeProjectQueryValue(matchingOption.name);
|
|
306
|
+
const queryKey = fieldNameToQueryKey(field.name);
|
|
307
|
+
queryTerms.push(`${queryKey}:"${escapedValue}"`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// Add server-side no:<field> filters for emptyFields.
|
|
312
|
+
// GitHub Projects V2 supports "no:<field-key>" to match items where
|
|
313
|
+
// a field has no value set, which avoids fetching the entire board.
|
|
314
|
+
// The client-side filter below is kept as a safety net in case the
|
|
315
|
+
// heuristic in fieldNameToQueryKey doesn't match a particular field.
|
|
316
|
+
for (const fieldName of emptyFields) {
|
|
317
|
+
const queryKey = fieldNameToQueryKey(fieldName);
|
|
318
|
+
queryTerms.push(`no:${queryKey}`);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
const projectQuery = queryTerms.join(' ');
|
|
322
|
+
|
|
323
|
+
const allItems = await fetchPaginated(
|
|
324
|
+
LIST_ITEMS_QUERY,
|
|
325
|
+
{ projectId: boardId, first, filterQuery: projectQuery || null },
|
|
326
|
+
result => {
|
|
327
|
+
if (!result?.node?.items) {
|
|
328
|
+
return { nodes: [], pageInfo: { hasNextPage: false } };
|
|
329
|
+
}
|
|
330
|
+
return {
|
|
331
|
+
nodes: result.node.items.nodes || [],
|
|
332
|
+
pageInfo: result.node.items.pageInfo || { hasNextPage: false }
|
|
333
|
+
};
|
|
334
|
+
},
|
|
335
|
+
token
|
|
336
|
+
);
|
|
337
|
+
|
|
338
|
+
// Generic empty-field filtering (supports single-select, text, date, and iteration fields)
|
|
339
|
+
function hasNonEmptyField(item, fieldName) {
|
|
340
|
+
return item.fieldValues.nodes.some(node => {
|
|
341
|
+
if (!node.field?.name) return false;
|
|
342
|
+
if (node.field.name.toLowerCase() !== fieldName.toLowerCase()) return false;
|
|
343
|
+
const value = node.name ?? node.text ?? node.date ?? node.title ?? '';
|
|
344
|
+
return typeof value === 'string' && value.trim() !== '';
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const filtered = allItems.filter(item => {
|
|
349
|
+
if (!item.fieldValues || !item.fieldValues.nodes) return false;
|
|
350
|
+
if (!item.content || !item.content.title) return false;
|
|
351
|
+
|
|
352
|
+
for (const fieldName of emptyFields) {
|
|
353
|
+
if (hasNonEmptyField(item, fieldName)) {
|
|
354
|
+
return false;
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
return true;
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
return {
|
|
361
|
+
status: 'success',
|
|
362
|
+
data: filtered.map(item => {
|
|
363
|
+
// Build compact fields map, omitting empty values
|
|
364
|
+
const fields = {};
|
|
365
|
+
if (item.fieldValues?.nodes) {
|
|
366
|
+
for (const node of item.fieldValues.nodes) {
|
|
367
|
+
if (node.field?.name && node.name) {
|
|
368
|
+
fields[node.field.name] = node.name;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// Extract assignees from issue content (already fetched by the query)
|
|
374
|
+
const assignees = item.content?.assignees?.nodes
|
|
375
|
+
?.map(a => a.login)
|
|
376
|
+
.filter(Boolean) || [];
|
|
377
|
+
|
|
378
|
+
// Extract labels from issue content (already fetched by the query)
|
|
379
|
+
const labels = item.content?.labels?.nodes
|
|
380
|
+
?.map(l => l.name)
|
|
381
|
+
.filter(Boolean) || [];
|
|
382
|
+
|
|
383
|
+
const entry = {
|
|
384
|
+
id: item.id,
|
|
385
|
+
title: item.content?.title || 'No title',
|
|
386
|
+
number: item.content?.number,
|
|
387
|
+
url: item.content?.url,
|
|
388
|
+
repo: item.content?.repository?.nameWithOwner || null,
|
|
389
|
+
private: item.content?.repository?.isPrivate ?? null,
|
|
390
|
+
fields
|
|
391
|
+
};
|
|
392
|
+
|
|
393
|
+
// Only include assignees and labels when non-empty to keep output compact
|
|
394
|
+
if (assignees.length > 0) entry.assignees = assignees;
|
|
395
|
+
if (labels.length > 0) entry.labels = labels;
|
|
396
|
+
|
|
397
|
+
return entry;
|
|
398
|
+
})
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
} catch (error) {
|
|
402
|
+
logger.error(`Error fetching items: ${error.message}`);
|
|
403
|
+
return {
|
|
404
|
+
status: 'error',
|
|
405
|
+
error: error.message
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Update a field value directly via GraphQL mutation
|
|
412
|
+
* @param {string} itemId - ID of the item to update
|
|
413
|
+
* @param {string} fieldId - ID of the field to update
|
|
414
|
+
* @param {Object} value - The value object for the mutation (e.g. { singleSelectOptionId }, { iterationId }, { date })
|
|
415
|
+
* @param {string} boardId - The GitHub project node ID
|
|
416
|
+
* @param {string} [token] - Optional per-request GitHub token
|
|
417
|
+
* @returns {Promise<Object>} - Update result
|
|
418
|
+
*/
|
|
419
|
+
export async function updateItemField(itemId, fieldId, value, boardId, token) {
|
|
420
|
+
return await graphQLWithAuth(UPDATE_ITEM_FIELD_MUTATION, {
|
|
421
|
+
projectId: boardId,
|
|
422
|
+
itemId: itemId,
|
|
423
|
+
fieldId: fieldId,
|
|
424
|
+
value
|
|
425
|
+
}, token);
|
|
426
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Logger Module
|
|
3
|
+
*
|
|
4
|
+
* Simple logger that writes all output to stderr to avoid interfering
|
|
5
|
+
* with the MCP stdio transport on stdout.
|
|
6
|
+
*
|
|
7
|
+
* Supports an optional second argument for structured data, e.g.:
|
|
8
|
+
* logger.info('Tool called', { tool: 'list_issues', filters: { team: 'foo' } });
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
function formatMessage(message, data) {
|
|
12
|
+
if (data !== undefined) {
|
|
13
|
+
try {
|
|
14
|
+
return `${message} ${JSON.stringify(data)}`;
|
|
15
|
+
} catch {
|
|
16
|
+
return `${message} [unserializable data]`;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return message;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export const logger = {
|
|
23
|
+
info: (message, data) => {
|
|
24
|
+
console.error(`[info] ${formatMessage(message, data)}`);
|
|
25
|
+
},
|
|
26
|
+
|
|
27
|
+
warn: (message, data) => {
|
|
28
|
+
console.error(`[warn] ${formatMessage(message, data)}`);
|
|
29
|
+
},
|
|
30
|
+
|
|
31
|
+
error: (message, data) => {
|
|
32
|
+
console.error(`[error] ${formatMessage(message, data)}`);
|
|
33
|
+
},
|
|
34
|
+
|
|
35
|
+
debug: (message, data) => {
|
|
36
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
37
|
+
console.error(`[debug] ${formatMessage(message, data)}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamable HTTP Transport for MCP Server
|
|
3
|
+
*
|
|
4
|
+
* Provides an Express-based HTTP server that exposes the MCP protocol via the
|
|
5
|
+
* Streamable HTTP transport specification. Used for remote/K8s deployment.
|
|
6
|
+
*
|
|
7
|
+
* When both GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET are set,
|
|
8
|
+
* enables OAuth 2.1 authentication:
|
|
9
|
+
* - MCP clients must authenticate via GitHub OAuth before using tools
|
|
10
|
+
* - OAuth endpoints: /authorize, /token, /register, /.well-known/*
|
|
11
|
+
* - GitHub callback: /github/callback
|
|
12
|
+
*
|
|
13
|
+
* When either GITHUB_OAUTH_CLIENT_ID or GITHUB_OAUTH_CLIENT_SECRET is NOT set,
|
|
14
|
+
* runs without auth (env var token mode).
|
|
15
|
+
*
|
|
16
|
+
* Each client session gets its own transport and MCP server instance,
|
|
17
|
+
* following the recommended pattern from the MCP SDK.
|
|
18
|
+
*
|
|
19
|
+
* Endpoints:
|
|
20
|
+
* POST/GET/DELETE /mcp - MCP streamable HTTP endpoint (auth required when OAuth enabled)
|
|
21
|
+
* GET /healthz - Liveness probe (always 200)
|
|
22
|
+
* GET /readyz - Readiness probe (200 when server is connected)
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import express from 'express';
|
|
26
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
27
|
+
import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
|
|
28
|
+
import { createMCPServer } from './server.js';
|
|
29
|
+
import { logger } from '../logger.js';
|
|
30
|
+
import { randomUUID } from 'crypto';
|
|
31
|
+
|
|
32
|
+
const DEFAULT_PORT = 8080;
|
|
33
|
+
const DEFAULT_ENDPOINT = '/mcp';
|
|
34
|
+
const SESSION_TTL_MS = 30 * 60 * 1000; // 30 minutes
|
|
35
|
+
const SESSION_SWEEP_INTERVAL_MS = 5 * 60 * 1000; // sweep every 5 minutes
|
|
36
|
+
|
|
37
|
+
let serverReady = false;
|
|
38
|
+
|
|
39
|
+
// Map of session ID -> { transport, lastActivity }
|
|
40
|
+
const sessions = {};
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Start the MCP server with streamable HTTP transport
|
|
44
|
+
* @param {Object} options
|
|
45
|
+
* @param {number} options.port - Port to listen on (default: 8080)
|
|
46
|
+
* @param {string} options.endpoint - MCP endpoint path (default: /mcp)
|
|
47
|
+
*/
|
|
48
|
+
export async function startHTTPServer(options = {}) {
|
|
49
|
+
const port = options.port || parseInt(process.env.HTTP_PORT, 10) || DEFAULT_PORT;
|
|
50
|
+
const endpoint = options.endpoint || DEFAULT_ENDPOINT;
|
|
51
|
+
|
|
52
|
+
const app = express();
|
|
53
|
+
// Trust exactly 1 proxy hop (Envoy Gateway). express-rate-limit requires
|
|
54
|
+
// a specific number rather than `true` to prevent IP spoofing.
|
|
55
|
+
app.set('trust proxy', 1);
|
|
56
|
+
app.use(express.json());
|
|
57
|
+
|
|
58
|
+
// ---------------------------------------------------------------------------
|
|
59
|
+
// OAuth 2.1 setup (when GITHUB_OAUTH_CLIENT_ID is configured)
|
|
60
|
+
// ---------------------------------------------------------------------------
|
|
61
|
+
const oauthClientId = process.env.GITHUB_OAUTH_CLIENT_ID;
|
|
62
|
+
const oauthClientSecret = process.env.GITHUB_OAUTH_CLIENT_SECRET;
|
|
63
|
+
let bearerAuthMiddleware = null;
|
|
64
|
+
|
|
65
|
+
if (oauthClientId && oauthClientSecret) {
|
|
66
|
+
const { mcpAuthRouter } = await import('@modelcontextprotocol/sdk/server/auth/router.js');
|
|
67
|
+
const { requireBearerAuth } = await import('@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js');
|
|
68
|
+
const { createGitHubOAuthProvider } = await import('../auth/provider.js');
|
|
69
|
+
|
|
70
|
+
const issuerUrl = new URL(process.env.OAUTH_ISSUER_URL || `http://localhost:${port}`);
|
|
71
|
+
|
|
72
|
+
const { provider, handleGitHubCallback } = createGitHubOAuthProvider({
|
|
73
|
+
clientId: oauthClientId,
|
|
74
|
+
clientSecret: oauthClientSecret
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// Mount OAuth routes: /authorize, /token, /register, /.well-known/*
|
|
78
|
+
app.use(mcpAuthRouter({
|
|
79
|
+
provider,
|
|
80
|
+
issuerUrl,
|
|
81
|
+
scopesSupported: ['repo', 'project', 'read:org'],
|
|
82
|
+
resourceName: 'Giant Swarm PRO MCP Server'
|
|
83
|
+
}));
|
|
84
|
+
|
|
85
|
+
// GitHub OAuth callback (not part of MCP spec — specific to our proxy)
|
|
86
|
+
app.get('/github/callback', handleGitHubCallback);
|
|
87
|
+
|
|
88
|
+
// Bearer auth middleware for the MCP endpoint
|
|
89
|
+
bearerAuthMiddleware = requireBearerAuth({ verifier: provider });
|
|
90
|
+
|
|
91
|
+
logger.info('OAuth 2.1 enabled — MCP clients must authenticate via GitHub');
|
|
92
|
+
} else {
|
|
93
|
+
logger.info('OAuth not configured — using GITHUB_API_TOKEN for all requests');
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
// Health probes (no auth required)
|
|
98
|
+
// ---------------------------------------------------------------------------
|
|
99
|
+
|
|
100
|
+
// Health check: liveness (no auth required)
|
|
101
|
+
app.get('/healthz', (req, res) => {
|
|
102
|
+
res.json({ status: 'ok' });
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Health check: readiness (no auth required)
|
|
106
|
+
app.get('/readyz', (req, res) => {
|
|
107
|
+
if (serverReady) {
|
|
108
|
+
res.json({ status: 'ready' });
|
|
109
|
+
} else {
|
|
110
|
+
res.status(503).json({ status: 'not ready' });
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
// ---------------------------------------------------------------------------
|
|
115
|
+
// MCP endpoint
|
|
116
|
+
// ---------------------------------------------------------------------------
|
|
117
|
+
|
|
118
|
+
// MCP endpoint — handles POST, GET (SSE), and DELETE (session teardown)
|
|
119
|
+
// When OAuth is enabled, Bearer auth is required
|
|
120
|
+
if (bearerAuthMiddleware) {
|
|
121
|
+
app.all(endpoint, bearerAuthMiddleware);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
app.all(endpoint, async (req, res) => {
|
|
125
|
+
try {
|
|
126
|
+
// Look up existing session
|
|
127
|
+
const sessionId = req.headers['mcp-session-id'];
|
|
128
|
+
let transport;
|
|
129
|
+
|
|
130
|
+
if (sessionId && sessions[sessionId]) {
|
|
131
|
+
// Reuse existing transport for this session
|
|
132
|
+
sessions[sessionId].lastActivity = Date.now();
|
|
133
|
+
transport = sessions[sessionId].transport;
|
|
134
|
+
} else if (req.method === 'POST' && !sessionId && isInitializeRequest(req.body)) {
|
|
135
|
+
// New initialization request — create a new transport and server
|
|
136
|
+
transport = new StreamableHTTPServerTransport({
|
|
137
|
+
sessionIdGenerator: () => randomUUID(),
|
|
138
|
+
onsessioninitialized: (id) => {
|
|
139
|
+
logger.info(`Session initialized: ${id}`);
|
|
140
|
+
sessions[id] = { transport, lastActivity: Date.now() };
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
transport.onclose = () => {
|
|
145
|
+
const sid = transport.sessionId;
|
|
146
|
+
if (sid && sessions[sid]) {
|
|
147
|
+
logger.info(`Session closed: ${sid}`);
|
|
148
|
+
delete sessions[sid];
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const mcpServer = createMCPServer();
|
|
153
|
+
await mcpServer.connect(transport);
|
|
154
|
+
|
|
155
|
+
await transport.handleRequest(req, res, req.body);
|
|
156
|
+
return;
|
|
157
|
+
} else if (sessionId) {
|
|
158
|
+
// Session ID provided but not found — expired or invalid
|
|
159
|
+
res.status(400).json({
|
|
160
|
+
jsonrpc: '2.0',
|
|
161
|
+
error: {
|
|
162
|
+
code: -32000,
|
|
163
|
+
message: 'Session not found or expired'
|
|
164
|
+
},
|
|
165
|
+
id: null
|
|
166
|
+
});
|
|
167
|
+
return;
|
|
168
|
+
} else {
|
|
169
|
+
// No session ID and not an initialize request
|
|
170
|
+
res.status(400).json({
|
|
171
|
+
jsonrpc: '2.0',
|
|
172
|
+
error: {
|
|
173
|
+
code: -32000,
|
|
174
|
+
message: 'Bad Request: missing session ID or not an initialize request'
|
|
175
|
+
},
|
|
176
|
+
id: null
|
|
177
|
+
});
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
await transport.handleRequest(req, res, req.body);
|
|
182
|
+
} catch (err) {
|
|
183
|
+
logger.error(`HTTP transport error: ${err.message}`);
|
|
184
|
+
if (!res.headersSent) {
|
|
185
|
+
res.status(500).json({ error: 'Internal server error' });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
serverReady = true;
|
|
191
|
+
|
|
192
|
+
// Periodic sweep to evict idle sessions
|
|
193
|
+
const sweepInterval = setInterval(() => {
|
|
194
|
+
const now = Date.now();
|
|
195
|
+
for (const sessionId in sessions) {
|
|
196
|
+
if (now - sessions[sessionId].lastActivity > SESSION_TTL_MS) {
|
|
197
|
+
logger.info(`Evicting idle session: ${sessionId}`);
|
|
198
|
+
try {
|
|
199
|
+
sessions[sessionId].transport.close();
|
|
200
|
+
} catch (err) {
|
|
201
|
+
logger.error(`Error closing idle session ${sessionId}: ${err.message}`);
|
|
202
|
+
}
|
|
203
|
+
delete sessions[sessionId];
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}, SESSION_SWEEP_INTERVAL_MS);
|
|
207
|
+
sweepInterval.unref();
|
|
208
|
+
|
|
209
|
+
// Start listening
|
|
210
|
+
const httpServer = app.listen(port, () => {
|
|
211
|
+
logger.info(`MCP HTTP server listening on port ${port} (endpoint: ${endpoint})`);
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
// Graceful shutdown
|
|
215
|
+
const shutdown = async () => {
|
|
216
|
+
logger.info('Shutting down HTTP server...');
|
|
217
|
+
serverReady = false;
|
|
218
|
+
clearInterval(sweepInterval);
|
|
219
|
+
for (const sessionId in sessions) {
|
|
220
|
+
try {
|
|
221
|
+
await sessions[sessionId].transport.close();
|
|
222
|
+
delete sessions[sessionId];
|
|
223
|
+
} catch (err) {
|
|
224
|
+
logger.error(`Error closing session ${sessionId}: ${err.message}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
httpServer.close();
|
|
228
|
+
process.exit(0);
|
|
229
|
+
};
|
|
230
|
+
|
|
231
|
+
process.on('SIGINT', shutdown);
|
|
232
|
+
process.on('SIGTERM', shutdown);
|
|
233
|
+
}
|