@s2life/mcp 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/match.mjs ADDED
@@ -0,0 +1,24 @@
1
+ // 공백 없는 한국어 조사 결합과 영문 대소문자를 함께 흡수한다. 외부 모델이나 상태를 쓰지 않는다.
2
+ const normalize = (text) => text.normalize('NFKC').toLocaleLowerCase('ko-KR').replace(/\s+/gu, '');
3
+ export function matchComponents(description, components, limit = 5) {
4
+ const query = normalize(description);
5
+ if (!query) return [];
6
+ const words = description.normalize('NFKC').toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((word) => word.length >= 2);
7
+ return components.filter((c) => c.kind !== 'constant').map((component) => {
8
+ let score = 0;
9
+ const reasons = [];
10
+ if (query.includes(normalize(component.name))) { const weight = query === normalize(component.name) ? 2000 : 1000;
11
+ score += weight; reasons.push(`이름 일치: ${component.name} (+${weight})`); }
12
+ for (const keyword of component.keywords) if (query.includes(normalize(keyword))) {
13
+ // 한 글자 문맥(표·행)이 작업 목적(요약)을 압도하지 않게 가중치를 낮춘다.
14
+ const weight = normalize(keyword).length === 1 ? 4 : 20;
15
+ score += weight; reasons.push(`키워드 일치: ${keyword} (+${weight})`);
16
+ }
17
+ for (const [field, weight] of [['purpose', 2], ['useWhen', 5]]) {
18
+ const text = normalize(Array.isArray(component[field]) ? component[field].join(' ') : component[field]);
19
+ const matches = [...new Set(words.filter((word) => text.includes(normalize(word))))];
20
+ if (matches.length) { score += matches.length * weight; reasons.push(`${field}: ${matches.join(', ')} (+${matches.length * weight})`); }
21
+ }
22
+ return { name: component.name, score, reasons, purpose: component.purpose, useWhen: component.useWhen, dont: component.dont };
23
+ }).filter((c) => c.score > 0).sort((a, b) => b.score - a.score || a.name.localeCompare(b.name, 'en')).slice(0, limit);
24
+ }
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@s2life/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "description": "S2Life 디자인 시스템 MCP 서버 — AI 가 토큰·컴포넌트·규칙을 질의한다",
6
+ "bin": {
7
+ "s2life-mcp": "./server.mjs"
8
+ },
9
+ "files": [
10
+ "server.mjs",
11
+ "manifest.json",
12
+ "match.mjs"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22"
16
+ },
17
+ "scripts": {
18
+ "build": "node ../../docs/research/mcp-build.mjs",
19
+ "prepack": "pnpm build",
20
+ "prepublishOnly": "node ../../scripts/publish-guard.mjs"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public",
24
+ "registry": "https://registry.npmjs.org"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/tom783/design-system.git",
29
+ "directory": "packages/mcp"
30
+ },
31
+ "homepage": "https://github.com/tom783/design-system#readme",
32
+ "bugs": {
33
+ "url": "https://github.com/tom783/design-system/issues"
34
+ },
35
+ "license": "UNLICENSED"
36
+ }
package/server.mjs ADDED
@@ -0,0 +1,112 @@
1
+ #!/usr/bin/env node
2
+ import { readFile } from 'node:fs/promises';
3
+ import { createInterface } from 'node:readline';
4
+ import { matchComponents } from './match.mjs';
5
+
6
+ const { version } = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
7
+
8
+ const versions = ['2025-06-18', '2025-03-26', '2024-11-05'];
9
+ const objectSchema = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
10
+ const string = { type: 'string', minLength: 1 };
11
+ const definitions = [
12
+ ['get_token','토큰 조회','토큰 이름으로 값·참조·용도·Tailwind 클래스와 라이트/다크 값을 조회한다.',objectSchema({ name: string }, ['name'])],
13
+ ['search_tokens','토큰 검색','category 또는 부분 문자열 query로 토큰을 찾는다. 분류: primitive, semantic, typography, spacing, shape, sizing, motion, loading.',objectSchema({ category: string, query: string })],
14
+ ['list_components','컴포넌트 목록','공개 컴포넌트와 상수의 이름·용도·import 구문을 조회한다.',objectSchema({})],
15
+ ['get_component','컴포넌트 조회','props·slots·규칙·금지사항·관련 컴포넌트를 조회한다. inherited props는 표준 DOM 속성이다.',objectSchema({ name: string }, ['name'])],
16
+ ['which_component','컴포넌트 선택','작업 설명을 단순 점수로 매칭해 후보·판단 근거·useWhen·dont를 함께 준다. 최종 선택은 호출자가 판단한다.',objectSchema({ description: string, limit: { type: 'integer', minimum: 1, maximum: 10 } }, ['description'])],
17
+ ['get_rules','규칙 조회','주제별 하드 규칙과 DESIGN.md 출처를 조회한다. topic 생략 시 전체 규칙.',objectSchema({ topic: { type: 'string', enum: ['색','타이포','간격','로딩','폼','안내','차트','표'] } })],
18
+ ].map(([name,title,description,inputSchema]) => ({ name,title,description,inputSchema }));
19
+ const resources = [
20
+ { uri: 'design://tokens', name: 'tokens', title: '전체 토큰', description: '생성된 토큰의 값·참조·용도·테마·클래스', mimeType: 'application/json' },
21
+ { uri: 'design://components', name: 'components', title: '컴포넌트 카탈로그', description: '공개 API와 선택 의도', mimeType: 'application/json' },
22
+ { uri: 'design://principles', name: 'principles', title: '하드 규칙', description: '주제별 규칙과 출처', mimeType: 'text/markdown' },
23
+ ];
24
+ class RpcError extends Error { constructor(code, message) { super(message); this.code = code; } }
25
+ const invalid = (message) => { throw new RpcError(-32602, message); };
26
+ const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
27
+ function validateArguments(args, schema) {
28
+ if (!isObject(args)) invalid('arguments는 객체여야 합니다.');
29
+ for (const name of schema.required) if (!Object.hasOwn(args, name)) invalid(`필수 인자 누락: ${name}`);
30
+ for (const [name, value] of Object.entries(args)) {
31
+ const rule = Object.hasOwn(schema.properties, name) ? schema.properties[name] : undefined;
32
+ if (!rule) invalid(`알 수 없는 인자: ${name}`);
33
+ if (rule.type === 'string' && (typeof value !== 'string' || !value.trim())) invalid(`${name}: 비어 있지 않은 문자열이 필요합니다.`);
34
+ if (rule.enum && !rule.enum.includes(value)) invalid(`${name}: ${rule.enum.join(', ')} 중 하나여야 합니다.`);
35
+ if (rule.type === 'integer' && (!Number.isInteger(value) || value < rule.minimum || value > rule.maximum)) invalid(`${name}: ${rule.minimum}~${rule.maximum} 정수가 필요합니다.`);
36
+ }
37
+ }
38
+ const structured = (data, isError = false) => ({ content: [{ type: 'text', text: JSON.stringify(data) }], structuredContent: data, ...(isError ? { isError: true } : {}) });
39
+ const missing = (message) => structured({ message }, true);
40
+ const normalizeName = (name) => name.trim().replace(/^--/, '').toLowerCase();
41
+
42
+ function callTool(manifest, params) {
43
+ if (!isObject(params) || typeof params.name !== 'string') invalid('tools/call에는 name이 필요합니다.');
44
+ const definition = definitions.find((tool) => tool.name === params.name);
45
+ if (!definition) invalid(`알 수 없는 도구: ${params.name}`);
46
+ const args = params.arguments === undefined ? {} : params.arguments;
47
+ validateArguments(args, definition.inputSchema);
48
+ switch (params.name) {
49
+ case 'get_token': {
50
+ const token = manifest.tokens.find((t) => t.name.toLowerCase() === normalizeName(args.name));
51
+ return token ? structured(token) : missing('그런 토큰이 없습니다. search_tokens로 이름을 찾아보세요.');
52
+ }
53
+ case 'search_tokens': {
54
+ const query = args.query?.trim().toLowerCase().replace(/^--/, '') ?? '';
55
+ const tokens = manifest.tokens.filter((t) => (!args.category || t.category === args.category.trim().toLowerCase()) && `${t.name} ${t.purpose} ${t.tailwind.join(' ')}`.toLowerCase().includes(query));
56
+ return tokens.length ? structured({ tokens }) : missing('일치하는 토큰이 없습니다. category를 생략하거나 search_tokens의 query를 짧게 해보세요.');
57
+ }
58
+ case 'list_components': return structured({ components: manifest.components.map(({ name, kind, purpose, import: statement }) => ({ name, kind, purpose, import: statement })) });
59
+ case 'get_component': {
60
+ const component = manifest.components.find((c) => c.name.toLowerCase() === args.name.trim().toLowerCase());
61
+ return component ? structured(component) : missing('그런 컴포넌트가 없습니다. list_components로 이름을 확인하세요.');
62
+ }
63
+ case 'which_component': {
64
+ const candidates = matchComponents(args.description, manifest.components, args.limit);
65
+ return candidates.length ? structured({ candidates }) : missing('일치하는 후보가 없습니다. list_components를 보세요.');
66
+ }
67
+ case 'get_rules': return structured({ rules: manifest.principles.filter((p) => !args.topic || p.topic === args.topic) });
68
+ }
69
+ }
70
+ function dispatch(manifest, method, params) {
71
+ switch (method) {
72
+ case 'initialize':
73
+ if (!isObject(params) || typeof params.protocolVersion !== 'string' || !isObject(params.capabilities) || !isObject(params.clientInfo) || typeof params.clientInfo.name !== 'string' || typeof params.clientInfo.version !== 'string') invalid('initialize에 protocolVersion, capabilities, clientInfo가 필요합니다.');
74
+ return { protocolVersion: versions.includes(params.protocolVersion) ? params.protocolVersion : versions[0], capabilities: { tools: {}, resources: {} }, serverInfo: { name: 's2life', version }, instructions: '작업 설명으로 which_component를 먼저 호출하고 후보의 useWhen·dont를 비교하세요. 선택한 컴포넌트는 get_component로 props·slots·규칙을 확인하고, 색·치수는 search_tokens와 get_token으로 찾으세요. get_rules로 주제별 하드 규칙을 확인하며 원시 색 대신 의미 토큰을 사용하세요. 전체 목록은 list_components와 design:// 리소스에서 조회할 수 있습니다. 이 서버는 읽기 전용입니다.' };
75
+ case 'ping': return {};
76
+ case 'tools/list': return { tools: definitions };
77
+ case 'tools/call': return callTool(manifest, params);
78
+ case 'resources/list': return { resources };
79
+ case 'resources/read': {
80
+ if (!isObject(params) || typeof params.uri !== 'string') invalid('resources/read에는 uri가 필요합니다.');
81
+ const resource = resources.find((r) => r.uri === params.uri);
82
+ if (!resource) throw new RpcError(-32002, `없는 리소스: ${params.uri}`);
83
+ const value = params.uri === 'design://tokens' ? manifest.tokens : params.uri === 'design://components' ? manifest.components
84
+ : manifest.principles.map((p) => `- **${p.topic}** ${p.text} (${p.source})`).join('\n');
85
+ return { contents: [{ uri: resource.uri, mimeType: resource.mimeType, text: typeof value === 'string' ? value : JSON.stringify(value) }] };
86
+ }
87
+ default: throw new RpcError(-32601, `알 수 없는 메서드: ${method}`);
88
+ }
89
+ }
90
+
91
+ async function main() {
92
+ const manifest = JSON.parse(await readFile(new URL('./manifest.json', import.meta.url), 'utf8'));
93
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
94
+ // stdout을 쓰는 유일한 지점이다. JSON.stringify가 문자열 내부 개행도 이스케이프한다.
95
+ const send = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
96
+ for await (const line of lines) {
97
+ let message;
98
+ try { message = JSON.parse(line); }
99
+ catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'JSON 파싱 실패' } }); continue; }
100
+ const hasId = isObject(message) && Object.hasOwn(message, 'id');
101
+ const validId = hasId && (message.id === null || typeof message.id === 'string' || (typeof message.id === 'number' && Number.isFinite(message.id)));
102
+ if (!isObject(message) || message.jsonrpc !== '2.0' || typeof message.method !== 'string' || (hasId && !validId)) {
103
+ // 유효한 알림에는 어떤 응답도 보내지 않는다. 잘못된 요청의 id는 null로 돌려준다.
104
+ if (isObject(message) && !hasId && typeof message.method === 'string') continue;
105
+ send({ jsonrpc: '2.0', id: validId ? message.id : null, error: { code: -32600, message: '잘못된 JSON-RPC 요청' } }); continue;
106
+ }
107
+ if (!hasId) continue;
108
+ try { send({ jsonrpc: '2.0', id: message.id, result: dispatch(manifest, message.method, message.params) }); }
109
+ catch (error) { send({ jsonrpc: '2.0', id: message.id, error: { code: error instanceof RpcError ? error.code : -32603, message: error instanceof RpcError ? error.message : '내부 오류' } }); }
110
+ }
111
+ }
112
+ main().catch((error) => { console.error(`MCP 시작 실패: ${error.message}`); process.exitCode = 1; });