@primer/mcp 0.2.0 → 0.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,1525 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import * as cheerio from 'cheerio';
3
+ import * as z from 'zod';
4
+ import TurndownService from 'turndown';
5
+ import componentsMetadata from '@primer/react/generated/components.json' with { type: 'json' };
6
+ import octicons from '@primer/octicons/build/data.json' with { type: 'json' };
7
+ import { readFileSync } from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import { spawn } from 'child_process';
10
+ import baseMotion from '@primer/primitives/dist/docs/base/motion/motion.json' with { type: 'json' };
11
+ import baseSize from '@primer/primitives/dist/docs/base/size/size.json' with { type: 'json' };
12
+ import baseTypography from '@primer/primitives/dist/docs/base/typography/typography.json' with { type: 'json' };
13
+ import functionalSizeBorder from '@primer/primitives/dist/docs/functional/size/border.json' with { type: 'json' };
14
+ import functionalSizeCoarse from '@primer/primitives/dist/docs/functional/size/size-coarse.json' with { type: 'json' };
15
+ import functionalSizeFine from '@primer/primitives/dist/docs/functional/size/size-fine.json' with { type: 'json' };
16
+ import functionalSize from '@primer/primitives/dist/docs/functional/size/size.json' with { type: 'json' };
17
+ import light from '@primer/primitives/dist/docs/functional/themes/light.json' with { type: 'json' };
18
+ import functionalTypography from '@primer/primitives/dist/docs/functional/typography/typography.json' with { type: 'json' };
19
+
20
+ function idToSlug(id) {
21
+ if (id === 'actionbar') {
22
+ return 'action-bar';
23
+ }
24
+ if (id === 'tooltip-v2') {
25
+ return 'tooltip';
26
+ }
27
+ if (id === 'dialog_v2') {
28
+ return 'dialog';
29
+ }
30
+ return id.replaceAll('_', '-');
31
+ }
32
+ const components = Object.entries(componentsMetadata.components).map(([id, component]) => {
33
+ return {
34
+ id,
35
+ name: component.name,
36
+ importPath: component.importPath,
37
+ slug: idToSlug(id)
38
+ };
39
+ });
40
+ function listComponents() {
41
+ return components;
42
+ }
43
+ const patterns = [{
44
+ id: 'data-visualization',
45
+ name: 'Data Visualization'
46
+ }, {
47
+ id: 'degraded-experiences',
48
+ name: 'Degraded Experiences'
49
+ }, {
50
+ id: 'empty-states',
51
+ name: 'Empty States'
52
+ }, {
53
+ id: 'feature-onboarding',
54
+ name: 'Feature Onboarding'
55
+ }, {
56
+ id: 'forms',
57
+ name: 'Forms'
58
+ }, {
59
+ id: 'loading',
60
+ name: 'Loading'
61
+ }, {
62
+ id: 'navigation',
63
+ name: 'Navigation'
64
+ }, {
65
+ id: 'notification-messaging',
66
+ name: 'Notification message'
67
+ }, {
68
+ id: 'progressive-disclosure',
69
+ name: 'Progressive disclosure'
70
+ }, {
71
+ id: 'saving',
72
+ name: 'Saving'
73
+ }];
74
+ function listPatterns() {
75
+ return patterns;
76
+ }
77
+ const icons = Object.values(octicons).map(icon => {
78
+ return {
79
+ name: icon.name,
80
+ keywords: icon.keywords,
81
+ heights: Object.keys(icon.heights)
82
+ };
83
+ });
84
+ function listIcons() {
85
+ return icons;
86
+ }
87
+
88
+ // radius.json may not exist in all versions of @primer/primitives
89
+ let functionalSizeRadius = {};
90
+ try {
91
+ const require = createRequire(import.meta.url);
92
+ const radiusPath = require.resolve('@primer/primitives/dist/docs/functional/size/radius.json');
93
+ functionalSizeRadius = JSON.parse(readFileSync(radiusPath, 'utf-8'));
94
+ } catch {
95
+ // radius.json not available in this version of @primer/primitives
96
+ }
97
+ const categories = {
98
+ base: {
99
+ motion: Object.values(baseMotion).map(token => {
100
+ return {
101
+ name: token.name,
102
+ type: token.type,
103
+ value: token.value
104
+ };
105
+ }),
106
+ size: Object.values(baseSize).map(token => {
107
+ return {
108
+ name: token.name,
109
+ type: token.type,
110
+ value: token.value
111
+ };
112
+ }),
113
+ typography: Object.values(baseTypography).map(token => {
114
+ return {
115
+ name: token.name,
116
+ type: token.type,
117
+ value: token.value
118
+ };
119
+ })
120
+ },
121
+ functional: {
122
+ border: Object.values(functionalSizeBorder).map(token => {
123
+ return {
124
+ name: token.name,
125
+ type: token.type,
126
+ value: token.value
127
+ };
128
+ }),
129
+ radius: Object.values(functionalSizeRadius).map(token => {
130
+ return {
131
+ name: token.name,
132
+ type: token.type,
133
+ value: token.value
134
+ };
135
+ }),
136
+ sizeCoarse: Object.values(functionalSizeCoarse).map(token => {
137
+ return {
138
+ name: token.name,
139
+ type: token.type,
140
+ value: token.value
141
+ };
142
+ }),
143
+ sizeFine: Object.values(functionalSizeFine).map(token => {
144
+ return {
145
+ name: token.name,
146
+ type: token.type,
147
+ value: token.value
148
+ };
149
+ }),
150
+ size: Object.values(functionalSize).map(token => {
151
+ return {
152
+ name: token.name,
153
+ type: token.type,
154
+ value: token.value
155
+ };
156
+ }),
157
+ themes: {
158
+ light: Object.values(light).map(token => {
159
+ return {
160
+ name: token.name,
161
+ type: token.type,
162
+ value: token.value
163
+ };
164
+ })
165
+ },
166
+ typography: Object.values(functionalTypography).map(token => {
167
+ return {
168
+ name: token.name,
169
+ type: token.type,
170
+ value: token.value
171
+ };
172
+ })
173
+ }
174
+ };
175
+ const tokens = [...categories.base.motion, ...categories.base.size, ...categories.base.typography, ...categories.functional.border, ...categories.functional.radius, ...categories.functional.sizeCoarse, ...categories.functional.sizeFine, ...categories.functional.size, ...categories.functional.themes.light, ...categories.functional.typography];
176
+
177
+ // Semantic group prefixes that apply to any element
178
+ const SEMANTIC_PREFIXES = ['bgColor', 'fgColor', 'border', 'borderColor', 'shadow', 'focus', 'color', 'animation', 'duration'];
179
+ function listTokenGroups() {
180
+ // Use the full token set so non-theme groups (stack, text, borderRadius, etc.) are included
181
+ const allTokens = tokens;
182
+
183
+ // Group tokens by their first segment
184
+ const groupMap = new Map();
185
+ for (const token of allTokens) {
186
+ const parts = token.name.split('-');
187
+ const prefix = parts[0];
188
+ if (!groupMap.has(prefix)) {
189
+ groupMap.set(prefix, {
190
+ count: 0,
191
+ subGroups: new Set()
192
+ });
193
+ }
194
+ const group = groupMap.get(prefix);
195
+ group.count++;
196
+
197
+ // For component tokens, track sub-groups (e.g., button-bgColor -> bgColor)
198
+ if (!SEMANTIC_PREFIXES.includes(prefix) && parts.length > 1) {
199
+ const subGroup = parts[1];
200
+ if (SEMANTIC_PREFIXES.includes(subGroup)) {
201
+ group.subGroups.add(subGroup);
202
+ }
203
+ }
204
+ }
205
+ const semantic = [];
206
+ const component = [];
207
+ for (const [name, data] of groupMap.entries()) {
208
+ const group = {
209
+ name,
210
+ count: data.count
211
+ };
212
+ if (data.subGroups.size > 0) {
213
+ group.subGroups = Array.from(data.subGroups).sort();
214
+ }
215
+ if (SEMANTIC_PREFIXES.includes(name)) {
216
+ semantic.push(group);
217
+ } else {
218
+ component.push(group);
219
+ }
220
+ }
221
+
222
+ // Sort by count descending
223
+ semantic.sort((a, b) => b.count - a.count);
224
+ component.sort((a, b) => b.count - a.count);
225
+ return {
226
+ semantic,
227
+ component
228
+ };
229
+ }
230
+
231
+ // Token with guidelines from markdown
232
+
233
+ // Parse design tokens spec from new DESIGN_TOKENS_SPEC.md format
234
+ function parseDesignTokensSpec(markdown) {
235
+ const results = [];
236
+ const lines = markdown.split('\n');
237
+ let currentGroup = '';
238
+ let currentToken = null;
239
+ let descriptionLines = [];
240
+ for (const line of lines) {
241
+ // Match group headings (## heading)
242
+ const groupMatch = line.match(/^## (.+)$/);
243
+ if (groupMatch) {
244
+ // Save previous token if exists
245
+ if (currentToken?.name) {
246
+ results.push({
247
+ name: currentToken.name,
248
+ value: getTokenValue(currentToken.name),
249
+ useCase: currentToken.useCase || descriptionLines.join(' '),
250
+ rules: currentToken.rules || '',
251
+ group: currentToken.group || ''
252
+ });
253
+ descriptionLines = [];
254
+ }
255
+ currentGroup = groupMatch[1].trim();
256
+ currentToken = null;
257
+ continue;
258
+ }
259
+
260
+ // Match token name (### tokenName)
261
+ const tokenMatch = line.match(/^### (.+)$/);
262
+ if (tokenMatch) {
263
+ // Save previous token if exists
264
+ if (currentToken?.name) {
265
+ results.push({
266
+ name: currentToken.name,
267
+ value: getTokenValue(currentToken.name),
268
+ useCase: currentToken.useCase || descriptionLines.join(' '),
269
+ rules: currentToken.rules || '',
270
+ group: currentToken.group || ''
271
+ });
272
+ }
273
+ descriptionLines = [];
274
+ currentToken = {
275
+ name: tokenMatch[1].trim(),
276
+ group: currentGroup
277
+ };
278
+ continue;
279
+ }
280
+
281
+ // Match new format usage line (**U:**)
282
+ const newUsageMatch = line.match(/^\*\*U:\*\*\s*(.+)$/);
283
+ if (newUsageMatch && currentToken) {
284
+ currentToken.useCase = newUsageMatch[1].trim();
285
+ continue;
286
+ }
287
+
288
+ // Match new format rules line (**R:**)
289
+ const newRulesMatch = line.match(/^\*\*R:\*\*\s*(.+)$/);
290
+ if (newRulesMatch && currentToken) {
291
+ currentToken.rules = newRulesMatch[1].trim();
292
+ continue;
293
+ }
294
+
295
+ // Description line (line after token name, before U:/R:)
296
+ if (currentToken && !currentToken.useCase && !line.startsWith('**') && line.trim() && !line.startsWith('#')) {
297
+ descriptionLines.push(line.trim());
298
+ }
299
+ }
300
+
301
+ // Don't forget the last token
302
+ if (currentToken?.name) {
303
+ results.push({
304
+ name: currentToken.name,
305
+ value: getTokenValue(currentToken.name),
306
+ useCase: currentToken.useCase || descriptionLines.join(' '),
307
+ rules: currentToken.rules || '',
308
+ group: currentToken.group || ''
309
+ });
310
+ }
311
+ return results;
312
+ }
313
+
314
+ // Get token value from the loaded tokens
315
+ function getTokenValue(tokenName) {
316
+ const found = tokens.find(token => token.name === tokenName);
317
+ return found ? String(found.value) : '';
318
+ }
319
+
320
+ // Human-readable display labels for canonical group prefixes
321
+ const GROUP_LABELS = {
322
+ bgColor: 'Background Color',
323
+ fgColor: 'Foreground Color',
324
+ borderColor: 'Border Color',
325
+ border: 'Border',
326
+ shadow: 'Shadow',
327
+ focus: 'Focus',
328
+ color: 'Color',
329
+ borderWidth: 'Border Width',
330
+ borderRadius: 'Border Radius',
331
+ boxShadow: 'Box Shadow',
332
+ controlStack: 'Control Stack',
333
+ fontStack: 'Font Stack',
334
+ outline: 'Outline',
335
+ text: 'Text',
336
+ control: 'Control',
337
+ overlay: 'Overlay',
338
+ stack: 'Stack',
339
+ spinner: 'Spinner'
340
+ };
341
+
342
+ // Get canonical group prefix from token name
343
+ function getGroupFromName(name) {
344
+ return name.split('-')[0];
345
+ }
346
+
347
+ // Build complete token list from JSON (includes all tokens, not just those with guidelines)
348
+ function buildAllTokens(guidelinesTokens) {
349
+ const guidelinesMap = new Map(guidelinesTokens.map(t => [t.name, t]));
350
+
351
+ // Include theme tokens AND size/typography/border tokens
352
+ const allSourceTokens = [...categories.base.motion, ...categories.base.size, ...categories.base.typography, ...categories.functional.themes.light, ...categories.functional.size, ...categories.functional.sizeCoarse, ...categories.functional.sizeFine, ...categories.functional.border, ...categories.functional.radius, ...categories.functional.typography];
353
+ const allTokens = [];
354
+ const seen = new Set();
355
+ for (const token of allSourceTokens) {
356
+ if (seen.has(token.name)) continue;
357
+ seen.add(token.name);
358
+ const existing = guidelinesMap.get(token.name);
359
+ if (existing) {
360
+ allTokens.push(existing);
361
+ } else {
362
+ allTokens.push({
363
+ name: token.name,
364
+ value: String(token.value),
365
+ useCase: '',
366
+ rules: '',
367
+ group: getGroupFromName(token.name)
368
+ });
369
+ }
370
+ }
371
+ return allTokens;
372
+ }
373
+
374
+ // Expand token patterns like [accent, danger] into multiple tokens
375
+ function expandTokenPattern(token) {
376
+ const bracketRegex = /\[(.*?)\]/;
377
+ const match = token.name.match(bracketRegex);
378
+ if (!match) return [token];
379
+ const variants = match[1].split(',').map(s => s.trim());
380
+ return variants.map(variant => ({
381
+ ...token,
382
+ name: token.name.replace(bracketRegex, variant)
383
+ }));
384
+ }
385
+
386
+ // Load and parse token guidelines, then build complete token list
387
+ function loadAllTokensWithGuidelines() {
388
+ try {
389
+ const specMarkdown = loadDesignTokensSpec();
390
+ const specTokens = parseDesignTokensSpec(specMarkdown);
391
+ return buildAllTokens(specTokens);
392
+ } catch {
393
+ // DESIGN_TOKENS_SPEC.md not available in this version of @primer/primitives
394
+ return buildAllTokens([]);
395
+ }
396
+ }
397
+
398
+ // Load the design tokens guide (logic, rules, patterns, golden examples)
399
+ function loadDesignTokensGuide() {
400
+ const require = createRequire(import.meta.url);
401
+ const guidePath = require.resolve('@primer/primitives/DESIGN_TOKENS_GUIDE.md');
402
+ return readFileSync(guidePath, 'utf-8');
403
+ }
404
+
405
+ // Load the design tokens spec (token dictionary with use cases and rules)
406
+ function loadDesignTokensSpec() {
407
+ const require = createRequire(import.meta.url);
408
+ const specPath = require.resolve('@primer/primitives/DESIGN_TOKENS_SPEC.md');
409
+ return readFileSync(specPath, 'utf-8');
410
+ }
411
+
412
+ // Get design token specifications text with dynamic group information
413
+ function getDesignTokenSpecsText(groups) {
414
+ return `
415
+ # Design Token Specifications
416
+
417
+ ## 1. Core Rule & Enforcement
418
+ * **Expert Mode**: CSS expert. NEVER use raw values (hex, px, etc.). Tokens only.
419
+ * **Motion & Transitions:** Every interactive state change (Hover, Active) MUST include a transition. NEVER use raw values like 200ms or ease-in. Use var(--base-duration-...) and var(--base-easing-...).
420
+ * **Shorthand**: MUST use \`font: var(...)\`. NEVER split size/weight.
421
+ * **Shorthand Fallback**: If no shorthand exists (e.g. Monospace), use individual tokens for font-size, family, and line-height. NEVER raw 1.5.
422
+ * **States**: Define 5: Rest, Hover, Focus-visible, Active, Disabled.
423
+ * **Focus**: \`:focus-visible\` MUST use \`outline: var(--focus-outline)\` AND \`outline-offset: var(--outline-focus-offset)\`.
424
+ * **Validation**: CALL \`lint_css\` after any CSS change. Task is incomplete without a success message.
425
+ * **Self-Correction**: Adopt autofixes immediately. Report unfixable errors to the user.
426
+
427
+ ## 2. Typography Constraints (STRICT)
428
+ - **Body Only**: Only \`body\` group supports size suffixes (e.g., \`body-small\`).
429
+ - **Static Shorthands**: NEVER add suffixes to \`caption\`, \`display\`, \`codeBlock\`, or \`codeInline\`.
430
+
431
+ ## 3. Logic Matrix: Color & Semantic Mapping
432
+ | Input Color/Intent | Semantic Role | Background Suffix | Foreground Requirement |
433
+ | :--- | :--- | :--- | :--- |
434
+ | Blue / Interactive | \`accent\` | \`-emphasis\` (Solid) | \`fgColor-onEmphasis\` |
435
+ | Green / Positive | \`success\` | \`-muted\` (Light) | \`fgColor-{semantic}\` |
436
+ | Red / Danger | \`danger\` | \`-emphasis\` | \`fgColor-onEmphasis\` |
437
+ | Yellow / Warning | \`attention\` | \`-muted\` | \`fgColor-attention\` |
438
+ | Orange / Critical | \`severe\` | \`-emphasis\` | \`fgColor-onEmphasis\` |
439
+ | Purple / Done | \`done\` | Any | Match intent |
440
+ | Pink / Sponsors | \`sponsors\` | Any | Match intent |
441
+ | Grey / Neutral | \`default\` | \`bgColor-muted\` | \`fgColor-default\` (Not muted) |
442
+
443
+ ## 4. Optimization & Recipes (MANDATORY)
444
+ **Strategy**: STOP property-by-property searching. Use \`get_token_group_bundle\` for these common patterns:
445
+ - **Forms**: \`["control", "focus", "outline", "text", "borderRadius", "stack", "animation"]\`
446
+ - **Modals/Cards**: \`["overlay", "shadow", "outline", "borderRadius", "bgColor", "stack", "animation"]\`
447
+ - **Tables/Lists**: \`["stack", "borderColor", "text", "bgColor", "control"]\`
448
+ - **Nav/Sidebars**: \`["control", "text", "accent", "stack", "focus", "animation"]\`
449
+ - **Status/Badges**: \`["text", "success", "danger", "attention", "severe", "stack"]\`
450
+
451
+ ## 5. Available Groups
452
+ - **Semantic**: ${groups.semantic.map(g => `${g.name}\``).join(', ')}
453
+ - **Components**: ${groups.component.map(g => `\`${g.name}\``).join(', ')}
454
+ `.trim();
455
+ }
456
+
457
+ // Get token usage patterns text (static golden examples)
458
+ function getTokenUsagePatternsText() {
459
+ return `
460
+ # Design Token Reference Examples
461
+
462
+ > **CRITICAL FOR AI**: To implement the examples below, DO NOT search for tokens one-by-one.
463
+ > Use \`get_token_group_bundle(groups: ["control", "stack", "focus", "borderRadius"])\` to fetch the required token values in a single call.
464
+
465
+ ---
466
+
467
+ ## 1. Interaction Pattern: The Primary Button
468
+ *Demonstrates: 5 states, color pairing, typography shorthand, and motion.*
469
+
470
+ \`\`\`css
471
+ .btn-primary {
472
+ /* Logic: Use control tokens for interactive elements */
473
+ background-color: var(--control-bgColor-rest);
474
+ color: var(--fgColor-default);
475
+ font: var(--text-body-shorthand-medium); /* MUST use shorthand */
476
+
477
+ /* Scale: DEFAULT is medium/normal */
478
+ padding-block: var(--control-medium-paddingBlock);
479
+ padding-inline: var(--control-medium-paddingInline-normal);
480
+ border: none;
481
+ border-radius: var(--borderRadius-medium);
482
+ cursor: pointer;
483
+
484
+ /* Motion: MUST be <300ms */
485
+ transition: background-color 150ms ease, transform 100ms ease;
486
+ }
487
+
488
+ .btn-primary:hover {
489
+ background-color: var(--control-bgColor-hover);
490
+ }
491
+
492
+ .btn-primary:focus-visible {
493
+ outline: var(--focus-outline);
494
+ outline-offset: var(--outline-focus-offset);
495
+ }
496
+
497
+ .btn-primary:active {
498
+ background-color: var(--control-bgColor-active);
499
+ transform: scale(0.98);
500
+ }
501
+
502
+ .btn-primary:disabled {
503
+ /* Logic: MUST pair bgColor-disabled with fgColor-disabled */
504
+ background-color: var(--bgColor-disabled);
505
+ color: var(--fgColor-disabled);
506
+ cursor: not-allowed;
507
+ }
508
+ \`\`\`
509
+
510
+ ---
511
+
512
+ ## 2. Layout Pattern: Vertical Stack
513
+ *Demonstrates: Layout spacing rules and matching padding density.*
514
+
515
+ \`\`\`css
516
+ .card-stack {
517
+ display: flex;
518
+ flex-direction: column;
519
+
520
+ /* Logic: Use stack tokens for layout spacing */
521
+ gap: var(--stack-gap-normal);
522
+ padding: var(--stack-padding-normal);
523
+
524
+ background-color: var(--bgColor-default);
525
+ border: 1px solid var(--borderColor-default);
526
+ border-radius: var(--borderRadius-large);
527
+ }
528
+
529
+ /* Logic: Matching padding density to purpose */
530
+ .card-header {
531
+ padding-block-end: var(--stack-gap-condensed);
532
+ border-bottom: 1px solid var(--borderColor-muted);
533
+ }
534
+ \`\`\`
535
+
536
+ ---
537
+
538
+ ## Implementation Rules for AI:
539
+ 1. **Shorthand First**: Always use \`font: var(...)\` rather than splitting size/weight.
540
+ 2. **States**: Never implement a button without all 5 states.
541
+ 3. **Spacing**: Use \`control-\` tokens for the component itself and \`stack-\` tokens for the container/layout.
542
+ 4. **Motion**: Always include the \`prefers-reduced-motion\` media query to set transitions to \`none\`.
543
+ \`\`\`css
544
+ @media (prefers-reduced-motion: reduce) {
545
+ .btn-primary {
546
+ transition: none;
547
+ }
548
+ }
549
+ \`\`\`
550
+ `.trim();
551
+ }
552
+
553
+ // Search tokens with keyword matching and optional group filter
554
+ // Returns expanded tokens (patterns like [accent, danger] are expanded) filtered by query
555
+ function searchTokens(allTokens, query, group) {
556
+ // 1. Flatten and expand all patterns first (e.g., [accent, danger])
557
+ const expandedTokens = allTokens.flatMap(expandTokenPattern);
558
+
559
+ // 2. Prepare keywords and group filter
560
+ const keywords = query.toLowerCase().split(/\s+/).filter(k => k.length > 0);
561
+
562
+ // 3. Perform filtered search with keyword splitting (Logical AND)
563
+ return expandedTokens.filter(token => {
564
+ // Combine all relevant metadata into one searchable string
565
+ const searchableText = `${token.name} ${token.useCase} ${token.rules} ${token.group}`.toLowerCase();
566
+
567
+ // Ensure EVERY keyword in the query exists somewhere in this token's metadata
568
+ const matchesKeywords = keywords.every(word => searchableText.includes(word));
569
+ const matchesGroup = !group || tokenMatchesGroup(token, group);
570
+ return matchesKeywords && matchesGroup;
571
+ });
572
+ }
573
+
574
+ // Alias map: fuzzy/human-readable names → canonical token name prefix
575
+ const GROUP_ALIASES = {
576
+ // Identity mappings (canonical prefixes, lowercased key)
577
+ bgcolor: 'bgColor',
578
+ fgcolor: 'fgColor',
579
+ bordercolor: 'borderColor',
580
+ border: 'border',
581
+ shadow: 'shadow',
582
+ focus: 'focus',
583
+ color: 'color',
584
+ button: 'button',
585
+ control: 'control',
586
+ overlay: 'overlay',
587
+ borderradius: 'borderRadius',
588
+ boxshadow: 'boxShadow',
589
+ fontstack: 'fontStack',
590
+ spinner: 'spinner',
591
+ // Fuzzy aliases
592
+ background: 'bgColor',
593
+ backgroundcolor: 'bgColor',
594
+ bg: 'bgColor',
595
+ foreground: 'fgColor',
596
+ foregroundcolor: 'fgColor',
597
+ textcolor: 'fgColor',
598
+ fg: 'fgColor',
599
+ radius: 'borderRadius',
600
+ rounded: 'borderRadius',
601
+ elevation: 'overlay',
602
+ depth: 'overlay',
603
+ btn: 'button',
604
+ typography: 'text',
605
+ font: 'text',
606
+ text: 'text',
607
+ 'line-height': 'text',
608
+ lineheight: 'text',
609
+ leading: 'text',
610
+ // Layout & Spacing
611
+ stack: 'stack',
612
+ controlstack: 'controlStack',
613
+ padding: 'stack',
614
+ margin: 'stack',
615
+ gap: 'stack',
616
+ spacing: 'stack',
617
+ layout: 'stack',
618
+ // State & Interaction
619
+ offset: 'focus',
620
+ outline: 'outline',
621
+ ring: 'focus',
622
+ // Decoration & Borders
623
+ borderwidth: 'borderWidth',
624
+ line: 'borderColor',
625
+ stroke: 'borderColor',
626
+ separator: 'borderColor',
627
+ // Color-to-Semantic Intent Mapping
628
+ red: 'danger',
629
+ green: 'success',
630
+ yellow: 'attention',
631
+ orange: 'severe',
632
+ blue: 'accent',
633
+ purple: 'done',
634
+ pink: 'sponsors',
635
+ grey: 'neutral',
636
+ gray: 'neutral',
637
+ // Descriptive Aliases
638
+ light: 'muted',
639
+ subtle: 'muted',
640
+ dark: 'emphasis',
641
+ strong: 'emphasis',
642
+ intense: 'emphasis',
643
+ bold: 'emphasis',
644
+ vivid: 'emphasis',
645
+ highlight: 'emphasis'
646
+ };
647
+
648
+ // Match a token against a resolved group by checking both the token name prefix and the group label
649
+ function tokenMatchesGroup(token, resolvedGroup) {
650
+ const rg = resolvedGroup.toLowerCase();
651
+ const tokenPrefix = token.name.split('-')[0].toLowerCase();
652
+ const tokenGroup = token.group.toLowerCase();
653
+ return tokenPrefix === rg || tokenGroup === rg;
654
+ }
655
+
656
+ // Group tokens by their group property and format as Markdown
657
+ function formatBundle(bundleTokens) {
658
+ const grouped = bundleTokens.reduce((acc, token) => {
659
+ const group = GROUP_LABELS[token.group] || token.group || 'Ungrouped';
660
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
661
+ if (!acc[group]) acc[group] = [];
662
+ acc[group].push(token);
663
+ return acc;
664
+ }, {});
665
+ return Object.entries(grouped).map(([group, groupTokens]) => {
666
+ const tokenList = groupTokens.map(t => {
667
+ const nameLabel = t.value ? `\`${t.name}\` → \`${t.value}\`` : `\`${t.name}\``;
668
+ return `- ${nameLabel}\n - **U**: ${t.useCase || '(none)'}\n - **R**: ${t.rules || '(none)'}`;
669
+ }).join('\n');
670
+ return `## ${group}\n\n${tokenList}`;
671
+ }).join('\n\n---\n\n');
672
+ }
673
+
674
+ /**
675
+ * Generates a sorted, unique list of group names from the current token cache.
676
+ * Used for "Healing" error messages and the Design System Search Map.
677
+ */
678
+ function getValidGroupsList(validTokens) {
679
+ if (validTokens.length === 0) {
680
+ return 'No groups available.';
681
+ }
682
+
683
+ // 1. Extract unique group names
684
+ const uniqueGroups = Array.from(new Set(validTokens.map(t => t.group)));
685
+
686
+ // 2. Sort alphabetically for consistency
687
+ uniqueGroups.sort((a, b) => a.localeCompare(b));
688
+
689
+ // 3. Return as a formatted Markdown string with backticks
690
+ return uniqueGroups.map(g => `\`${g}\``).join(', ');
691
+ }
692
+
693
+ // Usage Guidance Hints
694
+ const groupHints = {
695
+ control: '`control` tokens are for form inputs/checkboxes. For buttons, use the `button` group.',
696
+ button: '`button` tokens are for standard triggers. For form-fields, see the `control` group.',
697
+ text: 'STRICT: The following typography groups do NOT support size suffixes (-small, -medium, -large): `caption`, `display`, `codeBlock`, and `codeInline`. STRICT: Use shorthand tokens where possible. If splitting, you MUST fetch line-height tokens (e.g., --text-body-lineHeight-small) instead of using raw numbers.',
698
+ fgColor: 'Use `fgColor` for text. For borders, use `borderColor`.',
699
+ borderWidth: '`borderWidth` only has sizing values (thin, thick, thicker). For border *colors*, use the `borderColor` or `border` group.',
700
+ animation: 'TRANSITION RULE: Apply duration and easing to the base class, not the :hover state. Standard pairing: `transition: background-color var(--base-duration-200) var(--base-easing-easeInOut);`'
701
+ };
702
+
703
+ // -----------------------------------------------------------------------------
704
+ // Stylelint runner
705
+ // -----------------------------------------------------------------------------
706
+ function runStylelint(css) {
707
+ return new Promise((resolve, reject) => {
708
+ const proc = spawn('npx', ['stylelint', '--stdin', '--fix'], {
709
+ stdio: ['pipe', 'pipe', 'pipe'],
710
+ shell: true
711
+ });
712
+ let stdout = '';
713
+ let stderr = '';
714
+ proc.stdout.on('data', data => {
715
+ stdout += data.toString();
716
+ });
717
+ proc.stderr.on('data', data => {
718
+ stderr += data.toString();
719
+ });
720
+ proc.on('close', code => {
721
+ if (code === 0) {
722
+ resolve({
723
+ stdout,
724
+ stderr
725
+ });
726
+ } else {
727
+ const error = new Error(`Stylelint exited with code ${code}`);
728
+ error.stdout = stdout;
729
+ error.stderr = stderr;
730
+ reject(error);
731
+ }
732
+ });
733
+ proc.on('error', reject);
734
+ proc.stdin.write(css);
735
+ proc.stdin.end();
736
+ });
737
+ }
738
+
739
+ var version = "0.3.1";
740
+ var packageJson = {
741
+ version: version};
742
+
743
+ const server = new McpServer({
744
+ name: 'Primer',
745
+ version: packageJson.version
746
+ });
747
+ const turndownService = new TurndownService();
748
+
749
+ // Load all tokens with guidelines from primitives
750
+ const allTokensWithGuidelines = loadAllTokensWithGuidelines();
751
+
752
+ // -----------------------------------------------------------------------------
753
+ // Project setup
754
+ // -----------------------------------------------------------------------------
755
+ server.registerTool('init', {
756
+ description: 'Setup or create a project that includes Primer React'
757
+ }, async () => {
758
+ const url = new URL(`/product/getting-started/react`, 'https://primer.style');
759
+ const response = await fetch(url);
760
+ if (!response.ok) {
761
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
762
+ }
763
+ const html = await response.text();
764
+ if (!html) {
765
+ return {
766
+ content: []
767
+ };
768
+ }
769
+ const $ = cheerio.load(html);
770
+ const source = $('main').html();
771
+ if (!source) {
772
+ return {
773
+ content: []
774
+ };
775
+ }
776
+ const text = turndownService.turndown(source);
777
+ return {
778
+ content: [{
779
+ type: 'text',
780
+ text: `The getting started documentation for Primer React is included below. It's important that the project:
781
+
782
+ - Is using a tool like Vite, Next.js, etc that supports TypeScript and React. If the project does not have support for that, generate an appropriate project scaffold
783
+ - Installs the latest version of \`@primer/react\` from \`npm\`
784
+ - Correctly adds the \`ThemeProvider\` and \`BaseStyles\` components to the root of the application
785
+ - Includes an import to a theme from \`@primer/primitives\`
786
+ - If the project wants to use icons, also install the \`@primer/octicons-react\` from \`npm\`
787
+ - Add appropriate agent instructions (like for copilot) to the project to prefer using components, tokens, icons, and more from Primer packages
788
+
789
+ ---
790
+
791
+ ${text}
792
+ `
793
+ }]
794
+ };
795
+ });
796
+
797
+ // -----------------------------------------------------------------------------
798
+ // Components
799
+ // -----------------------------------------------------------------------------
800
+ server.registerTool('list_components', {
801
+ description: 'List all of the components available from Primer React'
802
+ }, async () => {
803
+ const components = listComponents().map(component => {
804
+ return `- ${component.name}`;
805
+ });
806
+ return {
807
+ content: [{
808
+ type: 'text',
809
+ text: `The following components are available in the @primer/react in TypeScript projects:
810
+
811
+ ${components.join('\n')}
812
+
813
+ You can use the \`get_component\` tool to get more information about a specific component. You can use these components from the @primer/react package.`
814
+ }]
815
+ };
816
+ });
817
+ server.registerTool('get_component', {
818
+ description: 'Retrieve documentation and usage details for a specific React component from the @primer/react package by its name. This tool provides the official Primer documentation for any listed component, making it easy to inspect, reuse, or integrate components in your project.',
819
+ inputSchema: {
820
+ name: z.string().describe('The name of the component to retrieve')
821
+ }
822
+ }, async ({
823
+ name
824
+ }) => {
825
+ const components = listComponents();
826
+ const match = components.find(component => {
827
+ return component.name === name || component.name.toLowerCase() === name.toLowerCase();
828
+ });
829
+ if (!match) {
830
+ return {
831
+ isError: true,
832
+ errorMessage: `There is no component named \`${name}\` in the @primer/react package. For a full list of components, use the \`list_components\` tool.`,
833
+ content: []
834
+ };
835
+ }
836
+ const llmsUrl = new URL(`/product/components/${match.slug}/llms.txt`, 'https://primer.style');
837
+ const llmsResponse = await fetch(llmsUrl);
838
+ if (llmsResponse.ok) {
839
+ try {
840
+ const llmsText = await llmsResponse.text();
841
+ return {
842
+ content: [{
843
+ type: 'text',
844
+ text: llmsText
845
+ }]
846
+ };
847
+ } catch (_) {
848
+ // If there's an error fetching or processing the llms.txt, we fall back to the regular documentation
849
+ }
850
+ }
851
+ const url = new URL(`/product/components/${match.slug}`, 'https://primer.style');
852
+ const response = await fetch(url);
853
+ if (!response.ok) {
854
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
855
+ }
856
+ const html = await response.text();
857
+ if (!html) {
858
+ return {
859
+ content: []
860
+ };
861
+ }
862
+ const $ = cheerio.load(html);
863
+ const source = $('main').html();
864
+ if (!source) {
865
+ return {
866
+ content: []
867
+ };
868
+ }
869
+ const text = turndownService.turndown(source);
870
+ return {
871
+ content: [{
872
+ type: 'text',
873
+ text: `Here is the documentation for the \`${name}\` component from the @primer/react package:
874
+ ${text}`
875
+ }]
876
+ };
877
+ });
878
+ server.registerTool('get_component_examples', {
879
+ description: 'Get examples for how to use a component from Primer React',
880
+ inputSchema: {
881
+ name: z.string().describe('The name of the component to retrieve')
882
+ }
883
+ }, async ({
884
+ name
885
+ }) => {
886
+ const components = listComponents();
887
+ const match = components.find(component => {
888
+ return component.name === name;
889
+ });
890
+ if (!match) {
891
+ return {
892
+ content: [{
893
+ type: 'text',
894
+ text: `There is no component named \`${name}\` in the @primer/react package. For a full list of components, use the \`get_components\` tool.`
895
+ }]
896
+ };
897
+ }
898
+ const url = new URL(`/product/components/${match.id}`, 'https://primer.style');
899
+ const response = await fetch(url);
900
+ if (!response.ok) {
901
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
902
+ }
903
+ const html = await response.text();
904
+ if (!html) {
905
+ return {
906
+ content: []
907
+ };
908
+ }
909
+ const $ = cheerio.load(html);
910
+ const source = $('main').html();
911
+ if (!source) {
912
+ return {
913
+ content: []
914
+ };
915
+ }
916
+ const text = turndownService.turndown(source);
917
+ return {
918
+ content: [{
919
+ type: 'text',
920
+ text: `Here are some examples of how to use the \`${name}\` component from the @primer/react package:
921
+
922
+ ${text}`
923
+ }]
924
+ };
925
+ });
926
+ server.registerTool('get_component_usage_guidelines', {
927
+ description: 'Get usage information for how to use a component from Primer',
928
+ inputSchema: {
929
+ name: z.string().describe('The name of the component to retrieve')
930
+ }
931
+ }, async ({
932
+ name
933
+ }) => {
934
+ const components = listComponents();
935
+ const match = components.find(component => {
936
+ return component.name === name;
937
+ });
938
+ if (!match) {
939
+ return {
940
+ content: [{
941
+ type: 'text',
942
+ text: `There is no component named \`${name}\` in the @primer/react package. For a full list of components, use the \`get_components\` tool.`
943
+ }]
944
+ };
945
+ }
946
+ const url = new URL(`/product/components/${match.id}/guidelines`, 'https://primer.style');
947
+ const response = await fetch(url);
948
+ if (!response.ok) {
949
+ if (response.status >= 400 && response.status < 500 || response.status >= 300 && response.status < 400) {
950
+ return {
951
+ content: [{
952
+ type: 'text',
953
+ text: `There are no accessibility guidelines for the \`${name}\` component in the @primer/react package.`
954
+ }]
955
+ };
956
+ }
957
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
958
+ }
959
+ const html = await response.text();
960
+ if (!html) {
961
+ return {
962
+ content: []
963
+ };
964
+ }
965
+ const $ = cheerio.load(html);
966
+ const source = $('main').html();
967
+ if (!source) {
968
+ return {
969
+ content: []
970
+ };
971
+ }
972
+ const text = turndownService.turndown(source);
973
+ return {
974
+ content: [{
975
+ type: 'text',
976
+ text: `Here are the usage guidelines for the \`${name}\` component from the @primer/react package:
977
+
978
+ ${text}`
979
+ }]
980
+ };
981
+ });
982
+ server.registerTool('get_component_accessibility_guidelines', {
983
+ description: 'Retrieve accessibility guidelines and best practices for a specific component from the @primer/react package by its name. Use this tool to get official accessibility recommendations, usage tips, and requirements to ensure your UI components are inclusive and meet accessibility standards.',
984
+ inputSchema: {
985
+ name: z.string().describe('The name of the component to retrieve')
986
+ }
987
+ }, async ({
988
+ name
989
+ }) => {
990
+ const components = listComponents();
991
+ const match = components.find(component => {
992
+ return component.name === name;
993
+ });
994
+ if (!match) {
995
+ return {
996
+ content: [{
997
+ type: 'text',
998
+ text: `There is no component named \`${name}\` in the @primer/react package. For a full list of components, use the \`list_components\` tool.`
999
+ }]
1000
+ };
1001
+ }
1002
+ const url = new URL(`/product/components/${match.id}/accessibility`, 'https://primer.style');
1003
+ const response = await fetch(url);
1004
+ if (!response.ok) {
1005
+ if (response.status >= 400 && response.status < 500 || response.status >= 300 && response.status < 400) {
1006
+ return {
1007
+ content: [{
1008
+ type: 'text',
1009
+ text: `There are no accessibility guidelines for the \`${name}\` component in the @primer/react package.`
1010
+ }]
1011
+ };
1012
+ }
1013
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
1014
+ }
1015
+ const html = await response.text();
1016
+ if (!html) {
1017
+ return {
1018
+ content: []
1019
+ };
1020
+ }
1021
+ const $ = cheerio.load(html);
1022
+ const source = $('main').html();
1023
+ if (!source) {
1024
+ return {
1025
+ content: []
1026
+ };
1027
+ }
1028
+ const text = turndownService.turndown(source);
1029
+ return {
1030
+ content: [{
1031
+ type: 'text',
1032
+ text: `Here are the accessibility guidelines for the \`${name}\` component from the @primer/react package:
1033
+
1034
+ ${text}`
1035
+ }]
1036
+ };
1037
+ });
1038
+
1039
+ // -----------------------------------------------------------------------------
1040
+ // Patterns
1041
+ // -----------------------------------------------------------------------------
1042
+ server.registerTool('list_patterns', {
1043
+ description: 'List all of the patterns available from Primer React'
1044
+ }, async () => {
1045
+ const patterns = listPatterns().map(pattern => {
1046
+ return `- ${pattern.name}`;
1047
+ });
1048
+ return {
1049
+ content: [{
1050
+ type: 'text',
1051
+ text: `The following patterns are available in the @primer/react in TypeScript projects:
1052
+
1053
+ ${patterns.join('\n')}`
1054
+ }]
1055
+ };
1056
+ });
1057
+ server.registerTool('get_pattern', {
1058
+ description: 'Get a specific pattern by name',
1059
+ inputSchema: {
1060
+ name: z.string().describe('The name of the pattern to retrieve')
1061
+ }
1062
+ }, async ({
1063
+ name
1064
+ }) => {
1065
+ const patterns = listPatterns();
1066
+ const match = patterns.find(pattern => {
1067
+ return pattern.name === name;
1068
+ });
1069
+ if (!match) {
1070
+ return {
1071
+ content: [{
1072
+ type: 'text',
1073
+ text: `There is no pattern named \`${name}\` in the @primer/react package. For a full list of patterns, use the \`list_patterns\` tool.`
1074
+ }]
1075
+ };
1076
+ }
1077
+ const url = new URL(`/product/ui-patterns/${match.id}`, 'https://primer.style');
1078
+ const response = await fetch(url);
1079
+ if (!response.ok) {
1080
+ throw new Error(`Failed to fetch ${url} - ${response.statusText}`);
1081
+ }
1082
+ const html = await response.text();
1083
+ if (!html) {
1084
+ return {
1085
+ content: []
1086
+ };
1087
+ }
1088
+ const $ = cheerio.load(html);
1089
+ const source = $('main').html();
1090
+ if (!source) {
1091
+ return {
1092
+ content: []
1093
+ };
1094
+ }
1095
+ const text = turndownService.turndown(source);
1096
+ return {
1097
+ content: [{
1098
+ type: 'text',
1099
+ text: `Here are the guidelines for the \`${name}\` pattern for Primer:
1100
+
1101
+ ${text}`
1102
+ }]
1103
+ };
1104
+ });
1105
+
1106
+ // -----------------------------------------------------------------------------
1107
+ // Design Tokens
1108
+ // -----------------------------------------------------------------------------
1109
+ server.registerTool('find_tokens', {
1110
+ description: 'Search for specific tokens. Tip: If you only provide a \'group\' and leave \'query\' empty, it returns all tokens in that category. Avoid property-by-property searching. COLOR RESOLUTION: If a user asks for "pink" or "blue", do not search for the color name. Use the semantic intent: blue->accent, red->danger, green->success. Always check both "emphasis" and "muted" variants for background colors. After identifying tokens and writing CSS, you MUST validate the result using lint_css.',
1111
+ inputSchema: {
1112
+ query: z.string().optional().default('').describe('Search keywords (e.g., "danger border", "success background")'),
1113
+ group: z.string().optional().describe('Filter by group (e.g., "fgColor", "border")'),
1114
+ limit: z.number().int().min(1).max(100).optional().default(15).describe('Maximum results to return to stay within context limits')
1115
+ }
1116
+ }, async ({
1117
+ query,
1118
+ group,
1119
+ limit
1120
+ }) => {
1121
+ // Resolve group via aliases
1122
+ const resolvedGroup = group ? GROUP_ALIASES[group.toLowerCase().replace(/\s+/g, '')] || group : undefined;
1123
+
1124
+ // Split query into keywords and extract any that match a known group
1125
+ const rawKeywords = query.toLowerCase().split(/\s+/).filter(k => k.length > 0);
1126
+ let effectiveGroup = resolvedGroup;
1127
+ const filteredKeywords = [];
1128
+ for (const kw of rawKeywords) {
1129
+ const normalized = kw.replace(/\s+/g, '');
1130
+ const aliasMatch = GROUP_ALIASES[normalized];
1131
+ if (aliasMatch && !effectiveGroup) {
1132
+ effectiveGroup = aliasMatch;
1133
+ } else {
1134
+ filteredKeywords.push(kw);
1135
+ }
1136
+ }
1137
+
1138
+ // Guard: no query and no group → ask user to provide at least one
1139
+ if (filteredKeywords.length === 0 && !effectiveGroup) {
1140
+ return {
1141
+ content: [{
1142
+ type: 'text',
1143
+ text: 'Please provide a query, a group, or both. Call `get_design_token_specs` to see available token groups.'
1144
+ }]
1145
+ };
1146
+ }
1147
+
1148
+ // Group-only search: return all tokens in the group
1149
+ const isGroupOnly = filteredKeywords.length === 0 && effectiveGroup;
1150
+ let results;
1151
+ if (isGroupOnly) {
1152
+ results = allTokensWithGuidelines.filter(token => tokenMatchesGroup(token, effectiveGroup));
1153
+ } else {
1154
+ results = searchTokens(allTokensWithGuidelines, filteredKeywords.join(' '), effectiveGroup);
1155
+ }
1156
+ if (results.length === 0) {
1157
+ const validGroups = getValidGroupsList(allTokensWithGuidelines);
1158
+ return {
1159
+ content: [{
1160
+ type: 'text',
1161
+ text: `No tokens found matching "${query}"${effectiveGroup ? ` in group "${effectiveGroup}"` : ''}.
1162
+
1163
+ ### 💡 Available Groups:
1164
+ ${validGroups}
1165
+
1166
+ ### Troubleshooting for AI:
1167
+ 1. **Multi-word Queries**: Search keywords use 'AND' logic. If searching "text shorthand typography" fails, try a single keyword like "shorthand" within the "text" group.
1168
+ 2. **Property Mismatch**: Do not search for CSS properties like "offset", "padding", or "font-size". Use semantic intent keywords: "danger", "muted", "emphasis".
1169
+ 3. **Typography**: Remember that \`caption\`, \`display\`, and \`code\` groups do NOT support size suffixes. Use the base shorthand only.
1170
+ 4. **Group Intent**: Use the \`group\` parameter instead of putting group names in the \`query\` string (e.g., use group: "stack" instead of query: "stack padding").`
1171
+ }]
1172
+ };
1173
+ }
1174
+ const limitedResults = results.slice(0, limit);
1175
+ let output;
1176
+ if (!query) {
1177
+ output = `Found ${results.length} token(s). Showing top ${limitedResults.length}:\n\n`;
1178
+ } else {
1179
+ output = `Found ${results.length} token(s) matching "${query}". Showing top ${limitedResults.length}:\n\n`;
1180
+ }
1181
+ output += formatBundle(limitedResults);
1182
+ if (results.length > limit) {
1183
+ output += `\n\n*...and ${results.length - limit} more matches. Use more specific keywords to narrow the search.*`;
1184
+ }
1185
+ return {
1186
+ content: [{
1187
+ type: 'text',
1188
+ text: output
1189
+ }]
1190
+ };
1191
+ });
1192
+ server.registerTool('get_token_group_bundle', {
1193
+ description: "PREFERRED FOR COMPONENTS. Fetch all tokens for complex UI (e.g., Dialogs, Cards) in one call by providing an array of groups like ['overlay', 'shadow']. Use this instead of multiple find_tokens calls to save context.",
1194
+ inputSchema: {
1195
+ groups: z.array(z.string()).describe('Array of group names (e.g., ["overlay", "shadow", "focus"])')
1196
+ }
1197
+ }, async ({
1198
+ groups
1199
+ }) => {
1200
+ // Normalize and resolve aliases
1201
+ const resolvedGroups = groups.map(g => {
1202
+ const normalized = g.toLowerCase().replace(/\s+/g, '');
1203
+ return GROUP_ALIASES[normalized] || g;
1204
+ });
1205
+
1206
+ // Filter tokens matching any of the resolved groups
1207
+ const matched = allTokensWithGuidelines.filter(token => resolvedGroups.some(rg => tokenMatchesGroup(token, rg)));
1208
+ if (matched.length === 0) {
1209
+ const validGroups = getValidGroupsList(allTokensWithGuidelines);
1210
+ return {
1211
+ content: [{
1212
+ type: 'text',
1213
+ text: `No tokens found for groups: ${groups.join(', ')}.\n\n### Valid Groups:\n${validGroups}`
1214
+ }]
1215
+ };
1216
+ }
1217
+ let text = `Found ${matched.length} token(s) across ${resolvedGroups.length} group(s):\n\n${formatBundle(matched)}`;
1218
+ const activeHints = resolvedGroups.map(g => groupHints[g]).filter(Boolean);
1219
+ if (activeHints.length > 0) {
1220
+ text += `\n\n### ⚠️ Usage Guidance:\n${activeHints.map(h => `- ${h}`).join('\n')}`;
1221
+ }
1222
+ return {
1223
+ content: [{
1224
+ type: 'text',
1225
+ text
1226
+ }]
1227
+ };
1228
+ });
1229
+ server.registerTool('get_design_token_specs', {
1230
+ description: 'CRITICAL: CALL THIS FIRST. Provides the logic matrix and the list of valid group names. You cannot search accurately without this map.'
1231
+ }, async () => {
1232
+ const groups = listTokenGroups();
1233
+ const customRules = getDesignTokenSpecsText(groups);
1234
+ let text;
1235
+ try {
1236
+ const upstreamGuide = loadDesignTokensGuide();
1237
+ text = `${customRules}\n\n---\n\n${upstreamGuide}`;
1238
+ } catch {
1239
+ text = customRules;
1240
+ }
1241
+ return {
1242
+ content: [{
1243
+ type: 'text',
1244
+ text
1245
+ }]
1246
+ };
1247
+ });
1248
+ server.registerTool('get_token_usage_patterns', {
1249
+ description: 'Provides "Golden Example" CSS for core patterns: Button (Interactions) and Stack (Layout). Use this to understand how to apply the Logic Matrix, Motion, and Spacing scales.'
1250
+ }, async () => {
1251
+ const customPatterns = getTokenUsagePatternsText();
1252
+ let text;
1253
+ try {
1254
+ const guide = loadDesignTokensGuide();
1255
+ const goldenExampleMatch = guide.match(/## Golden Example[\s\S]*?(?=\n## |$)/);
1256
+ if (goldenExampleMatch) {
1257
+ text = `${customPatterns}\n\n---\n\n${goldenExampleMatch[0].trim()}`;
1258
+ } else {
1259
+ text = customPatterns;
1260
+ }
1261
+ } catch {
1262
+ text = customPatterns;
1263
+ }
1264
+ return {
1265
+ content: [{
1266
+ type: 'text',
1267
+ text
1268
+ }]
1269
+ };
1270
+ });
1271
+ server.registerTool('lint_css', {
1272
+ description: 'REQUIRED FINAL STEP. Use this to validate your CSS. You cannot complete a task involving CSS without a successful run of this tool.',
1273
+ inputSchema: {
1274
+ css: z.string()
1275
+ }
1276
+ }, async ({
1277
+ css
1278
+ }) => {
1279
+ try {
1280
+ // --fix flag tells Stylelint to repair what it can
1281
+ const {
1282
+ stdout
1283
+ } = await runStylelint(css);
1284
+ return {
1285
+ content: [{
1286
+ type: 'text',
1287
+ text: stdout || '✅ Stylelint passed (or was successfully autofixed).'
1288
+ }]
1289
+ };
1290
+ } catch (error) {
1291
+ // If Stylelint still has errors it CANNOT fix, it will land here
1292
+ const errorOutput = error instanceof Error && 'stdout' in error ? error.stdout : String(error);
1293
+ return {
1294
+ content: [{
1295
+ type: 'text',
1296
+ text: `❌ Errors without autofix remaining:\n${errorOutput}`
1297
+ }]
1298
+ };
1299
+ }
1300
+ });
1301
+
1302
+ // -----------------------------------------------------------------------------
1303
+ // Foundations
1304
+ // -----------------------------------------------------------------------------
1305
+ server.registerTool('get_color_usage', {
1306
+ description: 'Get the guidelines for how to apply color to a user interface'
1307
+ }, async () => {
1308
+ const url = new URL(`/product/getting-started/foundations/color-usage`, 'https://primer.style');
1309
+ const response = await fetch(url);
1310
+ if (!response.ok) {
1311
+ throw new Error(`Failed to fetch ${url} - ${response.statusText}`);
1312
+ }
1313
+ const html = await response.text();
1314
+ if (!html) {
1315
+ return {
1316
+ content: []
1317
+ };
1318
+ }
1319
+ const $ = cheerio.load(html);
1320
+ const source = $('main').html();
1321
+ if (!source) {
1322
+ return {
1323
+ content: []
1324
+ };
1325
+ }
1326
+ const text = turndownService.turndown(source);
1327
+ return {
1328
+ content: [{
1329
+ type: 'text',
1330
+ text: `Here is the documentation for color usage in Primer:\n\n${text}`
1331
+ }]
1332
+ };
1333
+ });
1334
+ server.registerTool('get_typography_usage', {
1335
+ description: 'Get the guidelines for how to apply typography to a user interface'
1336
+ }, async () => {
1337
+ const url = new URL(`/product/getting-started/foundations/typography`, 'https://primer.style');
1338
+ const response = await fetch(url);
1339
+ if (!response.ok) {
1340
+ throw new Error(`Failed to fetch ${url} - ${response.statusText}`);
1341
+ }
1342
+ const html = await response.text();
1343
+ if (!html) {
1344
+ return {
1345
+ content: []
1346
+ };
1347
+ }
1348
+ const $ = cheerio.load(html);
1349
+ const source = $('main').html();
1350
+ if (!source) {
1351
+ return {
1352
+ content: []
1353
+ };
1354
+ }
1355
+ const text = turndownService.turndown(source);
1356
+ return {
1357
+ content: [{
1358
+ type: 'text',
1359
+ text: `Here is the documentation for typography usage in Primer:\n\n${text}`
1360
+ }]
1361
+ };
1362
+ });
1363
+
1364
+ // -----------------------------------------------------------------------------
1365
+ // Icons
1366
+ // -----------------------------------------------------------------------------
1367
+ server.registerTool('list_icons', {
1368
+ description: 'List all of the icons (octicons) available from Primer Octicons React'
1369
+ }, async () => {
1370
+ const icons = listIcons().map(icon => {
1371
+ const keywords = icon.keywords.map(keyword => {
1372
+ return `<keyword>${keyword}</keyword>`;
1373
+ });
1374
+ const sizes = icon.heights.map(height => {
1375
+ return `<size value="${height}"></size>`;
1376
+ });
1377
+ return [`<icon name="${icon.name}">`, ...keywords, ...sizes, `</icon>`].join('\n');
1378
+ });
1379
+ return {
1380
+ content: [{
1381
+ type: 'text',
1382
+ text: `The following icons are available in the @primer/octicons-react package in TypeScript projects:
1383
+
1384
+ ${icons.join('\n')}
1385
+
1386
+ You can use the \`get_icon\` tool to get more information about a specific icon. You can use these components from the @primer/octicons-react package.`
1387
+ }]
1388
+ };
1389
+ });
1390
+ server.registerTool('get_icon', {
1391
+ description: 'Get a specific icon (octicon) by name from Primer',
1392
+ inputSchema: {
1393
+ name: z.string().describe('The name of the icon to retrieve'),
1394
+ size: z.string().optional().describe('The size of the icon to retrieve, e.g. "16"').default('16')
1395
+ }
1396
+ }, async ({
1397
+ name,
1398
+ size
1399
+ }) => {
1400
+ const icons = listIcons();
1401
+ const match = icons.find(icon => {
1402
+ return icon.name === name || icon.name.toLowerCase() === name.toLowerCase();
1403
+ });
1404
+ if (!match) {
1405
+ return {
1406
+ content: [{
1407
+ type: 'text',
1408
+ text: `There is no icon named \`${name}\` in the @primer/octicons-react package. For a full list of icons, use the \`get_icon\` tool.`
1409
+ }]
1410
+ };
1411
+ }
1412
+ const url = new URL(`/octicons/icon/${match.name}-${size}`, 'https://primer.style');
1413
+ const response = await fetch(url);
1414
+ if (!response.ok) {
1415
+ throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
1416
+ }
1417
+ const html = await response.text();
1418
+ if (!html) {
1419
+ return {
1420
+ content: []
1421
+ };
1422
+ }
1423
+ const $ = cheerio.load(html);
1424
+ const source = $('main').html();
1425
+ if (!source) {
1426
+ return {
1427
+ content: []
1428
+ };
1429
+ }
1430
+ const text = turndownService.turndown(source);
1431
+ return {
1432
+ content: [{
1433
+ type: 'text',
1434
+ text: `Here is the documentation for the \`${name}\` icon at size: \`${size}\`:
1435
+ ${text}`
1436
+ }]
1437
+ };
1438
+ });
1439
+
1440
+ // -----------------------------------------------------------------------------
1441
+ // Coding guidelines
1442
+ // -----------------------------------------------------------------------------
1443
+ server.registerTool('primer_coding_guidelines', {
1444
+ description: 'Get the guidelines when writing code that uses Primer or for UI code that you are creating'
1445
+ }, async () => {
1446
+ return {
1447
+ content: [{
1448
+ type: 'text',
1449
+ text: `When writing code that uses Primer, follow these guidelines:
1450
+
1451
+ ## Design Tokens
1452
+
1453
+ - Prefer design tokens over hard-coded values. For example, use \`var(--fgColor-default)\` instead of \`#24292f\`. Use the \`find_tokens\` tool to search for a design token by keyword or group. Use \`get_design_token_specs\` to browse available token groups, and \`get_token_group_bundle\` to retrieve all tokens within a specific group.
1454
+ - Prefer recommending design tokens in the same group for related CSS properties. For example, when styling background and border color, use tokens from the same group/category
1455
+
1456
+ ## Authoring & Using Components
1457
+
1458
+ - Prefer re-using a component from Primer when possible over writing a new component.
1459
+ - Prefer using existing props for a component for styling instead of adding styling to a component
1460
+ - Prefer using icons from Primer instead of creating new icons. Use the \`list_icons\` tool to find the icon you need.
1461
+ - Follow patterns from Primer when creating new components. Use the \`list_patterns\` tool to find the pattern you need, if one exists
1462
+ - When using a component from Primer, make sure to follow the component's usage and accessibility guidelines
1463
+
1464
+ ## Coding guidelines
1465
+
1466
+ The following list of coding guidelines must be followed:
1467
+
1468
+ - Do not use the sx prop for styling components. Instead, use CSS Modules.
1469
+ - Do not use the Box component for styling components. Instead, use CSS Modules.
1470
+ `
1471
+ }]
1472
+ };
1473
+ });
1474
+
1475
+ // -----------------------------------------------------------------------------
1476
+ // Accessibility
1477
+ // -----------------------------------------------------------------------------
1478
+
1479
+ /**
1480
+ * The `review_alt_text` tool is experimental and may be removed in future versions.
1481
+ *
1482
+ * The intent of this tool is to assist products like Copilot Code Review and Copilot Coding Agent
1483
+ * in reviewing both user- and AI-generated alt text for images, ensuring compliance with accessibility guidelines.
1484
+ * This tool is not intended to replace human-generated alt text; rather, it supports the review process
1485
+ * by providing suggestions for improvement. It should be used alongside human review, not as a substitute.
1486
+ *
1487
+ *
1488
+ **/
1489
+ server.registerTool('review_alt_text', {
1490
+ description: 'Evaluates image alt text against accessibility best practices and context relevance.',
1491
+ inputSchema: {
1492
+ surroundingText: z.string().describe('Text surrounding the image, relevant to the image.'),
1493
+ alt: z.string().describe('The alt text of the image being evaluated'),
1494
+ image: z.string().describe('The image URL or file path being evaluated')
1495
+ }
1496
+ }, async ({
1497
+ surroundingText,
1498
+ alt,
1499
+ image
1500
+ }) => {
1501
+ // Call the LLM through MCP sampling
1502
+ const response = await server.server.createMessage({
1503
+ messages: [{
1504
+ role: 'user',
1505
+ content: {
1506
+ type: 'text',
1507
+ text: `Does this alt text: '${alt}' meet accessibility guidelines and describe the image: ${image} accurately in context of this surrounding text: '${surroundingText}'?\n\n`
1508
+ }
1509
+ }],
1510
+ sampling: {
1511
+ temperature: 0.4
1512
+ },
1513
+ maxTokens: 500
1514
+ });
1515
+ return {
1516
+ content: [{
1517
+ type: 'text',
1518
+ text: response.content.type === 'text' ? response.content.text : 'Unable to generate summary'
1519
+ }],
1520
+ altTextEvaluation: response.content.type === 'text' ? response.content.text : 'Unable to generate summary',
1521
+ nextSteps: `If the evaluation indicates issues with the alt text, provide more meaningful alt text based on the feedback. DO NOT run this tool repeatedly on the same image - evaluations may vary slightly with each run.`
1522
+ };
1523
+ });
1524
+
1525
+ export { server as s };