@primer/mcp 0.4.0 → 0.5.0-rc.0ad25a240

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