codesign-mcp-next 0.3.2 → 0.3.4

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.
@@ -22,6 +22,7 @@ export const ERROR_CODES = [
22
22
  'ARTIFACT_SIZE_MISMATCH',
23
23
  'ARTIFACT_MAGIC_MISMATCH',
24
24
  'ARTIFACT_PATH_INVALID',
25
+ 'CODE_FILE_INVALID',
25
26
  ];
26
27
  export class CodesignError extends Error {
27
28
  code;
@@ -0,0 +1,495 @@
1
+ // 还原度静态校验的纯函数部分:锚点解析、代码声明提取、六维度比对、盲区枚举。
2
+ // 不依赖浏览器/网络,便于单测。期望值一律由调用方传入(MCP 工具层重新拉 spec 重建)。
3
+ export const VERIFY_CHECKS = ['size', 'scale', 'color', 'typography', 'radius', 'hierarchy'];
4
+ const WINDOW_LINES = 16;
5
+ const ATTR_RE = /data-slice-id\s*=\s*["'`]([^"'`]+)["'`]/gi;
6
+ const COMMENT_RE = /\/\*\s*slice\s*[::]\s*([^*]+?)\s*\*\//gi;
7
+ const NUM = '(-?\\d+(?:\\.\\d+)?)';
8
+ const UNIT = '(px|rem|rpx|dp|pt|%)?';
9
+ function cssProp(prop) {
10
+ return new RegExp(`(?:^|[;{\\s])${prop}\\s*:\\s*${NUM}\\s*${UNIT}`, 'gi');
11
+ }
12
+ function htmlAttr(prop) {
13
+ return new RegExp(`${prop}\\s*=\\s*["']${NUM}${UNIT}["']`, 'gi');
14
+ }
15
+ const BG_SIZE_RE = new RegExp(`background-size\\s*:\\s*${NUM}\\s*${UNIT}[\\s,]+${NUM}\\s*${UNIT}`, 'gi');
16
+ const URL_RE = /(?:url\(\s*["']?|src\s*=\s*["'])([^"')>\s]+)/gi;
17
+ const COLOR_RE = /#[0-9a-fA-F]{3,8}\b|rgba?\([^)]+\)/g;
18
+ function extractAnchors(files) {
19
+ const anchors = [];
20
+ for (const file of files) {
21
+ const lines = file.text.split(/\r?\n/);
22
+ for (let i = 0; i < lines.length; i += 1) {
23
+ const line = lines[i];
24
+ for (const [pattern, kind] of [
25
+ [ATTR_RE, 'attribute'],
26
+ [COMMENT_RE, 'comment'],
27
+ ]) {
28
+ pattern.lastIndex = 0;
29
+ let match;
30
+ while ((match = pattern.exec(line)) !== null) {
31
+ const objectId = match[1].trim();
32
+ if (!objectId)
33
+ continue;
34
+ const end = Math.min(lines.length, i + WINDOW_LINES);
35
+ anchors.push({
36
+ objectId,
37
+ kind,
38
+ file: file.path,
39
+ line: i + 1,
40
+ block: lines.slice(i, end).join('\n'),
41
+ });
42
+ }
43
+ }
44
+ }
45
+ }
46
+ return anchors;
47
+ }
48
+ function firstValue(block, prop) {
49
+ const css = cssProp(prop);
50
+ const match = css.exec(block);
51
+ if (match)
52
+ return { value: Number(match[1]), unit: (match[2] ?? '').toLowerCase() };
53
+ const attr = htmlAttr(prop);
54
+ const attrMatch = attr.exec(block);
55
+ if (attrMatch)
56
+ return { value: Number(attrMatch[1]), unit: (attrMatch[2] ?? '').toLowerCase() };
57
+ return undefined;
58
+ }
59
+ function extractDeclarations(block) {
60
+ const declarations = {
61
+ width: firstValue(block, 'width'),
62
+ height: firstValue(block, 'height'),
63
+ fontSize: firstValue(block, 'font-size'),
64
+ lineHeight: firstValue(block, 'line-height'),
65
+ radius: firstValue(block, 'border-radius'),
66
+ colors: [],
67
+ assetRefs: [],
68
+ };
69
+ BG_SIZE_RE.lastIndex = 0;
70
+ const bg = BG_SIZE_RE.exec(block);
71
+ if (bg) {
72
+ declarations.backgroundSize = [
73
+ { value: Number(bg[1]), unit: (bg[2] ?? '').toLowerCase() },
74
+ { value: Number(bg[3]), unit: (bg[4] ?? '').toLowerCase() },
75
+ ];
76
+ }
77
+ let match;
78
+ COLOR_RE.lastIndex = 0;
79
+ while ((match = COLOR_RE.exec(block)) !== null)
80
+ declarations.colors.push(normalizeColor(match[0]));
81
+ URL_RE.lastIndex = 0;
82
+ while ((match = URL_RE.exec(block)) !== null)
83
+ declarations.assetRefs.push(match[1]);
84
+ return declarations;
85
+ }
86
+ function normalizeColor(raw) {
87
+ const value = raw.trim().toLowerCase();
88
+ if (value.startsWith('#')) {
89
+ const hex = value.slice(1);
90
+ if (hex.length === 3)
91
+ return `#${hex.split('').map((c) => c + c).join('')}`;
92
+ return `#${hex}`;
93
+ }
94
+ const numbers = value.match(/\d+(?:\.\d+)?/g) ?? [];
95
+ return `rgba(${numbers.slice(0, 4).join(',')})`;
96
+ }
97
+ // 统一以 px 为基准:rem 用 remBasePx 换算,px 原值,
98
+ // rpx/dp/pt 只在与目标平台同单位时按数值直接比较(跨单位无法静态换算)。
99
+ function toPixels(value, platform) {
100
+ const unit = value.unit || platform.unit;
101
+ if (unit === 'rem')
102
+ return value.value * remBase(platform);
103
+ if (unit === 'px')
104
+ return value.value;
105
+ if (unit === platform.unit)
106
+ return value.value;
107
+ return undefined;
108
+ }
109
+ function remBase(platform) {
110
+ const base = platform.conversion.remBasePx;
111
+ return typeof base === 'number' && base > 0 ? base : 16;
112
+ }
113
+ function expectedPixels(value, platform) {
114
+ return platform.unit === 'rem' ? value * remBase(platform) : value;
115
+ }
116
+ function compareSize(expected, platform, actual) {
117
+ if (!actual || actual.unit === '%')
118
+ return { status: 'unverifiable' };
119
+ const actualPx = toPixels(actual, platform);
120
+ const expectedPx = expectedPixels(expected, platform);
121
+ if (actualPx == null || !Number.isFinite(expectedPx) || expectedPx <= 0)
122
+ return { status: 'unverifiable' };
123
+ const ratio = actualPx / expectedPx;
124
+ if (Math.abs(ratio - 1) <= 0.02 || Math.abs(actualPx - expectedPx) <= 1) {
125
+ return { status: 'pass', actualPx };
126
+ }
127
+ if (Math.abs(ratio - 2) <= 0.02)
128
+ return { status: 'double', actualPx };
129
+ return { status: 'mismatch', actualPx };
130
+ }
131
+ function detectScaleRefs(refs) {
132
+ const scales = new Set();
133
+ for (const ref of refs) {
134
+ const match = ref.match(/@(\d)x|[-_](\d)x\.|scale[=_-]?(\d)/i);
135
+ if (!match)
136
+ continue;
137
+ const value = Number(match[1] ?? match[2] ?? match[3]);
138
+ if ([1, 2, 3, 4].includes(value))
139
+ scales.add(value);
140
+ }
141
+ return [...scales];
142
+ }
143
+ function expectedColors(layer) {
144
+ const found = [];
145
+ const visit = (value, depth) => {
146
+ if (depth > 4 || found.length > 8)
147
+ return;
148
+ if (typeof value === 'string') {
149
+ let match;
150
+ COLOR_RE.lastIndex = 0;
151
+ while ((match = COLOR_RE.exec(value)) !== null)
152
+ found.push(normalizeColor(match[0]));
153
+ return;
154
+ }
155
+ if (Array.isArray(value)) {
156
+ for (const item of value)
157
+ visit(item, depth + 1);
158
+ return;
159
+ }
160
+ if (value && typeof value === 'object') {
161
+ for (const [key, item] of Object.entries(value)) {
162
+ if (/color|fill|stroke|background/i.test(key))
163
+ visit(item, depth + 1);
164
+ }
165
+ }
166
+ };
167
+ if (layer.fills)
168
+ visit(layer.fills, 0);
169
+ if (layer.color)
170
+ visit(layer.color, 0);
171
+ return [...new Set(found)];
172
+ }
173
+ function reviewReasons(layer) {
174
+ const reasons = [];
175
+ const extra = layer;
176
+ if (Array.isArray(extra.masks) && extra.masks.length > 0)
177
+ reasons.push('mask');
178
+ if (Array.isArray(layer.effects) && layer.effects.length > 0)
179
+ reasons.push('effect');
180
+ if (Array.isArray(layer.shadows) && layer.shadows.length > 0)
181
+ reasons.push('shadow');
182
+ const css = Array.isArray(layer.css) ? layer.css.join(' ') : (layer.css ?? '');
183
+ if (/gradient|mask|filter|backdrop-filter|blur|mix-blend/i.test(css))
184
+ reasons.push('css-complex');
185
+ if (layer.type === 'text' && !layer.content)
186
+ reasons.push('text-content-missing');
187
+ return reasons;
188
+ }
189
+ function collectOrder(nodes, output = []) {
190
+ for (const node of nodes) {
191
+ if (!node || typeof node !== 'object')
192
+ continue;
193
+ const record = node;
194
+ const id = record.object_id ?? record.objectId ?? record.id;
195
+ if (typeof id === 'string' && id && !output.includes(id))
196
+ output.push(id);
197
+ for (const key of ['children', 'layers', 'groups']) {
198
+ const child = record[key];
199
+ if (Array.isArray(child))
200
+ collectOrder(child, output);
201
+ }
202
+ }
203
+ return output;
204
+ }
205
+ function scaleFromManifest(manifest, objectId) {
206
+ const item = manifest.find((entry) => entry.object_id === objectId);
207
+ if (!item)
208
+ return [];
209
+ return [...new Set(item.exportables.map((e) => e.scale).filter((s) => typeof s === 'number'))];
210
+ }
211
+ export function verifyRendering(input) {
212
+ const checks = new Set(input.checks ?? VERIFY_CHECKS);
213
+ const expectedScale = input.scale ?? 2;
214
+ const anchors = extractAnchors(input.files);
215
+ const allLayers = [...input.layers, ...input.groups];
216
+ const layerByObjectId = new Map(allLayers.map((layer) => [layer.object_id, layer]));
217
+ const platformByObjectId = new Map([...input.platformSpec.layers, ...input.platformSpec.groups].map((layer) => [layer.objectId, layer]));
218
+ const issues = [];
219
+ const seen = new Set();
220
+ let pass = 0;
221
+ const addIssue = (issue) => {
222
+ issues.push(issue);
223
+ };
224
+ for (const anchor of anchors) {
225
+ const layer = layerByObjectId.get(anchor.objectId);
226
+ if (!layer) {
227
+ addIssue({
228
+ code: 'ANCHOR_UNRESOLVED',
229
+ dimension: 'parse',
230
+ severity: 'warning',
231
+ layerObjectId: anchor.objectId,
232
+ file: anchor.file,
233
+ line: anchor.line,
234
+ message: `anchor ${anchor.objectId} does not match any spec layer`,
235
+ });
236
+ continue;
237
+ }
238
+ seen.add(anchor.objectId);
239
+ const declarations = extractDeclarations(anchor.block);
240
+ const platformLayer = platformByObjectId.get(anchor.objectId);
241
+ if (checks.has('size') && platformLayer) {
242
+ for (const [axis, actual] of [
243
+ ['width', declarations.width],
244
+ ['height', declarations.height],
245
+ ]) {
246
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
247
+ const expectedText = `${platformLayer.rect[axis]}${platformLayer.rect.unit}`;
248
+ const actualText = actual ? `${actual.value}${actual.unit || input.platformSpec.unit}` : null;
249
+ if (result.status === 'pass') {
250
+ pass += 1;
251
+ }
252
+ else if (result.status === 'double') {
253
+ addIssue({
254
+ code: 'DOUBLE_SCALE',
255
+ dimension: 'size',
256
+ severity: 'error',
257
+ layerObjectId: anchor.objectId,
258
+ file: anchor.file,
259
+ line: anchor.line,
260
+ expected: expectedText,
261
+ actual: actualText,
262
+ message: `${axis} is about 2x the design size (2x asset must be displayed at design size)`,
263
+ });
264
+ }
265
+ else if (result.status === 'mismatch') {
266
+ addIssue({
267
+ code: 'SIZE_MISMATCH',
268
+ dimension: 'size',
269
+ severity: 'error',
270
+ layerObjectId: anchor.objectId,
271
+ file: anchor.file,
272
+ line: anchor.line,
273
+ expected: expectedText,
274
+ actual: actualText,
275
+ message: `${axis} does not match the design size`,
276
+ });
277
+ }
278
+ else {
279
+ addIssue({
280
+ code: 'UNVERIFIABLE',
281
+ dimension: 'size',
282
+ severity: 'warning',
283
+ layerObjectId: anchor.objectId,
284
+ file: anchor.file,
285
+ line: anchor.line,
286
+ expected: expectedText,
287
+ actual: actualText,
288
+ message: `${axis} cannot be statically resolved (external class, percentage, or dynamic style)`,
289
+ });
290
+ }
291
+ }
292
+ if (declarations.backgroundSize) {
293
+ const [bgWidth, bgHeight] = declarations.backgroundSize;
294
+ for (const [axis, actual] of [
295
+ ['width', bgWidth],
296
+ ['height', bgHeight],
297
+ ]) {
298
+ const result = compareSize(platformLayer.rect[axis], input.platformSpec, actual);
299
+ if (result.status === 'pass')
300
+ pass += 1;
301
+ else if (result.status !== 'unverifiable') {
302
+ addIssue({
303
+ code: result.status === 'double' ? 'DOUBLE_SCALE' : 'SIZE_MISMATCH',
304
+ dimension: 'size',
305
+ severity: 'error',
306
+ layerObjectId: anchor.objectId,
307
+ file: anchor.file,
308
+ line: anchor.line,
309
+ expected: `${platformLayer.rect[axis]}${platformLayer.rect.unit}`,
310
+ actual: `${actual.value}${actual.unit || input.platformSpec.unit}`,
311
+ message: `background-size ${axis} does not match the design size`,
312
+ });
313
+ }
314
+ }
315
+ }
316
+ }
317
+ if (checks.has('scale')) {
318
+ const assetScales = detectScaleRefs(declarations.assetRefs);
319
+ const wrong = assetScales.filter((scale) => scale !== expectedScale);
320
+ if (wrong.length > 0) {
321
+ addIssue({
322
+ code: 'WRONG_SCALE_ASSET',
323
+ dimension: 'scale',
324
+ severity: 'error',
325
+ layerObjectId: anchor.objectId,
326
+ file: anchor.file,
327
+ line: anchor.line,
328
+ expected: `${expectedScale}x`,
329
+ actual: wrong.map((s) => `${s}x`).join(','),
330
+ message: `code references a non-${expectedScale}x slice asset`,
331
+ });
332
+ }
333
+ else if (assetScales.includes(expectedScale)) {
334
+ pass += 1;
335
+ }
336
+ const available = scaleFromManifest(input.manifest, anchor.objectId);
337
+ if (available.length > 0 && !available.includes(expectedScale)) {
338
+ addIssue({
339
+ code: 'SCALE_UNAVAILABLE',
340
+ dimension: 'scale',
341
+ severity: 'error',
342
+ layerObjectId: anchor.objectId,
343
+ file: anchor.file,
344
+ line: anchor.line,
345
+ expected: `${expectedScale}x`,
346
+ actual: available.map((s) => `${s}x`).join(','),
347
+ message: `design manifest has no ${expectedScale}x export for this layer`,
348
+ });
349
+ }
350
+ }
351
+ if (checks.has('typography')) {
352
+ if (layer.fontSize != null && declarations.fontSize) {
353
+ const expectedFont = expectedPixels(layer.fontSize * input.platformSpec.scale, input.platformSpec);
354
+ const result = compareSize(expectedFont, input.platformSpec, declarations.fontSize);
355
+ if (result.status === 'pass')
356
+ pass += 1;
357
+ else if (result.status !== 'unverifiable') {
358
+ addIssue({
359
+ code: 'FONT_SIZE_MISMATCH',
360
+ dimension: 'typography',
361
+ severity: 'warning',
362
+ layerObjectId: anchor.objectId,
363
+ file: anchor.file,
364
+ line: anchor.line,
365
+ expected: `${expectedFont}${input.platformSpec.unit}`,
366
+ actual: `${declarations.fontSize.value}${declarations.fontSize.unit || input.platformSpec.unit}`,
367
+ message: 'font-size does not match the design annotation',
368
+ });
369
+ }
370
+ }
371
+ if (layer.lineHeight != null && declarations.lineHeight) {
372
+ const expectedLine = expectedPixels(layer.lineHeight * input.platformSpec.scale, input.platformSpec);
373
+ const result = compareSize(expectedLine, input.platformSpec, declarations.lineHeight);
374
+ if (result.status === 'pass')
375
+ pass += 1;
376
+ else if (result.status !== 'unverifiable') {
377
+ addIssue({
378
+ code: 'LINE_HEIGHT_MISMATCH',
379
+ dimension: 'typography',
380
+ severity: 'warning',
381
+ layerObjectId: anchor.objectId,
382
+ file: anchor.file,
383
+ line: anchor.line,
384
+ expected: `${expectedLine}${input.platformSpec.unit}`,
385
+ actual: `${declarations.lineHeight.value}${declarations.lineHeight.unit || input.platformSpec.unit}`,
386
+ message: 'line-height does not match the design annotation',
387
+ });
388
+ }
389
+ }
390
+ }
391
+ if (checks.has('radius')) {
392
+ const radius = Array.isArray(layer.radius) ? layer.radius[0] : layer.radius;
393
+ if (typeof radius === 'number' && declarations.radius) {
394
+ const expectedRadius = expectedPixels(radius * input.platformSpec.scale, input.platformSpec);
395
+ const result = compareSize(expectedRadius, input.platformSpec, declarations.radius);
396
+ if (result.status === 'pass')
397
+ pass += 1;
398
+ else if (result.status !== 'unverifiable') {
399
+ addIssue({
400
+ code: 'RADIUS_MISMATCH',
401
+ dimension: 'radius',
402
+ severity: 'warning',
403
+ layerObjectId: anchor.objectId,
404
+ file: anchor.file,
405
+ line: anchor.line,
406
+ expected: `${expectedRadius}${input.platformSpec.unit}`,
407
+ actual: `${declarations.radius.value}${declarations.radius.unit || input.platformSpec.unit}`,
408
+ message: 'border-radius does not match the design annotation',
409
+ });
410
+ }
411
+ }
412
+ }
413
+ if (checks.has('color') && declarations.colors.length > 0) {
414
+ const expected = expectedColors(layer);
415
+ if (expected.length > 0 && !expected.some((color) => declarations.colors.includes(color))) {
416
+ addIssue({
417
+ code: 'COLOR_MISMATCH',
418
+ dimension: 'color',
419
+ severity: 'warning',
420
+ layerObjectId: anchor.objectId,
421
+ file: anchor.file,
422
+ line: anchor.line,
423
+ expected: expected.slice(0, 3).join(','),
424
+ actual: declarations.colors.slice(0, 3).join(','),
425
+ message: 'no code color matches the design fills (CSS variables may need mapping)',
426
+ });
427
+ }
428
+ else if (expected.length > 0) {
429
+ pass += 1;
430
+ }
431
+ }
432
+ }
433
+ if (checks.has('hierarchy')) {
434
+ const expectedOrder = collectOrder(input.hierarchy).filter((id) => seen.has(id));
435
+ const actualOrder = anchors.map((anchor) => anchor.objectId).filter((id, index, list) => seen.has(id) && list.indexOf(id) === index);
436
+ for (let i = 0; i < Math.min(expectedOrder.length, actualOrder.length); i += 1) {
437
+ if (expectedOrder[i] === actualOrder[i])
438
+ pass += 1;
439
+ else {
440
+ const first = anchors.find((anchor) => anchor.objectId === actualOrder[i]);
441
+ addIssue({
442
+ code: 'HIERARCHY_ORDER',
443
+ dimension: 'hierarchy',
444
+ severity: 'warning',
445
+ layerObjectId: actualOrder[i],
446
+ file: first?.file ?? '',
447
+ line: first?.line ?? 0,
448
+ expected: expectedOrder[i],
449
+ actual: actualOrder[i],
450
+ message: 'anchor order differs from the design hierarchy',
451
+ });
452
+ break;
453
+ }
454
+ }
455
+ }
456
+ const unusedSlices = input.manifest
457
+ .filter((item) => item.exportables.some((e) => e.scale === expectedScale))
458
+ .map((item) => item.object_id)
459
+ .filter((id) => !seen.has(id));
460
+ for (const objectId of unusedSlices) {
461
+ addIssue({
462
+ code: 'SLICE_UNUSED',
463
+ dimension: 'asset',
464
+ severity: 'error',
465
+ layerObjectId: objectId,
466
+ file: '',
467
+ line: 0,
468
+ message: `design has a ${expectedScale}x slice but no code anchor uses it`,
469
+ });
470
+ }
471
+ const reviewRequired = [];
472
+ for (const layer of allLayers) {
473
+ const reasons = reviewReasons(layer);
474
+ if (reasons.length === 0)
475
+ continue;
476
+ const anchor = anchors.find((item) => item.objectId === layer.object_id);
477
+ reviewRequired.push({
478
+ layerObjectId: layer.object_id,
479
+ name: layer.name,
480
+ reasons,
481
+ file: anchor?.file,
482
+ line: anchor?.line,
483
+ });
484
+ }
485
+ const fail = issues.filter((issue) => issue.severity === 'error').length;
486
+ const warn = issues.filter((issue) => issue.severity === 'warning').length;
487
+ return {
488
+ ok: fail === 0,
489
+ summary: { pass, fail, warn },
490
+ issues,
491
+ reviewRequired,
492
+ anchors: anchors.length,
493
+ checkedSlices: input.manifest.filter((item) => item.exportables.some((e) => e.scale === expectedScale)).length,
494
+ };
495
+ }
@@ -122,6 +122,25 @@ function summarizeIntegrity(value) {
122
122
  }
123
123
  return `integrity: ${integrity.ok === false ? 'failed' : 'ok'}`;
124
124
  }
125
+ export function summarizeVerifyPayload(payload) {
126
+ const lines = [payload.ok === false ? 'failed' : 'ok'];
127
+ const summary = payload.summary;
128
+ if (summary)
129
+ lines.push(`checks: pass=${summary.pass ?? 0} fail=${summary.fail ?? 0} warn=${summary.warn ?? 0}`);
130
+ const issues = Array.isArray(payload.issues) ? payload.issues : [];
131
+ const failed = issues.filter((issue) => /MISMATCH|DOUBLE_SCALE|WRONG_SCALE|UNUSED|UNAVAILABLE|UNRESOLVED|ORDER/.test(issue.code ?? ''));
132
+ if (failed.length > 0) {
133
+ lines.push('failed checks (first 5):');
134
+ for (const issue of failed.slice(0, 5)) {
135
+ lines.push(` [${issue.code}] ${issue.dimension ?? '?'} ${issue.layerObjectId ?? ''} @ ${issue.file ?? ''}:${issue.line ?? 0}`);
136
+ }
137
+ }
138
+ const review = Array.isArray(payload.reviewRequired) ? payload.reviewRequired.length : 0;
139
+ if (review > 0)
140
+ lines.push(`reviewRequired: ${review} layers need manual review`);
141
+ lines.push('Full data is available in structuredContent.');
142
+ return lines.join('\n');
143
+ }
125
144
  // 诊断记录本身就是给 LLM 阅读的内容,默认保留完整文本但不加缩进。
126
145
  export function toolSuccessFull(payload) {
127
146
  const structuredContent = { ok: true, ...payload };
@@ -62,7 +62,7 @@ const argsSchema = objectSchema({
62
62
  export function registerDesignToCodePrompt(server) {
63
63
  server.registerPrompt('implement_codesign_page', {
64
64
  title: 'Implement CoDesign Page',
65
- description: 'Generate a design-to-code workflow prompt that uses list_artboards, get_artboard_spec, and download_slice in order.',
65
+ description: 'Generate a design-to-code workflow prompt that uses list_artboards, get_artboard_spec, download_slice, and verify_rendering in order.',
66
66
  argsSchema,
67
67
  }, async ({ sharingUrl, password, artboardName, screenId, layerObjectId, layerName, selectionScope, targetPlatform, targetUnit, customScale, customWidth, remBasePx, outputDir, }) => ({
68
68
  messages: [
@@ -108,21 +108,23 @@ function buildPrompt(args) {
108
108
  const customWidthLine = args.customWidth != null ? `Custom width: ${args.customWidth}\n` : '';
109
109
  const remBaseLine = args.remBasePx != null ? `Rem base px: ${args.remBasePx}\n` : '';
110
110
  const outputDirLine = args.outputDir ? `Target directory: ${args.outputDir}\n` : '';
111
- return `Implement the page from this Tencent CoDesign design.
112
-
113
- CoDesign link: ${args.sharingUrl}
114
- ${passwordLine}${artboardLine}${screenIdLine}${layerNameLine}${layerIdLine}${selectionScopeLine}${platformLine}${unitLine}${customScaleLine}${customWidthLine}${remBaseLine}${outputDirLine}
115
- Requirements:
116
- 1. Call the codesign-mcp list_artboards tool first to resolve the sharing link and inspect the available designs and artboards.
117
- 2. Select the requested artboard when a preferred artboard or screen ID is provided. Otherwise, choose the artboard that best matches the user's page request and state the selected artboard name.
118
- 3. Call get_artboard_spec for the selected artboard and use the official layer, text, color, CSS, coordinate, group, and slice metadata as the source of truth. When a layer object ID is provided, pass it as layerObjectId together with the requested selectionScope and implement only the returned selection.
119
- 4. For a selected region, use selection.layers, selection.groups, selection.hierarchy, selection.bounds, and each node's relativeRect to reconstruct its structure. selectionScope=region includes non-ancestor nodes fully contained by the selected bounds; selectionScope=subtree includes only strict descendants.
120
- 5. If a target platform is provided or implied by the user's request, pass it as get_artboard_spec.targetPlatform using the user's natural-language wording.
121
- 6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as get_artboard_spec.targetUnit, customScale, customWidth, and remBasePx. For example, "1440px design width, rem, 1rem=100px" maps to targetUnit=rem, customWidth=1440, remBasePx=100.
122
- 7. Use spec.platformSpec or platformSelection when returned for platform id, units, converted rects, unit-adjusted CSS, and conversion metadata. Keep the raw CoDesign data available as the source of truth.
123
- 8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before coding. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
124
- 9. When the design includes designer-exported slice assets, call download_slice for those assets. Do not crop production assets from the full preview image.
125
- 10. Use get_artboard_image only for visual comparison and final review.
126
- 11. Implement the page in the target directory when one is provided, following the existing project structure and styles.
127
- 12. Surface any CoDesign access, password, login, or missing-spec failure clearly instead of fabricating design data.`;
111
+ return `Implement the page from this Tencent CoDesign design.
112
+
113
+ CoDesign link: ${args.sharingUrl}
114
+ ${passwordLine}${artboardLine}${screenIdLine}${layerNameLine}${layerIdLine}${selectionScopeLine}${platformLine}${unitLine}${customScaleLine}${customWidthLine}${remBaseLine}${outputDirLine}
115
+ Requirements:
116
+ 1. Call the codesign-mcp list_artboards tool first to resolve the sharing link and inspect the available designs and artboards.
117
+ 2. Select the requested artboard when a preferred artboard or screen ID is provided. Otherwise, choose the artboard that best matches the user's page request and state the selected artboard name.
118
+ 3. Call get_artboard_spec for the selected artboard and use the official layer, text, color, CSS, coordinate, group, and slice metadata as the source of truth. When a layer object ID is provided, pass it as layerObjectId together with the requested selectionScope and implement only the returned selection.
119
+ 4. For a selected region, use selection.layers, selection.groups, selection.hierarchy, selection.bounds, and each node's relativeRect to reconstruct its structure. selectionScope=region includes non-ancestor nodes fully contained by the selected bounds; selectionScope=subtree includes only strict descendants.
120
+ 5. If a target platform is provided or implied by the user's request, pass it as get_artboard_spec.targetPlatform using the user's natural-language wording.
121
+ 6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as get_artboard_spec.targetUnit, customScale, customWidth, and remBasePx. For example, "1440px design width, rem, 1rem=100px" maps to targetUnit=rem, customWidth=1440, remBasePx=100.
122
+ 7. Use spec.platformSpec or platformSelection when returned for platform id, units, converted rects, unit-adjusted CSS, and conversion metadata. Keep the raw CoDesign data available as the source of truth.
123
+ 8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before coding. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
124
+ 9. When the design includes designer-exported slice assets, call download_slice for those assets with the same targetPlatform/unit/width options. Use the returned slice.designSize as the CSS display size — a 2x asset is shown at design size, never at its pixel size. Do not crop production assets from the full preview image.
125
+ 10. Mark every slice usage in code with data-slice-id="<layerObjectId>" (attribute) or /* slice:<layerObjectId> */ (comment) so it can be verified.
126
+ 11. Implement the page in the target directory when one is provided, following the existing project structure and styles.
127
+ 12. Before finishing, call verify_rendering with the written code files and the same platform options. Fix every error issue (size, scale, color, typography, radius, hierarchy), re-run until ok is true, and manually review every item in reviewRequired. It re-fetches the official spec itself, so pass the real file paths, not copied measurements.
128
+ 13. Use get_artboard_image only for visual comparison and final review.
129
+ 14. Surface any CoDesign access, password, login, or missing-spec failure clearly instead of fabricating design data.`;
128
130
  }
@@ -1,20 +1,21 @@
1
1
  export const DESIGN_TO_CODE_WORKFLOW_URI = 'codesign://workflow/design-to-code';
2
- const workflowMarkdown = `# CoDesign Design-to-Code Workflow
3
-
4
- Use this workflow when a user asks an agent to implement, recreate, or inspect a Tencent CoDesign sharing link.
5
-
6
- 1. Call \`list_artboards\` with the CoDesign sharing URL and optional password. Use the returned design and artboard metadata to select the target screen.
7
- 2. Call \`get_artboard_spec\` for the selected artboard. Treat the official spec data as the source of truth for layout, text, color, CSS, coordinates, grouping, and slice metadata.
8
- 3. When the user supplies a copied CoDesign selection reference, pass its \`screenId\`, \`layerObjectId\`, and \`selectionScope\` to \`get_artboard_spec\`. Use \`selectionScope=region\` for a visual area or \`selectionScope=subtree\` for the selected node's strict descendants.
9
- 4. Reconstruct a selected area from \`selection.layers\`, \`selection.groups\`, \`selection.hierarchy\`, \`selection.bounds\`, and each node's \`relativeRect\`. Implement only that selection unless the user asks for the full page.
10
- 5. If the user specifies a development platform in natural language, such as Web, Android, 安卓, iOS, 微信小程序, or mini program, pass that wording as \`get_artboard_spec.targetPlatform\`.
11
- 6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as \`targetUnit\`, \`customScale\`, \`customWidth\`, and \`remBasePx\`. For example, "1440px design width, rem, 1rem=100px" maps to \`targetUnit=rem\`, \`customWidth=1440\`, and \`remBasePx=100\`.
12
- 7. Use the returned \`spec.platformSpec\` or \`platformSelection\` for normalized platform id, units, converted rects, unit-adjusted CSS, and conversion metadata while keeping the raw spec as the original CoDesign data.
13
- 8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before implementation. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
14
- 9. If the selected artboard includes designer-exported slice assets, call \`download_slice\` for those assets. Do not crop production assets from a preview image.
15
- 10. Use \`get_artboard_image\` only for visual comparison, review, or debugging.
16
- 11. Use \`codesign_status\` before private designs when login state or runtime paths need to be checked. Use \`codesign_login\` only when the user needs to establish a CoDesign browser session.
17
- 12. Surface access, password, login, network, missing-artboard, and missing-spec failures clearly. Do not fabricate design data when the official CoDesign data is unavailable.
2
+ const workflowMarkdown = `# CoDesign Design-to-Code Workflow
3
+
4
+ Use this workflow when a user asks an agent to implement, recreate, or inspect a Tencent CoDesign sharing link.
5
+
6
+ 1. Call \`list_artboards\` with the CoDesign sharing URL and optional password. Use the returned design and artboard metadata to select the target screen.
7
+ 2. Call \`get_artboard_spec\` for the selected artboard. Treat the official spec data as the source of truth for layout, text, color, CSS, coordinates, grouping, and slice metadata.
8
+ 3. When the user supplies a copied CoDesign selection reference, pass its \`screenId\`, \`layerObjectId\`, and \`selectionScope\` to \`get_artboard_spec\`. Use \`selectionScope=region\` for a visual area or \`selectionScope=subtree\` for the selected node's strict descendants.
9
+ 4. Reconstruct a selected area from \`selection.layers\`, \`selection.groups\`, \`selection.hierarchy\`, \`selection.bounds\`, and each node's \`relativeRect\`. Implement only that selection unless the user asks for the full page.
10
+ 5. If the user specifies a development platform in natural language, such as Web, Android, 安卓, iOS, 微信小程序, or mini program, pass that wording as \`get_artboard_spec.targetPlatform\`.
11
+ 6. If the user specifies a unit, custom scale, target design width, or rem base, pass those as \`targetUnit\`, \`customScale\`, \`customWidth\`, and \`remBasePx\`. For example, "1440px design width, rem, 1rem=100px" maps to \`targetUnit=rem\`, \`customWidth=1440\`, and \`remBasePx=100\`.
12
+ 7. Use the returned \`spec.platformSpec\` or \`platformSelection\` for normalized platform id, units, converted rects, unit-adjusted CSS, and conversion metadata while keeping the raw spec as the original CoDesign data.
13
+ 8. Unless the user's current request explicitly requires an absolute-positioned or canvas-style implementation, translate the CoDesign coordinates into semantic page structure and normal document flow before implementation. Prefer Flexbox/Grid and existing layout primitives for page layout; do not recreate the whole page as a flat canvas of globally absolute-positioned layers. When the user explicitly requests absolute positioning, honor that instruction and scope positioning to the requested page or selection container where practical. Otherwise reserve absolute/fixed positioning for local overlays or intentionally overlapping elements required by the design.
14
+ 9. If the selected artboard includes designer-exported slice assets, call \`download_slice\` for those assets with the same platform options and use the returned \`slice.designSize\` as the CSS display size (a 2x asset is shown at design size, not pixel size). Do not crop production assets from a preview image.
15
+ 10. Mark each slice usage with \`data-slice-id="<layerObjectId>"\` or a \`/* slice:<layerObjectId> */\` comment. Before finishing, call \`verify_rendering\` with the written code files and the same platform options; fix its error issues, re-run until \`ok\` is true, and manually review every \`reviewRequired\` item. It re-fetches the official spec itself and never trusts measurements copied into the prompt.
16
+ 11. Use \`get_artboard_image\` only for visual comparison, review, or debugging.
17
+ 12. Use \`codesign_status\` before private designs when login state or runtime paths need to be checked. Use \`codesign_login\` only when the user needs to establish a CoDesign browser session.
18
+ 13. Surface access, password, login, network, missing-artboard, and missing-spec failures clearly. Do not fabricate design data when the official CoDesign data is unavailable.
18
19
  `;
19
20
  export function registerWorkflowResource(server) {
20
21
  server.registerResource('design-to-code-workflow', DESIGN_TO_CODE_WORKFLOW_URI, {
package/dist/server.js CHANGED
@@ -5,6 +5,7 @@ import { registerArtboardsTool } from './tools/artboards.js';
5
5
  import { registerSpecTool } from './tools/spec.js';
6
6
  import { registerImageTool } from './tools/image.js';
7
7
  import { registerSlicesTool } from './tools/slices.js';
8
+ import { registerVerifyRenderingTool } from './tools/verify-rendering.js';
8
9
  import { registerDiagnosticsTool } from './tools/diagnostics.js';
9
10
  import { registerDesignToCodePrompt } from './prompts/design-to-code.js';
10
11
  import { registerWorkflowResource } from './resources/workflow.js';
@@ -30,6 +31,7 @@ export function buildServer() {
30
31
  registerSpecTool(server);
31
32
  registerImageTool(server);
32
33
  registerSlicesTool(server);
34
+ registerVerifyRenderingTool(server);
33
35
  registerDiagnosticsTool(server);
34
36
  registerDesignToCodePrompt(server);
35
37
  registerWorkflowResource(server);