@adobe/spectrum-design-data-mcp 1.0.0

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,111 @@
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 { readFileSync } from "fs";
14
+ import { join, dirname } from "path";
15
+ import { fileURLToPath } from "url";
16
+
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = dirname(__filename);
19
+
20
+ /**
21
+ * Get token data from the spectrum-tokens package
22
+ * @returns {Promise<Object>} Token data organized by category
23
+ */
24
+ export async function getTokenData() {
25
+ try {
26
+ // Try to import from the workspace package first
27
+ const spectrumTokens = await import("@adobe/spectrum-tokens");
28
+
29
+ // If the package exports token data directly, use it
30
+ if (spectrumTokens.default || spectrumTokens.tokens) {
31
+ return spectrumTokens.default || spectrumTokens.tokens;
32
+ }
33
+
34
+ // Otherwise, read the token files directly from the package
35
+ return await loadTokenFilesFromPackage();
36
+ } catch (error) {
37
+ console.error(
38
+ "Failed to load token data from package, trying direct file access:",
39
+ error,
40
+ );
41
+ return await loadTokenFilesDirectly();
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Load token files from the spectrum-tokens package structure
47
+ * @returns {Promise<Object>} Token data
48
+ */
49
+ async function loadTokenFilesFromPackage() {
50
+ // This would be the ideal approach - loading from the actual package
51
+ // For now, we'll fall back to direct file access
52
+ return await loadTokenFilesDirectly();
53
+ }
54
+
55
+ /**
56
+ * Load token files directly from the repository structure
57
+ * @returns {Promise<Object>} Token data
58
+ */
59
+ async function loadTokenFilesDirectly() {
60
+ const tokenData = {};
61
+
62
+ // Path to the tokens source directory
63
+ const tokensPath = join(__dirname, "../../../../packages/tokens/src");
64
+
65
+ // List of token files to load
66
+ const tokenFiles = [
67
+ "color-aliases.json",
68
+ "color-component.json",
69
+ "color-palette.json",
70
+ "icons.json",
71
+ "layout-component.json",
72
+ "layout.json",
73
+ "semantic-color-palette.json",
74
+ "typography.json",
75
+ ];
76
+
77
+ for (const fileName of tokenFiles) {
78
+ try {
79
+ const filePath = join(tokensPath, fileName);
80
+ const fileContent = readFileSync(filePath, "utf8");
81
+ tokenData[fileName] = JSON.parse(fileContent);
82
+ } catch (error) {
83
+ console.error(`Failed to load token file ${fileName}:`, error);
84
+ // Continue loading other files even if one fails
85
+ }
86
+ }
87
+
88
+ return tokenData;
89
+ }
90
+
91
+ /**
92
+ * Get available token categories
93
+ * @returns {Promise<Array<string>>} List of token categories
94
+ */
95
+ export async function getTokenCategories() {
96
+ const tokenData = await getTokenData();
97
+ return Object.keys(tokenData).map((fileName) =>
98
+ fileName.replace(".json", ""),
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Get tokens from a specific category
104
+ * @param {string} category - Token category name
105
+ * @returns {Promise<Object|null>} Token data for the category
106
+ */
107
+ export async function getTokensByCategory(category) {
108
+ const tokenData = await getTokenData();
109
+ const fileName = category.endsWith(".json") ? category : `${category}.json`;
110
+ return tokenData[fileName] || null;
111
+ }
package/src/index.js ADDED
@@ -0,0 +1,97 @@
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 { Server } from "@modelcontextprotocol/sdk/server/index.js";
14
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
15
+ import {
16
+ CallToolRequestSchema,
17
+ ListToolsRequestSchema,
18
+ } from "@modelcontextprotocol/sdk/types.js";
19
+
20
+ import { createTokenTools } from "./tools/tokens.js";
21
+ import { createSchemaTools } from "./tools/schemas.js";
22
+
23
+ /**
24
+ * Create and configure the Spectrum Design Data MCP server
25
+ * @returns {Server} Configured MCP server instance
26
+ */
27
+ export function createMCPServer() {
28
+ const server = new Server(
29
+ {
30
+ name: "spectrum-design-data",
31
+ version: "0.1.0",
32
+ },
33
+ {
34
+ capabilities: {
35
+ tools: {},
36
+ },
37
+ },
38
+ );
39
+
40
+ // Combine all available tools
41
+ const allTools = [...createTokenTools(), ...createSchemaTools()];
42
+
43
+ // Register list_tools handler
44
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
45
+ return {
46
+ tools: allTools.map((tool) => ({
47
+ name: tool.name,
48
+ description: tool.description,
49
+ inputSchema: tool.inputSchema,
50
+ })),
51
+ };
52
+ });
53
+
54
+ // Register call_tool handler
55
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
56
+ const { name, arguments: args } = request.params;
57
+
58
+ const tool = allTools.find((t) => t.name === name);
59
+ if (!tool) {
60
+ throw new Error(`Tool not found: ${name}`);
61
+ }
62
+
63
+ try {
64
+ const result = await tool.handler(args || {});
65
+ return {
66
+ content: [
67
+ {
68
+ type: "text",
69
+ text:
70
+ typeof result === "string"
71
+ ? result
72
+ : JSON.stringify(result, null, 2),
73
+ },
74
+ ],
75
+ };
76
+ } catch (error) {
77
+ throw new Error(`Tool execution failed: ${error.message}`);
78
+ }
79
+ });
80
+
81
+ return server;
82
+ }
83
+
84
+ /**
85
+ * Start the MCP server with stdio transport
86
+ */
87
+ export async function startServer() {
88
+ const server = createMCPServer();
89
+ const transport = new StdioServerTransport();
90
+ await server.connect(transport);
91
+
92
+ // Log server start for debugging (this goes to stderr, not stdout which is used for MCP)
93
+ console.error("Spectrum Design Data MCP server started");
94
+ }
95
+
96
+ // Export for testing
97
+ export { createTokenTools, createSchemaTools };
@@ -0,0 +1,472 @@
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 { getSchemaData } from "../data/schemas.js";
14
+
15
+ /**
16
+ * Create schema-related MCP tools
17
+ * @returns {Array} Array of schema tools
18
+ */
19
+ export function createSchemaTools() {
20
+ return [
21
+ {
22
+ name: "query-component-schemas",
23
+ description: "Search and retrieve Spectrum component API schemas",
24
+ inputSchema: {
25
+ type: "object",
26
+ properties: {
27
+ component: {
28
+ type: "string",
29
+ description:
30
+ 'Component name to search for (e.g., "button", "action-button")',
31
+ },
32
+ query: {
33
+ type: "string",
34
+ description:
35
+ "Search query to filter schemas (searches component names, descriptions)",
36
+ },
37
+ limit: {
38
+ type: "number",
39
+ description: "Maximum number of schemas to return (default: 20)",
40
+ default: 20,
41
+ },
42
+ },
43
+ },
44
+ handler: async (args) => {
45
+ const { component, query, limit = 20 } = args;
46
+ const schemaData = await getSchemaData();
47
+
48
+ let results = [];
49
+
50
+ // Search through component schemas
51
+ for (const [fileName, schema] of Object.entries(
52
+ schemaData.components,
53
+ )) {
54
+ const componentName = fileName.replace(".json", "");
55
+
56
+ // Apply component filter
57
+ if (component && !componentName.includes(component.toLowerCase())) {
58
+ continue;
59
+ }
60
+
61
+ // Apply query filter
62
+ if (query && !matchesSchemaQuery(componentName, schema, query)) {
63
+ continue;
64
+ }
65
+
66
+ results.push({
67
+ component: componentName,
68
+ fileName,
69
+ title: schema.title,
70
+ description: schema.description,
71
+ properties: Object.keys(schema.properties || {}),
72
+ required: schema.required || [],
73
+ schema,
74
+ });
75
+ }
76
+
77
+ // Apply limit
78
+ results = results.slice(0, limit);
79
+
80
+ return {
81
+ total: results.length,
82
+ schemas: results,
83
+ query: { component, query, limit },
84
+ };
85
+ },
86
+ },
87
+ {
88
+ name: "get-component-schema",
89
+ description: "Get the complete schema for a specific component",
90
+ inputSchema: {
91
+ type: "object",
92
+ properties: {
93
+ component: {
94
+ type: "string",
95
+ description: 'Component name (e.g., "action-button")',
96
+ required: true,
97
+ },
98
+ },
99
+ required: ["component"],
100
+ },
101
+ handler: async (args) => {
102
+ const { component } = args;
103
+ const schemaData = await getSchemaData();
104
+
105
+ const fileName = `${component}.json`;
106
+ const schema = schemaData.components[fileName];
107
+
108
+ if (!schema) {
109
+ throw new Error(`Component schema not found: ${component}`);
110
+ }
111
+
112
+ return {
113
+ component,
114
+ schema,
115
+ metadata: {
116
+ title: schema.title,
117
+ description: schema.description,
118
+ propertyCount: Object.keys(schema.properties || {}).length,
119
+ requiredCount: (schema.required || []).length,
120
+ },
121
+ };
122
+ },
123
+ },
124
+ {
125
+ name: "list-components",
126
+ description: "List all available Spectrum components with schemas",
127
+ inputSchema: {
128
+ type: "object",
129
+ properties: {},
130
+ },
131
+ handler: async () => {
132
+ const schemaData = await getSchemaData();
133
+
134
+ const components = Object.keys(schemaData.components).map(
135
+ (fileName) => {
136
+ const componentName = fileName.replace(".json", "");
137
+ const schema = schemaData.components[fileName];
138
+
139
+ return {
140
+ name: componentName,
141
+ title: schema.title,
142
+ description: schema.description,
143
+ propertyCount: Object.keys(schema.properties || {}).length,
144
+ hasRequired: (schema.required || []).length > 0,
145
+ };
146
+ },
147
+ );
148
+
149
+ return {
150
+ total: components.length,
151
+ components: components.sort((a, b) => a.name.localeCompare(b.name)),
152
+ };
153
+ },
154
+ },
155
+ {
156
+ name: "validate-component-props",
157
+ description: "Validate component properties against their schema",
158
+ inputSchema: {
159
+ type: "object",
160
+ properties: {
161
+ component: {
162
+ type: "string",
163
+ description: "Component name to validate against",
164
+ required: true,
165
+ },
166
+ props: {
167
+ type: "object",
168
+ description: "Component properties to validate",
169
+ required: true,
170
+ },
171
+ },
172
+ required: ["component", "props"],
173
+ },
174
+ handler: async (args) => {
175
+ const { component, props } = args;
176
+ const schemaData = await getSchemaData();
177
+
178
+ const fileName = `${component}.json`;
179
+ const schema = schemaData.components[fileName];
180
+
181
+ if (!schema) {
182
+ throw new Error(`Component schema not found: ${component}`);
183
+ }
184
+
185
+ // Basic validation logic
186
+ const validationResults = validateProps(props, schema);
187
+
188
+ return {
189
+ component,
190
+ valid: validationResults.valid,
191
+ errors: validationResults.errors,
192
+ warnings: validationResults.warnings,
193
+ props,
194
+ };
195
+ },
196
+ },
197
+ {
198
+ name: "get-type-schemas",
199
+ description: "Get type definitions used in component schemas",
200
+ inputSchema: {
201
+ type: "object",
202
+ properties: {
203
+ type: {
204
+ type: "string",
205
+ description: 'Specific type to retrieve (e.g., "hex-color")',
206
+ },
207
+ },
208
+ },
209
+ handler: async (args) => {
210
+ const { type } = args;
211
+ const schemaData = await getSchemaData();
212
+
213
+ if (type) {
214
+ const typeSchema = schemaData.types[`${type}.json`];
215
+ if (!typeSchema) {
216
+ throw new Error(`Type schema not found: ${type}`);
217
+ }
218
+
219
+ return {
220
+ type,
221
+ schema: typeSchema,
222
+ };
223
+ }
224
+
225
+ // Return all types
226
+ const types = Object.keys(schemaData.types).map((fileName) => {
227
+ const typeName = fileName.replace(".json", "");
228
+ const typeSchema = schemaData.types[fileName];
229
+
230
+ return {
231
+ name: typeName,
232
+ title: typeSchema.title,
233
+ description: typeSchema.description,
234
+ type: typeSchema.type,
235
+ };
236
+ });
237
+
238
+ return {
239
+ total: types.length,
240
+ types: types.sort((a, b) => a.name.localeCompare(b.name)),
241
+ };
242
+ },
243
+ },
244
+ {
245
+ name: "get-component-options",
246
+ description:
247
+ "Get all available options/properties for a component in a user-friendly format - perfect for discovering what options a component supports",
248
+ inputSchema: {
249
+ type: "object",
250
+ properties: {
251
+ component: {
252
+ type: "string",
253
+ description:
254
+ 'Component name (e.g., "action-button", "text-field", "menu")',
255
+ required: true,
256
+ },
257
+ detailed: {
258
+ type: "boolean",
259
+ description:
260
+ "Include detailed property information like enums, default values, etc.",
261
+ default: false,
262
+ },
263
+ },
264
+ required: ["component"],
265
+ },
266
+ handler: async (args) => {
267
+ const { component, detailed = false } = args;
268
+ const schemaData = await getSchemaData();
269
+
270
+ const fileName = `${component}.json`;
271
+ const schema = schemaData.components[fileName];
272
+
273
+ if (!schema) {
274
+ throw new Error(
275
+ `Component not found: ${component}. Use list-components to see available components.`,
276
+ );
277
+ }
278
+
279
+ const componentInfo = {
280
+ name: component,
281
+ title: schema.title || component,
282
+ description: schema.description,
283
+ totalProperties: 0,
284
+ properties: [],
285
+ };
286
+
287
+ if (schema.properties) {
288
+ componentInfo.totalProperties = Object.keys(schema.properties).length;
289
+
290
+ Object.entries(schema.properties).forEach(([propName, propDef]) => {
291
+ const propInfo = {
292
+ name: propName,
293
+ type: propDef.type || "object",
294
+ required: schema.required
295
+ ? schema.required.includes(propName)
296
+ : false,
297
+ description: propDef.description,
298
+ };
299
+
300
+ if (detailed) {
301
+ // Add detailed information
302
+ if (propDef.enum) {
303
+ propInfo.possibleValues = propDef.enum;
304
+ }
305
+ if (propDef.default !== undefined) {
306
+ propInfo.defaultValue = propDef.default;
307
+ }
308
+ if (propDef.properties) {
309
+ propInfo.nestedProperties = Object.keys(propDef.properties);
310
+ }
311
+ if (propDef.$ref) {
312
+ propInfo.reference = propDef.$ref;
313
+ }
314
+ }
315
+
316
+ componentInfo.properties.push(propInfo);
317
+ });
318
+
319
+ // Sort properties: required first, then alphabetical
320
+ componentInfo.properties.sort((a, b) => {
321
+ if (a.required !== b.required) return a.required ? -1 : 1;
322
+ return a.name.localeCompare(b.name);
323
+ });
324
+ }
325
+
326
+ return componentInfo;
327
+ },
328
+ },
329
+ {
330
+ name: "search-components-by-feature",
331
+ description:
332
+ 'Find components that have specific features or properties (e.g., "size", "disabled", "selected")',
333
+ inputSchema: {
334
+ type: "object",
335
+ properties: {
336
+ feature: {
337
+ type: "string",
338
+ description:
339
+ 'The feature/property to search for (e.g., "size", "disabled", "icon", "label")',
340
+ required: true,
341
+ },
342
+ },
343
+ required: ["feature"],
344
+ },
345
+ handler: async (args) => {
346
+ const { feature } = args;
347
+ const schemaData = await getSchemaData();
348
+ const matchingComponents = [];
349
+
350
+ Object.entries(schemaData.components).forEach(([fileName, schema]) => {
351
+ const componentName = fileName.replace(".json", "");
352
+
353
+ if (schema.properties) {
354
+ const hasFeature = Object.keys(schema.properties).some((prop) =>
355
+ prop.toLowerCase().includes(feature.toLowerCase()),
356
+ );
357
+
358
+ if (hasFeature) {
359
+ const matchingProps = Object.keys(schema.properties).filter(
360
+ (prop) => prop.toLowerCase().includes(feature.toLowerCase()),
361
+ );
362
+
363
+ matchingComponents.push({
364
+ name: componentName,
365
+ title: schema.title || componentName,
366
+ description: schema.description,
367
+ matchingProperties: matchingProps,
368
+ totalProperties: Object.keys(schema.properties).length,
369
+ });
370
+ }
371
+ }
372
+ });
373
+
374
+ return {
375
+ feature,
376
+ totalMatches: matchingComponents.length,
377
+ components: matchingComponents.sort((a, b) =>
378
+ a.name.localeCompare(b.name),
379
+ ),
380
+ };
381
+ },
382
+ },
383
+ ];
384
+ }
385
+
386
+ /**
387
+ * Check if a schema matches the search query
388
+ * @param {string} componentName - Component name
389
+ * @param {Object} schema - Schema object
390
+ * @param {string} query - Search query
391
+ * @returns {boolean} Whether the schema matches
392
+ */
393
+ function matchesSchemaQuery(componentName, schema, query) {
394
+ const searchText = query.toLowerCase();
395
+
396
+ // Search in component name
397
+ if (componentName.toLowerCase().includes(searchText)) {
398
+ return true;
399
+ }
400
+
401
+ // Search in title
402
+ if (schema.title && schema.title.toLowerCase().includes(searchText)) {
403
+ return true;
404
+ }
405
+
406
+ // Search in description
407
+ if (
408
+ schema.description &&
409
+ schema.description.toLowerCase().includes(searchText)
410
+ ) {
411
+ return true;
412
+ }
413
+
414
+ // Search in property names
415
+ if (schema.properties) {
416
+ for (const propName of Object.keys(schema.properties)) {
417
+ if (propName.toLowerCase().includes(searchText)) {
418
+ return true;
419
+ }
420
+ }
421
+ }
422
+
423
+ return false;
424
+ }
425
+
426
+ /**
427
+ * Basic validation of properties against schema
428
+ * @param {Object} props - Properties to validate
429
+ * @param {Object} schema - Schema to validate against
430
+ * @returns {Object} Validation results
431
+ */
432
+ function validateProps(props, schema) {
433
+ const errors = [];
434
+ const warnings = [];
435
+
436
+ // Check required properties
437
+ const required = schema.required || [];
438
+ for (const requiredProp of required) {
439
+ if (!(requiredProp in props)) {
440
+ errors.push(`Missing required property: ${requiredProp}`);
441
+ }
442
+ }
443
+
444
+ // Check property types (basic validation)
445
+ const schemaProps = schema.properties || {};
446
+ for (const [propName, propValue] of Object.entries(props)) {
447
+ const propSchema = schemaProps[propName];
448
+
449
+ if (!propSchema) {
450
+ warnings.push(`Unknown property: ${propName}`);
451
+ continue;
452
+ }
453
+
454
+ // Basic type checking
455
+ if (propSchema.type) {
456
+ const expectedType = propSchema.type;
457
+ const actualType = Array.isArray(propValue) ? "array" : typeof propValue;
458
+
459
+ if (expectedType !== actualType) {
460
+ errors.push(
461
+ `Property ${propName} should be ${expectedType}, got ${actualType}`,
462
+ );
463
+ }
464
+ }
465
+ }
466
+
467
+ return {
468
+ valid: errors.length === 0,
469
+ errors,
470
+ warnings,
471
+ };
472
+ }