@adobe/spectrum-design-data-mcp 0.0.0-layout-20260209174611

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,592 @@
1
+ /*
2
+ Copyright 2024 Adobe. All rights reserved.
3
+ This file is licensed to you under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License. You may obtain a copy
5
+ of the License at http://www.apache.org/licenses/LICENSE-2.0
6
+
7
+ Unless required by applicable law or agreed to in writing, software distributed under
8
+ the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9
+ OF ANY KIND, either express or implied. See the License for the specific language
10
+ governing permissions and limitations under the License.
11
+ */
12
+
13
+ import { getTokenData } from "../data/tokens.js";
14
+
15
+ /**
16
+ * Create token-related MCP tools
17
+ * @returns {Array} Array of token tools
18
+ */
19
+ export function createTokenTools() {
20
+ return [
21
+ {
22
+ name: "query-tokens",
23
+ description:
24
+ "Search and retrieve Spectrum design tokens by name, type, or category",
25
+ inputSchema: {
26
+ type: "object",
27
+ properties: {
28
+ query: {
29
+ type: "string",
30
+ description:
31
+ "Search query to filter tokens (searches names, types, categories)",
32
+ },
33
+ category: {
34
+ type: "string",
35
+ description:
36
+ 'Filter by token category (e.g., "color", "layout", "typography")',
37
+ },
38
+ type: {
39
+ type: "string",
40
+ description: 'Filter by token type (e.g., "alias", "component")',
41
+ },
42
+ limit: {
43
+ type: "number",
44
+ description: "Maximum number of tokens to return (default: 50)",
45
+ default: 50,
46
+ },
47
+ },
48
+ },
49
+ handler: async (args) => {
50
+ const { query, category, type, limit = 50 } = args;
51
+ const tokenData = await getTokenData();
52
+
53
+ let results = [];
54
+
55
+ // Search through all token files
56
+ for (const [fileName, tokens] of Object.entries(tokenData)) {
57
+ // Skip if category filter doesn't match
58
+ if (
59
+ category &&
60
+ !fileName.toLowerCase().includes(category.toLowerCase())
61
+ ) {
62
+ continue;
63
+ }
64
+
65
+ // Process tokens based on their structure
66
+ const processedTokens = processTokens(tokens, fileName, query, type);
67
+ results.push(...processedTokens);
68
+ }
69
+
70
+ // Apply limit
71
+ results = results.slice(0, limit);
72
+
73
+ return {
74
+ total: results.length,
75
+ tokens: results,
76
+ query: { query, category, type, limit },
77
+ };
78
+ },
79
+ },
80
+ {
81
+ name: "get-token-categories",
82
+ description:
83
+ "Get all available token categories in the Spectrum design system",
84
+ inputSchema: {
85
+ type: "object",
86
+ properties: {},
87
+ },
88
+ handler: async () => {
89
+ const tokenData = await getTokenData();
90
+ const categories = Object.keys(tokenData).map((fileName) => {
91
+ // Extract category from filename (e.g., "color-palette.json" -> "color-palette")
92
+ return fileName.replace(".json", "");
93
+ });
94
+
95
+ return {
96
+ categories,
97
+ total: categories.length,
98
+ };
99
+ },
100
+ },
101
+ {
102
+ name: "get-token-details",
103
+ description:
104
+ "Get detailed information about a specific token by its path",
105
+ inputSchema: {
106
+ type: "object",
107
+ properties: {
108
+ tokenPath: {
109
+ type: "string",
110
+ description: 'The full path to the token (e.g., "color.blue.100")',
111
+ required: true,
112
+ },
113
+ category: {
114
+ type: "string",
115
+ description: 'Token category to search in (e.g., "color-palette")',
116
+ },
117
+ },
118
+ required: ["tokenPath"],
119
+ },
120
+ handler: async (args) => {
121
+ const { tokenPath, category } = args;
122
+ const tokenData = await getTokenData();
123
+
124
+ // Search for the token in all categories or specific category
125
+ const categoriesToSearch = category
126
+ ? [category]
127
+ : Object.keys(tokenData);
128
+
129
+ for (const cat of categoriesToSearch) {
130
+ const categoryData = tokenData[cat + ".json"] || tokenData[cat];
131
+ if (!categoryData) continue;
132
+
133
+ const token = findTokenByPath(categoryData, tokenPath);
134
+ if (token) {
135
+ return {
136
+ path: tokenPath,
137
+ category: cat,
138
+ token,
139
+ };
140
+ }
141
+ }
142
+
143
+ throw new Error(`Token not found: ${tokenPath}`);
144
+ },
145
+ },
146
+ {
147
+ name: "find-tokens-by-use-case",
148
+ description:
149
+ 'Find appropriate design tokens for specific component use cases (e.g., "button background", "text color", "border", "spacing")',
150
+ inputSchema: {
151
+ type: "object",
152
+ properties: {
153
+ useCase: {
154
+ type: "string",
155
+ description:
156
+ 'The use case or purpose (e.g., "button background", "text color", "border", "spacing", "error state")',
157
+ },
158
+ componentType: {
159
+ type: "string",
160
+ description:
161
+ 'Optional: Type of component being built (e.g., "button", "input", "card")',
162
+ },
163
+ },
164
+ required: ["useCase"],
165
+ },
166
+ handler: async ({ useCase, componentType }) => {
167
+ const data = await getTokenData();
168
+ const recommendations = [];
169
+
170
+ // Smart token recommendations based on use case
171
+ const useCaseLower = useCase.toLowerCase();
172
+ const compTypeLower = (componentType || "").toLowerCase();
173
+
174
+ // Define use case mappings
175
+ const useCasePatterns = {
176
+ background: [
177
+ "color-component",
178
+ "semantic-color-palette",
179
+ "color-palette",
180
+ ],
181
+ text: ["color-component", "semantic-color-palette", "typography"],
182
+ border: ["color-component", "semantic-color-palette"],
183
+ spacing: ["layout", "layout-component"],
184
+ padding: ["layout", "layout-component"],
185
+ margin: ["layout", "layout-component"],
186
+ font: ["typography"],
187
+ icon: ["icons", "layout"],
188
+ error: ["semantic-color-palette", "color-component"],
189
+ success: ["semantic-color-palette", "color-component"],
190
+ warning: ["semantic-color-palette", "color-component"],
191
+ accent: ["semantic-color-palette", "color-component"],
192
+ button: ["color-component", "layout-component"],
193
+ input: ["color-component", "layout-component"],
194
+ card: ["color-component", "layout-component"],
195
+ };
196
+
197
+ // Find relevant categories
198
+ const relevantCategories = [];
199
+ for (const [pattern, categories] of Object.entries(useCasePatterns)) {
200
+ if (
201
+ useCaseLower.includes(pattern) ||
202
+ compTypeLower.includes(pattern)
203
+ ) {
204
+ relevantCategories.push(...categories);
205
+ }
206
+ }
207
+
208
+ // If no specific patterns match, search all categories
209
+ const categoriesToSearch =
210
+ relevantCategories.length > 0
211
+ ? [...new Set(relevantCategories)]
212
+ : Object.keys(data);
213
+
214
+ // Search within relevant categories
215
+ for (const category of categoriesToSearch) {
216
+ const filename = category.includes(".json")
217
+ ? category
218
+ : `${category}.json`;
219
+ const tokens = data[filename];
220
+ if (!tokens) continue;
221
+
222
+ Object.entries(tokens).forEach(([name, token]) => {
223
+ const nameMatch =
224
+ name.toLowerCase().includes(useCaseLower) ||
225
+ (componentType && name.toLowerCase().includes(compTypeLower));
226
+ const descMatch =
227
+ token.description &&
228
+ token.description.toLowerCase().includes(useCaseLower);
229
+
230
+ if (nameMatch || descMatch) {
231
+ recommendations.push({
232
+ name,
233
+ category: filename,
234
+ value: token.value,
235
+ description: token.description,
236
+ schema: token.$schema,
237
+ uuid: token.uuid,
238
+ private: token.private || false,
239
+ deprecated: token.deprecated || false,
240
+ deprecated_comment: token.deprecated_comment,
241
+ renamed: token.renamed,
242
+ relevanceReason: nameMatch ? "name match" : "description match",
243
+ });
244
+ }
245
+ });
246
+ }
247
+
248
+ // Sort by relevance (non-private first, then by name match)
249
+ recommendations.sort((a, b) => {
250
+ if (a.private !== b.private) return a.private ? 1 : -1;
251
+ if (a.relevanceReason !== b.relevanceReason) {
252
+ return a.relevanceReason === "name match" ? -1 : 1;
253
+ }
254
+ return a.name.localeCompare(b.name);
255
+ });
256
+
257
+ return {
258
+ useCase,
259
+ componentType,
260
+ recommendations: recommendations.slice(0, 20), // Limit to top 20
261
+ totalFound: recommendations.length,
262
+ searchedCategories: categoriesToSearch,
263
+ };
264
+ },
265
+ },
266
+ {
267
+ name: "get-component-tokens",
268
+ description: "Get all tokens related to a specific component type",
269
+ inputSchema: {
270
+ type: "object",
271
+ properties: {
272
+ componentName: {
273
+ type: "string",
274
+ description:
275
+ 'Name of the component (e.g., "button", "input", "card", "modal")',
276
+ },
277
+ },
278
+ required: ["componentName"],
279
+ },
280
+ handler: async ({ componentName }) => {
281
+ const data = await getTokenData();
282
+ const componentTokens = [];
283
+ const componentLower = componentName.toLowerCase();
284
+
285
+ // Search through all token categories for component-specific tokens
286
+ Object.entries(data).forEach(([category, tokens]) => {
287
+ if (!tokens) return;
288
+
289
+ Object.entries(tokens).forEach(([name, token]) => {
290
+ if (name.toLowerCase().includes(componentLower)) {
291
+ componentTokens.push({
292
+ name,
293
+ category,
294
+ value: token.value,
295
+ description: token.description,
296
+ schema: token.$schema,
297
+ uuid: token.uuid,
298
+ private: token.private || false,
299
+ deprecated: token.deprecated || false,
300
+ deprecated_comment: token.deprecated_comment,
301
+ renamed: token.renamed,
302
+ });
303
+ }
304
+ });
305
+ });
306
+
307
+ // Group by category for better organization
308
+ const groupedTokens = componentTokens.reduce((acc, token) => {
309
+ if (!acc[token.category]) acc[token.category] = [];
310
+ acc[token.category].push(token);
311
+ return acc;
312
+ }, {});
313
+
314
+ return {
315
+ componentName,
316
+ tokensByCategory: groupedTokens,
317
+ totalTokens: componentTokens.length,
318
+ };
319
+ },
320
+ },
321
+ {
322
+ name: "get-design-recommendations",
323
+ description:
324
+ "Get design token recommendations for common design decisions and component states",
325
+ inputSchema: {
326
+ type: "object",
327
+ properties: {
328
+ intent: {
329
+ type: "string",
330
+ description:
331
+ 'Design intent (e.g., "primary", "secondary", "accent", "negative", "notice", "positive", "informative")',
332
+ },
333
+ state: {
334
+ type: "string",
335
+ description:
336
+ 'Component state (e.g., "default", "hover", "focus", "active", "disabled", "selected")',
337
+ },
338
+ context: {
339
+ type: "string",
340
+ description:
341
+ 'Usage context (e.g., "button", "input", "text", "background", "border", "icon")',
342
+ },
343
+ },
344
+ required: ["intent"],
345
+ },
346
+ handler: async ({ intent, state, context }) => {
347
+ const data = await getTokenData();
348
+ const recommendations = {
349
+ colors: [],
350
+ layout: [],
351
+ typography: [],
352
+ };
353
+
354
+ const intentLower = intent.toLowerCase();
355
+ const stateLower = (state || "").toLowerCase();
356
+ const contextLower = (context || "").toLowerCase();
357
+
358
+ // Search semantic colors first (these are typically the best recommendations)
359
+ const semanticColors = data["semantic-color-palette.json"] || {};
360
+ Object.entries(semanticColors).forEach(([name, token]) => {
361
+ const nameLower = name.toLowerCase();
362
+
363
+ // Intent matching
364
+ const intentMatch =
365
+ nameLower.includes(intentLower) ||
366
+ (intentLower === "error" && nameLower.includes("negative")) ||
367
+ (intentLower === "success" && nameLower.includes("positive")) ||
368
+ (intentLower === "warning" && nameLower.includes("notice"));
369
+
370
+ // State matching
371
+ const stateMatch = !state || nameLower.includes(stateLower);
372
+
373
+ // Context matching
374
+ const contextMatch = !context || nameLower.includes(contextLower);
375
+
376
+ if (intentMatch && stateMatch && contextMatch) {
377
+ recommendations.colors.push({
378
+ name,
379
+ value: token.value,
380
+ category: "semantic-color-palette",
381
+ type: "semantic",
382
+ confidence: "high",
383
+ });
384
+ }
385
+ });
386
+
387
+ // Search component colors if semantic colors don't provide enough options
388
+ if (recommendations.colors.length < 3) {
389
+ const componentColors = data["color-component.json"] || {};
390
+ Object.entries(componentColors).forEach(([name, token]) => {
391
+ const nameLower = name.toLowerCase();
392
+
393
+ // Intent and context matching for component colors
394
+ const intentMatch = nameLower.includes(intentLower);
395
+ const contextMatch = !context || nameLower.includes(contextLower);
396
+ const stateMatch = !state || nameLower.includes(stateLower);
397
+
398
+ if ((intentMatch || contextMatch) && stateMatch) {
399
+ recommendations.colors.push({
400
+ name,
401
+ value: token.value,
402
+ category: "color-component",
403
+ type: "component",
404
+ confidence: "medium",
405
+ });
406
+ }
407
+ });
408
+ }
409
+
410
+ // Layout recommendations if context suggests spacing/sizing
411
+ if (
412
+ context &&
413
+ ["button", "input", "spacing", "padding", "margin"].some((c) =>
414
+ contextLower.includes(c),
415
+ )
416
+ ) {
417
+ const layoutComponent = data["layout-component.json"] || {};
418
+ Object.entries(layoutComponent).forEach(([name, token]) => {
419
+ const nameLower = name.toLowerCase();
420
+
421
+ if (
422
+ contextLower &&
423
+ nameLower.includes(contextLower) &&
424
+ nameLower.includes(stateLower || "size")
425
+ ) {
426
+ recommendations.layout.push({
427
+ name,
428
+ value: token.value,
429
+ category: "layout-component",
430
+ type: "spacing",
431
+ confidence: "high",
432
+ });
433
+ }
434
+ });
435
+ }
436
+
437
+ // Typography recommendations for text contexts
438
+ if (
439
+ context &&
440
+ ["text", "label", "heading", "body"].some((c) =>
441
+ contextLower.includes(c),
442
+ )
443
+ ) {
444
+ const typography = data["typography.json"] || {};
445
+ Object.entries(typography).forEach(([name, token]) => {
446
+ const nameLower = name.toLowerCase();
447
+
448
+ if (nameLower.includes(contextLower)) {
449
+ recommendations.typography.push({
450
+ name,
451
+ value: token.value,
452
+ category: "typography",
453
+ type: "text",
454
+ confidence: "high",
455
+ });
456
+ }
457
+ });
458
+ }
459
+
460
+ // Sort by confidence and limit results
461
+ ["colors", "layout", "typography"].forEach((category) => {
462
+ recommendations[category] = recommendations[category]
463
+ .sort((a, b) => {
464
+ const confidenceOrder = { high: 0, medium: 1, low: 2 };
465
+ return (
466
+ confidenceOrder[a.confidence] - confidenceOrder[b.confidence]
467
+ );
468
+ })
469
+ .slice(0, 10);
470
+ });
471
+
472
+ return {
473
+ intent,
474
+ state,
475
+ context,
476
+ recommendations,
477
+ totalFound:
478
+ recommendations.colors.length +
479
+ recommendations.layout.length +
480
+ recommendations.typography.length,
481
+ };
482
+ },
483
+ },
484
+ ];
485
+ }
486
+
487
+ /**
488
+ * Process tokens based on search criteria
489
+ * @param {Object} tokens - Token data structure
490
+ * @param {string} fileName - Name of the token file
491
+ * @param {string} query - Search query
492
+ * @param {string} type - Type filter
493
+ * @returns {Array} Processed tokens
494
+ */
495
+ function processTokens(tokens, fileName, query, type) {
496
+ const results = [];
497
+ const category = fileName.replace(".json", "");
498
+
499
+ function traverse(obj, path = "") {
500
+ for (const [key, value] of Object.entries(obj)) {
501
+ const currentPath = path ? `${path}.${key}` : key;
502
+
503
+ if (value && typeof value === "object") {
504
+ if (value.$value !== undefined || value.value !== undefined) {
505
+ // This is a token
506
+ const tokenType = value.$type || value.type || "unknown";
507
+
508
+ // Apply type filter
509
+ if (type && tokenType !== type) {
510
+ continue;
511
+ }
512
+
513
+ // Apply query filter
514
+ if (query && !matchesQuery(currentPath, value, query)) {
515
+ continue;
516
+ }
517
+
518
+ results.push({
519
+ name: key,
520
+ path: currentPath,
521
+ category,
522
+ type: tokenType,
523
+ value: value.$value || value.value,
524
+ description: value.$description || value.description,
525
+ extensions: value.$extensions || value.extensions,
526
+ uuid: value.uuid,
527
+ private: value.private || false,
528
+ deprecated: value.deprecated || false,
529
+ deprecated_comment: value.deprecated_comment,
530
+ renamed: value.renamed,
531
+ });
532
+ } else {
533
+ // Recurse into nested objects
534
+ traverse(value, currentPath);
535
+ }
536
+ }
537
+ }
538
+ }
539
+
540
+ traverse(tokens);
541
+ return results;
542
+ }
543
+
544
+ /**
545
+ * Find a token by its path
546
+ * @param {Object} tokens - Token data structure
547
+ * @param {string} path - Token path (e.g., "color.blue.100")
548
+ * @returns {Object|null} Token object or null if not found
549
+ */
550
+ function findTokenByPath(tokens, path) {
551
+ const parts = path.split(".");
552
+ let current = tokens;
553
+
554
+ for (const part of parts) {
555
+ if (current[part] === undefined) {
556
+ return null;
557
+ }
558
+ current = current[part];
559
+ }
560
+
561
+ return current;
562
+ }
563
+
564
+ /**
565
+ * Check if a token matches the search query
566
+ * @param {string} path - Token path
567
+ * @param {Object} token - Token object
568
+ * @param {string} query - Search query
569
+ * @returns {boolean} Whether the token matches
570
+ */
571
+ function matchesQuery(path, token, query) {
572
+ const searchText = query.toLowerCase();
573
+
574
+ // Search in path
575
+ if (path.toLowerCase().includes(searchText)) {
576
+ return true;
577
+ }
578
+
579
+ // Search in description
580
+ const description = token.$description || token.description || "";
581
+ if (description.toLowerCase().includes(searchText)) {
582
+ return true;
583
+ }
584
+
585
+ // Search in value (for string values)
586
+ const value = token.$value || token.value || "";
587
+ if (typeof value === "string" && value.toLowerCase().includes(searchText)) {
588
+ return true;
589
+ }
590
+
591
+ return false;
592
+ }