@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,304 @@
1
+ /**
2
+ * MCP Resources Implementation
3
+ *
4
+ * Exposes per-board resources providing context about project boards:
5
+ * - {board}://schema: Compact field schema with valid option values, repository guidance, and content policy
6
+ * - {board}://overview: Board-level stats (issue counts, status and repository distribution)
7
+ *
8
+ * Supported boards: roadmap, customer
9
+ */
10
+
11
+ import { listFields } from '../fields.js';
12
+ import { fetchPaginated } from '../api.js';
13
+ import { BOARDS, LIST_ITEMS_OVERVIEW_QUERY } from '../project.js';
14
+ import { logger } from '../logger.js';
15
+
16
+ /**
17
+ * Board-specific repository documentation for the schema resource.
18
+ * Helps the LLM understand which repositories exist on each board,
19
+ * how to use the `repository` filter on `list_issues`, and the
20
+ * content policy for each repository.
21
+ */
22
+ const REPOSITORY_SCHEMA = {
23
+ roadmap: {
24
+ repositories: [
25
+ { name: 'giantswarm/roadmap', visibility: 'public', usage: 'Sanitized, public-safe issues only.' },
26
+ { name: 'giantswarm/giantswarm', visibility: 'private', usage: 'Internal issues and customer-specific operational context.' }
27
+ ],
28
+ policy: [
29
+ 'Use giantswarm/roadmap only for sanitized, public-safe content.',
30
+ 'Never include customer-specific or internal-sensitive details in public issues.',
31
+ 'Use giantswarm/giantswarm for internal issues and customer-specific operational context.'
32
+ ]
33
+ },
34
+ customer: {
35
+ repositoryPattern: 'giantswarm/<customer-name>',
36
+ policy: [
37
+ 'Customer board issues live in private customer-specific repositories (e.g. giantswarm/<customer>).',
38
+ 'The customer project board itself is a public GitHub project, but issue content is only visible to users with access to the private repository.',
39
+ 'Giant Swarm staff can see all issues; customers can only see issues from their own repository.',
40
+ 'Never move customer-specific issue content into public repositories.'
41
+ ]
42
+ }
43
+ };
44
+
45
+ /**
46
+ * Project field data types that don't have enumerable option values.
47
+ * These are skipped from the schema's `fields` map because they can't be
48
+ * used with the generic `filters` parameter on list_issues.
49
+ *
50
+ * Note: some of these (ASSIGNEES, LABELS, REPOSITORY) ARE filterable via
51
+ * dedicated parameters on list_issues — those are documented separately
52
+ * in the schema's `issueFilters` section.
53
+ */
54
+ const SKIP_DATA_TYPES = new Set([
55
+ 'TITLE', 'ASSIGNEES', 'LABELS', 'LINKED_PULL_REQUESTS',
56
+ 'REVIEWERS', 'REPOSITORY', 'MILESTONE', 'PARENT_ISSUE', 'SUB_ISSUES_PROGRESS'
57
+ ]);
58
+
59
+ /**
60
+ * Generate the schema resource for a board.
61
+ * Compact field schema: only actionable fields, no internal IDs, no empty values.
62
+ * Organised by category so the LLM can quickly find valid filter/update values.
63
+ *
64
+ * @param {string} boardKey - Board key (e.g. "roadmap", "customer")
65
+ * @param {string} [token] - Optional per-request GitHub token
66
+ * @returns {Promise<Object>} - MCP resource response
67
+ */
68
+ async function getSchemaResource(boardKey, token) {
69
+ const board = BOARDS[boardKey];
70
+ if (!board) {
71
+ throw new Error(`Unknown board '${boardKey}'. Valid boards: ${Object.keys(BOARDS).join(', ')}`);
72
+ }
73
+ try {
74
+ logger.info(`MCP: Generating schema resource for ${boardKey} board`);
75
+
76
+ const fields = await listFields(board.id, token);
77
+
78
+ // Categorise fields with enumerable options (skip types without option values)
79
+ const selectFields = {};
80
+ const hints = {};
81
+ const dateFields = [];
82
+ const textFields = [];
83
+ const iterationFields = {};
84
+
85
+ for (const field of fields) {
86
+ if (SKIP_DATA_TYPES.has(field.dataType)) continue;
87
+
88
+ if (field.__typename === 'ProjectV2SingleSelectField' && field.options?.length) {
89
+ selectFields[field.name] = field.options.map(opt => opt.name);
90
+
91
+ // Collect non-empty option descriptions as hints (e.g. team responsibilities)
92
+ const fieldHints = {};
93
+ let hasHints = false;
94
+ for (const opt of field.options) {
95
+ if (opt.description?.trim()) {
96
+ fieldHints[opt.name] = opt.description.trim();
97
+ hasHints = true;
98
+ }
99
+ }
100
+ if (hasHints) hints[field.name] = fieldHints;
101
+ } else if (field.dataType === 'DATE') {
102
+ dateFields.push(field.name);
103
+ } else if (field.dataType === 'TEXT') {
104
+ textFields.push(field.name);
105
+ } else if (field.__typename === 'ProjectV2IterationField') {
106
+ const iterations = field.configuration?.iterations || [];
107
+ iterationFields[field.name] = iterations.map(iter => iter.title);
108
+ }
109
+ }
110
+
111
+ // Build compact schema — only include non-empty sections
112
+ const schema = { fields: selectFields };
113
+ if (Object.keys(hints).length) schema.hints = hints;
114
+ if (dateFields.length) schema.dateFields = dateFields;
115
+ if (textFields.length) schema.textFields = textFields;
116
+ if (Object.keys(iterationFields).length) schema.iterationFields = iterationFields;
117
+
118
+ // Document issue-level filters (not project fields, but available on list_issues)
119
+ schema.issueFilters = {
120
+ repository: 'Short name (e.g. "myrepo") or full "owner/name". See repos/repoPattern below for valid values.',
121
+ assignee: 'GitHub username (e.g. "octocat"). Comma-separated for OR matching.',
122
+ label: 'Label name (e.g. "bug"). Comma-separated for OR matching.',
123
+ state: '"open" or "closed"',
124
+ keyword: 'Free text search on titles and text fields (word-prefix matching)',
125
+ updated: 'Last-updated date filter. Examples: ">@today-7d" (last 7 days), "<@today-30d" (older than 30 days), "@today" (today), ">2025-01-01" (after date)',
126
+ reason: '"completed", "not planned", or "reopened" (close reason for closed items)'
127
+ };
128
+
129
+ // Compact repository info
130
+ const repoInfo = REPOSITORY_SCHEMA[boardKey];
131
+ if (repoInfo) {
132
+ if (repoInfo.repositories?.length) {
133
+ schema.repos = {};
134
+ for (const repo of repoInfo.repositories) {
135
+ schema.repos[repo.name] = `${repo.visibility}, ${repo.usage}`;
136
+ }
137
+ }
138
+ if (repoInfo.repositoryPattern) {
139
+ schema.repoPattern = repoInfo.repositoryPattern;
140
+ }
141
+ if (repoInfo.policy?.length) {
142
+ schema.policy = repoInfo.policy.join(' ');
143
+ }
144
+ }
145
+
146
+ return {
147
+ contents: [{
148
+ uri: `${boardKey}://schema`,
149
+ mimeType: 'application/json',
150
+ text: JSON.stringify(schema)
151
+ }]
152
+ };
153
+ } catch (error) {
154
+ logger.error(`MCP: Error generating schema resource for ${boardKey}`, { error: error.message });
155
+ throw error;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Generate the overview resource for a board.
161
+ * Board-level stats: total items, status distribution, repository distribution.
162
+ *
163
+ * Uses a lightweight GraphQL query (Status + repository only) instead of
164
+ * the full listItems() to stay within the 60-second MCP resource timeout
165
+ * on large boards (the roadmap board has thousands of items).
166
+ *
167
+ * @param {string} boardKey - Board key (e.g. "roadmap", "customer")
168
+ * @param {string} [token] - Optional per-request GitHub token
169
+ * @returns {Promise<Object>} - MCP resource response
170
+ */
171
+ async function getOverviewResource(boardKey, token) {
172
+ const board = BOARDS[boardKey];
173
+ if (!board) {
174
+ throw new Error(`Unknown board '${boardKey}'. Valid boards: ${Object.keys(BOARDS).join(', ')}`);
175
+ }
176
+ try {
177
+ logger.info(`MCP: Generating overview resource for ${boardKey} board`);
178
+
179
+ const allItems = await fetchPaginated(
180
+ LIST_ITEMS_OVERVIEW_QUERY,
181
+ { projectId: board.id, first: 100 },
182
+ result => {
183
+ if (!result?.node?.items) {
184
+ return { nodes: [], pageInfo: { hasNextPage: false } };
185
+ }
186
+ return {
187
+ nodes: result.node.items.nodes || [],
188
+ pageInfo: result.node.items.pageInfo || { hasNextPage: false }
189
+ };
190
+ },
191
+ token
192
+ );
193
+
194
+ // Build distributions from lightweight item data
195
+ const statusCounts = {};
196
+ const repositoryDistribution = {};
197
+ let totalIssues = 0;
198
+
199
+ for (const item of allItems) {
200
+ // Skip items without content (drafts) or without a title
201
+ if (!item.content?.title) continue;
202
+ totalIssues++;
203
+
204
+ // Extract Status from single-select field values
205
+ let status = 'Unknown';
206
+ if (item.fieldValues?.nodes) {
207
+ for (const fv of item.fieldValues.nodes) {
208
+ if (fv.field?.name === 'Status' && fv.name) {
209
+ status = fv.name;
210
+ break;
211
+ }
212
+ }
213
+ }
214
+ statusCounts[status] = (statusCounts[status] || 0) + 1;
215
+
216
+ const repoName = item.content?.repository?.nameWithOwner || 'unknown';
217
+ repositoryDistribution[repoName] = (repositoryDistribution[repoName] || 0) + 1;
218
+ }
219
+
220
+ const overview = {
221
+ board: boardKey,
222
+ boardName: board.name,
223
+ projectId: board.id,
224
+ totalIssues,
225
+ statusDistribution: statusCounts,
226
+ repositoryDistribution,
227
+ lastUpdated: new Date().toISOString()
228
+ };
229
+
230
+ return {
231
+ contents: [{
232
+ uri: `${boardKey}://overview`,
233
+ mimeType: 'application/json',
234
+ text: JSON.stringify(overview)
235
+ }]
236
+ };
237
+ } catch (error) {
238
+ logger.error(`MCP: Error generating overview resource for ${boardKey}`, { error: error.message });
239
+ throw error;
240
+ }
241
+ }
242
+
243
+ /**
244
+ * List all available resources (one schema + one overview per board)
245
+ */
246
+ export async function listResources() {
247
+ const resources = [];
248
+
249
+ for (const [boardKey, board] of Object.entries(BOARDS)) {
250
+ resources.push(
251
+ {
252
+ uri: `${boardKey}://schema`,
253
+ name: `${board.name} Field Schema`,
254
+ description: `Compact schema of the ${board.name}: single-select field names with valid option values, date/text/iteration fields, issue-level filters (assignee, label, state, keyword, updated, reason), repository guidance, and content policy. Read this first to discover valid field names and filter parameters.`,
255
+ mimeType: 'application/json'
256
+ },
257
+ {
258
+ uri: `${boardKey}://overview`,
259
+ name: `${board.name} Overview`,
260
+ description: `High-level overview of the ${board.name} including total items, status distribution, and repository distribution.`,
261
+ mimeType: 'application/json'
262
+ }
263
+ );
264
+ }
265
+
266
+ return { resources };
267
+ }
268
+
269
+ /**
270
+ * Read a specific resource by URI
271
+ * @param {string} uri - Resource URI
272
+ * @param {Object} [extra] - MCP request extra context (contains authInfo for HTTP transport)
273
+ */
274
+ export async function readResource(uri, extra) {
275
+ try {
276
+ const token = extra?.authInfo?.token;
277
+ logger.info('MCP: Reading resource', { uri });
278
+
279
+ // Parse URI: expected format is "{boardKey}://schema" or "{boardKey}://overview"
280
+ const match = uri.match(/^([\w-]+):\/\/([\w-]+)$/);
281
+ if (!match) {
282
+ throw new Error(`Invalid resource URI format: ${uri}`);
283
+ }
284
+
285
+ const [, boardKey, resourceType] = match;
286
+
287
+ if (!BOARDS[boardKey]) {
288
+ throw new Error(`Unknown board '${boardKey}' in resource URI: ${uri}. Valid boards: ${Object.keys(BOARDS).join(', ')}`);
289
+ }
290
+
291
+ if (resourceType === 'schema') {
292
+ return await getSchemaResource(boardKey, token);
293
+ }
294
+
295
+ if (resourceType === 'overview') {
296
+ return await getOverviewResource(boardKey, token);
297
+ }
298
+
299
+ throw new Error(`Unknown resource type '${resourceType}' in URI: ${uri}`);
300
+ } catch (error) {
301
+ logger.error('MCP: Error reading resource', { uri, error: error.message });
302
+ throw error;
303
+ }
304
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * MCP Server Implementation
3
+ *
4
+ * WHY:
5
+ * - Provides a Model Context Protocol server for AI assistant integration
6
+ * - Enables AI-powered interaction with Giant Swarm project boards
7
+ * - Allows conversational access to all roadmap management features
8
+ *
9
+ * HOW:
10
+ * - Uses @modelcontextprotocol/sdk to implement MCP server
11
+ * - Exposes tools and resources for AI consumption
12
+ * - Runs as a stdio server for integration with AI assistants
13
+ *
14
+ * WHAT:
15
+ * - Exports createMCPServer function to initialize the server
16
+ * - Registers all tools and resources
17
+ * - Handles tool calls and resource requests
18
+ * - Provides error handling and logging
19
+ */
20
+
21
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
22
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
23
+ import {
24
+ CallToolRequestSchema,
25
+ ListResourcesRequestSchema,
26
+ ListToolsRequestSchema,
27
+ ReadResourceRequestSchema
28
+ } from '@modelcontextprotocol/sdk/types.js';
29
+
30
+ import { tools, toolHandlers } from './tools.js';
31
+ import { listResources, readResource } from './resources.js';
32
+ import { logger } from '../logger.js';
33
+ import { version } from '../version.js';
34
+
35
+ /**
36
+ * Create and configure the MCP server
37
+ * @returns {Server} - Configured MCP server instance
38
+ */
39
+ export function createMCPServer() {
40
+ const server = new Server(
41
+ {
42
+ name: 'giantswarm-pro',
43
+ version
44
+ },
45
+ {
46
+ capabilities: {
47
+ tools: {},
48
+ resources: {}
49
+ }
50
+ }
51
+ );
52
+
53
+ /**
54
+ * Handler: list_tools
55
+ * Returns the list of available tools
56
+ */
57
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
58
+ // Routine operation - no logging needed
59
+ return { tools };
60
+ });
61
+
62
+ /**
63
+ * Handler: call_tool
64
+ * Executes a requested tool
65
+ */
66
+ server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
67
+ const { name, arguments: args } = request.params;
68
+
69
+ // Only log tool name, not full args (reduces noise)
70
+ logger.info(`MCP: Tool called: ${name}`);
71
+
72
+ const handler = toolHandlers[name];
73
+
74
+ if (!handler) {
75
+ logger.error('MCP: Unknown tool', { tool: name });
76
+ throw new Error(`Unknown tool: ${name}`);
77
+ }
78
+
79
+ try {
80
+ const result = await handler(args || {}, extra);
81
+
82
+ // If result has an error, throw it
83
+ if (result.error) {
84
+ throw new Error(result.error);
85
+ }
86
+
87
+ return result;
88
+ } catch (error) {
89
+ logger.error('MCP: Tool execution error', {
90
+ tool: name,
91
+ error: error.message
92
+ });
93
+
94
+ return {
95
+ content: [{
96
+ type: 'text',
97
+ text: `Error: ${error.message}`
98
+ }],
99
+ isError: true
100
+ };
101
+ }
102
+ });
103
+
104
+ /**
105
+ * Handler: list_resources
106
+ * Returns the list of available resources
107
+ */
108
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
109
+ // Routine operation - no logging needed
110
+ return await listResources();
111
+ });
112
+
113
+ /**
114
+ * Handler: read_resource
115
+ * Reads a specific resource
116
+ */
117
+ server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
118
+ const { uri } = request.params;
119
+
120
+ logger.info(`MCP: Reading resource: ${uri}`);
121
+
122
+ try {
123
+ return await readResource(uri, extra);
124
+ } catch (error) {
125
+ logger.error('MCP: Resource read error', {
126
+ uri,
127
+ error: error.message
128
+ });
129
+
130
+ throw error;
131
+ }
132
+ });
133
+
134
+ return server;
135
+ }
136
+
137
+ /**
138
+ * Start the MCP server with stdio transport
139
+ */
140
+ export async function startMCPServer() {
141
+ const server = createMCPServer();
142
+ const transport = new StdioServerTransport();
143
+
144
+ await server.connect(transport);
145
+
146
+ // Handle process termination
147
+ process.on('SIGINT', async () => {
148
+ await server.close();
149
+ process.exit(0);
150
+ });
151
+
152
+ process.on('SIGTERM', async () => {
153
+ await server.close();
154
+ process.exit(0);
155
+ });
156
+ }