codesign-mcp-next 0.0.0-stage → 0.3.3

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +137 -0
  2. package/LICENSE +21 -0
  3. package/README.md +457 -2
  4. package/dist/browser/manager.js +204 -0
  5. package/dist/browser/session.js +62 -0
  6. package/dist/codesign/cache.js +85 -0
  7. package/dist/codesign/errors.js +47 -0
  8. package/dist/codesign/integrity.js +197 -0
  9. package/dist/codesign/meta.js +57 -0
  10. package/dist/codesign/parser.js +56 -0
  11. package/dist/codesign/platform.js +232 -0
  12. package/dist/codesign/selection.js +205 -0
  13. package/dist/codesign/sharing.js +153 -0
  14. package/dist/codesign/slices.js +34 -0
  15. package/dist/codesign/types.js +1 -0
  16. package/dist/config.js +94 -0
  17. package/dist/index.js +16 -0
  18. package/dist/logger.js +68 -0
  19. package/dist/mcp/result.js +151 -0
  20. package/dist/mcp/schema.js +122 -0
  21. package/dist/mcp/server.js +313 -0
  22. package/dist/prompts/design-to-code.js +128 -0
  23. package/dist/resources/workflow.js +33 -0
  24. package/dist/server.js +61 -0
  25. package/dist/tools/artboards.js +96 -0
  26. package/dist/tools/diagnostics.js +192 -0
  27. package/dist/tools/image.js +134 -0
  28. package/dist/tools/login.js +136 -0
  29. package/dist/tools/slices.js +228 -0
  30. package/dist/tools/spec.js +236 -0
  31. package/dist/tools/status.js +62 -0
  32. package/dist/utils/download.js +290 -0
  33. package/dist/utils/filename.js +16 -0
  34. package/dist/utils/http.js +54 -0
  35. package/dist/utils/rate-limit.js +120 -0
  36. package/dist/utils/redact.js +110 -0
  37. package/dist/utils/retry.js +97 -0
  38. package/dist/utils/url.js +98 -0
  39. package/package.json +56 -4
  40. package/userscripts/codesign-ai-selection.user.js +445 -0
@@ -0,0 +1,313 @@
1
+ import process from 'node:process';
2
+ import { getLogger } from '../logger.js';
3
+ import { validateArgs } from './schema.js';
4
+ const LATEST_PROTOCOL_VERSION = '2025-11-25';
5
+ const SUPPORTED_PROTOCOL_VERSIONS = new Set([
6
+ LATEST_PROTOCOL_VERSION,
7
+ '2025-06-18',
8
+ '2025-03-26',
9
+ '2024-11-05',
10
+ '2024-10-07',
11
+ ]);
12
+ export class StdioServerTransport {
13
+ stdin;
14
+ stdout;
15
+ onmessage;
16
+ onerror;
17
+ onclose;
18
+ buffer = '';
19
+ started = false;
20
+ constructor(stdin = process.stdin, stdout = process.stdout) {
21
+ this.stdin = stdin;
22
+ this.stdout = stdout;
23
+ }
24
+ async start() {
25
+ if (this.started)
26
+ throw new Error('StdioServerTransport already started');
27
+ this.started = true;
28
+ this.stdin.on('data', this.onData);
29
+ this.stdin.on('error', this.onError);
30
+ }
31
+ async close() {
32
+ this.stdin.off('data', this.onData);
33
+ this.stdin.off('error', this.onError);
34
+ this.buffer = '';
35
+ this.onclose?.();
36
+ }
37
+ async send(message) {
38
+ await new Promise((resolveWrite) => {
39
+ const line = `${JSON.stringify(message)}\n`;
40
+ if (this.stdout.write(line)) {
41
+ resolveWrite();
42
+ }
43
+ else {
44
+ this.stdout.once('drain', resolveWrite);
45
+ }
46
+ });
47
+ }
48
+ onData = (chunk) => {
49
+ this.buffer += chunk.toString();
50
+ let newlineIndex = this.buffer.indexOf('\n');
51
+ while (newlineIndex >= 0) {
52
+ const line = this.buffer.slice(0, newlineIndex).replace(/\r$/, '').trim();
53
+ this.buffer = this.buffer.slice(newlineIndex + 1);
54
+ if (line)
55
+ this.parseLine(line);
56
+ newlineIndex = this.buffer.indexOf('\n');
57
+ }
58
+ };
59
+ onError = (error) => {
60
+ this.onerror?.(error);
61
+ };
62
+ parseLine(line) {
63
+ try {
64
+ const parsed = JSON.parse(line);
65
+ this.onmessage?.(parsed);
66
+ }
67
+ catch (err) {
68
+ const error = err instanceof Error ? err : new Error(String(err));
69
+ this.onerror?.(error);
70
+ void this.send({
71
+ jsonrpc: '2.0',
72
+ id: null,
73
+ error: { code: -32700, message: `Parse error: ${error.message}` },
74
+ });
75
+ }
76
+ }
77
+ }
78
+ export class McpServer {
79
+ serverInfo;
80
+ tools = new Map();
81
+ prompts = new Map();
82
+ resources = new Map();
83
+ capabilities;
84
+ transport;
85
+ log = getLogger();
86
+ constructor(serverInfo, options = {}) {
87
+ this.serverInfo = serverInfo;
88
+ this.capabilities = options.capabilities ?? {};
89
+ }
90
+ registerTool(name, config, handler) {
91
+ assertUnique(this.tools, name, 'Tool');
92
+ this.tools.set(name, { ...config, handler: handler });
93
+ }
94
+ registerPrompt(name, config, handler) {
95
+ assertUnique(this.prompts, name, 'Prompt');
96
+ this.prompts.set(name, { ...config, handler: handler });
97
+ }
98
+ registerResource(name, uri, config, handler) {
99
+ if (this.resources.has(uri))
100
+ throw new Error(`Resource ${uri} is already registered`);
101
+ this.resources.set(uri, { name, uri, ...config, handler });
102
+ }
103
+ async connect(transport) {
104
+ this.transport = transport;
105
+ transport.onmessage = (message) => {
106
+ void this.handleMessage(message);
107
+ };
108
+ transport.onerror = (error) => {
109
+ this.log.error({ err: error.message, stack: error.stack }, 'stdio transport error');
110
+ };
111
+ await transport.start();
112
+ }
113
+ async close() {
114
+ const transport = this.transport;
115
+ this.transport = undefined;
116
+ if (transport)
117
+ await transport.close();
118
+ }
119
+ async handleMessage(message) {
120
+ const id = message.id ?? null;
121
+ const isNotification = message.id === undefined;
122
+ try {
123
+ const result = await this.dispatch(message);
124
+ if (!isNotification)
125
+ await this.send({ jsonrpc: '2.0', id, result });
126
+ }
127
+ catch (err) {
128
+ const protocolError = toProtocolError(err);
129
+ if (!isNotification) {
130
+ await this.send({
131
+ jsonrpc: '2.0',
132
+ id,
133
+ error: protocolError,
134
+ });
135
+ }
136
+ else {
137
+ this.log.warn({ err: protocolError.message, method: message.method }, 'notification failed');
138
+ }
139
+ }
140
+ }
141
+ async dispatch(message) {
142
+ switch (message.method) {
143
+ case 'initialize':
144
+ return this.handleInitialize(message.params);
145
+ case 'notifications/initialized':
146
+ return {};
147
+ case 'ping':
148
+ return {};
149
+ case 'logging/setLevel':
150
+ return {};
151
+ case 'tools/list':
152
+ return { tools: this.listTools() };
153
+ case 'tools/call':
154
+ return this.callTool(message.params);
155
+ case 'prompts/list':
156
+ return { prompts: this.listPrompts() };
157
+ case 'prompts/get':
158
+ return this.getPrompt(message.params);
159
+ case 'resources/list':
160
+ return { resources: this.listResources() };
161
+ case 'resources/templates/list':
162
+ return { resourceTemplates: [] };
163
+ case 'resources/read':
164
+ return this.readResource(message.params);
165
+ default:
166
+ throw new ProtocolError(-32601, `Method not found: ${message.method}`);
167
+ }
168
+ }
169
+ handleInitialize(params) {
170
+ const input = params && typeof params === 'object' ? params : {};
171
+ const requested = typeof input.protocolVersion === 'string' ? input.protocolVersion : undefined;
172
+ return {
173
+ protocolVersion: requested && SUPPORTED_PROTOCOL_VERSIONS.has(requested)
174
+ ? requested
175
+ : LATEST_PROTOCOL_VERSION,
176
+ capabilities: this.getCapabilities(),
177
+ serverInfo: this.serverInfo,
178
+ };
179
+ }
180
+ getCapabilities() {
181
+ return {
182
+ ...this.capabilities,
183
+ tools: { listChanged: true },
184
+ prompts: { listChanged: true },
185
+ resources: { listChanged: true },
186
+ logging: this.capabilities.logging ?? {},
187
+ };
188
+ }
189
+ listTools() {
190
+ return Array.from(this.tools.entries()).map(([name, tool]) => ({
191
+ name,
192
+ title: tool.title,
193
+ description: tool.description,
194
+ inputSchema: tool.inputSchema,
195
+ annotations: tool.annotations,
196
+ }));
197
+ }
198
+ async callTool(params) {
199
+ const input = params && typeof params === 'object' ? params : {};
200
+ const name = input.name;
201
+ if (typeof name !== 'string') {
202
+ throw new ProtocolError(-32602, 'tools/call params.name must be a string');
203
+ }
204
+ const tool = this.tools.get(name);
205
+ if (!tool) {
206
+ throw new ProtocolError(-32602, `Tool ${name} not found`);
207
+ }
208
+ try {
209
+ const args = validateArgs(tool.inputSchema, input.arguments, `tools.${name}`);
210
+ return await tool.handler(args);
211
+ }
212
+ catch (err) {
213
+ return toolError(err instanceof Error ? err.message : String(err));
214
+ }
215
+ }
216
+ listPrompts() {
217
+ return Array.from(this.prompts.entries()).map(([name, prompt]) => ({
218
+ name,
219
+ title: prompt.title,
220
+ description: prompt.description,
221
+ arguments: promptArgumentsFromSchema(prompt.argsSchema),
222
+ }));
223
+ }
224
+ async getPrompt(params) {
225
+ const input = params && typeof params === 'object' ? params : {};
226
+ const name = input.name;
227
+ if (typeof name !== 'string') {
228
+ throw new ProtocolError(-32602, 'prompts/get params.name must be a string');
229
+ }
230
+ const prompt = this.prompts.get(name);
231
+ if (!prompt) {
232
+ throw new ProtocolError(-32602, `Prompt ${name} not found`);
233
+ }
234
+ let args;
235
+ try {
236
+ args = validateArgs(prompt.argsSchema, input.arguments, `prompts.${name}`);
237
+ }
238
+ catch (err) {
239
+ throw new ProtocolError(-32602, err instanceof Error ? err.message : String(err));
240
+ }
241
+ return prompt.handler(args);
242
+ }
243
+ listResources() {
244
+ return Array.from(this.resources.values()).map((resource) => ({
245
+ name: resource.name,
246
+ uri: resource.uri,
247
+ title: resource.title,
248
+ description: resource.description,
249
+ mimeType: resource.mimeType,
250
+ }));
251
+ }
252
+ async readResource(params) {
253
+ const input = params && typeof params === 'object' ? params : {};
254
+ const uri = input.uri;
255
+ if (typeof uri !== 'string') {
256
+ throw new ProtocolError(-32602, 'resources/read params.uri must be a string');
257
+ }
258
+ const resource = this.resources.get(uri);
259
+ if (!resource) {
260
+ throw new ProtocolError(-32602, `Resource ${uri} not found`);
261
+ }
262
+ return resource.handler();
263
+ }
264
+ async send(message) {
265
+ const transport = this.transport;
266
+ if (!transport)
267
+ throw new Error('MCP server is not connected');
268
+ await transport.send(message);
269
+ }
270
+ }
271
+ function assertUnique(map, name, kind) {
272
+ if (map.has(name))
273
+ throw new Error(`${kind} ${name} is already registered`);
274
+ }
275
+ function promptArgumentsFromSchema(schema) {
276
+ const required = new Set(schema.required ?? []);
277
+ return Object.entries(schema.properties).map(([name, field]) => ({
278
+ name,
279
+ description: field.description,
280
+ required: required.has(name),
281
+ }));
282
+ }
283
+ function toolError(message) {
284
+ return {
285
+ isError: true,
286
+ content: [{ type: 'text', text: message }],
287
+ };
288
+ }
289
+ class ProtocolError extends Error {
290
+ code;
291
+ data;
292
+ constructor(code, message, data) {
293
+ super(message);
294
+ this.code = code;
295
+ this.data = data;
296
+ this.name = 'ProtocolError';
297
+ }
298
+ }
299
+ function toProtocolError(err) {
300
+ if (err instanceof ProtocolError) {
301
+ const out = {
302
+ code: err.code,
303
+ message: err.message,
304
+ };
305
+ if (err.data !== undefined)
306
+ out.data = err.data;
307
+ return out;
308
+ }
309
+ return {
310
+ code: -32603,
311
+ message: err instanceof Error ? err.message : String(err),
312
+ };
313
+ }
@@ -0,0 +1,128 @@
1
+ import { objectSchema } from '../mcp/schema.js';
2
+ import { LAYER_SELECTION_SCOPES, } from '../codesign/selection.js';
3
+ const argsSchema = objectSchema({
4
+ sharingUrl: {
5
+ type: 'string',
6
+ minLength: 1,
7
+ description: 'CoDesign sharing URL or bare sharing id.',
8
+ },
9
+ password: {
10
+ type: 'string',
11
+ description: 'Sharing password, if the CoDesign link requires one.',
12
+ },
13
+ artboardName: {
14
+ type: 'string',
15
+ description: 'Preferred artboard or screen name, if the user already knows it.',
16
+ },
17
+ screenId: {
18
+ anyOf: [{ type: 'integer' }, { type: 'string' }],
19
+ description: 'Exact CoDesign screen id copied from a selected-region reference.',
20
+ },
21
+ layerObjectId: {
22
+ type: 'string',
23
+ description: 'Exact CoDesign layer object_id copied from a selected-region reference.',
24
+ },
25
+ layerName: {
26
+ type: 'string',
27
+ description: 'Human-readable selected layer name for prompt context.',
28
+ },
29
+ selectionScope: {
30
+ type: 'string',
31
+ enum: [...LAYER_SELECTION_SCOPES],
32
+ description: 'Selected layer scope: layer, strict subtree, or the complete visual region inside its bounds.',
33
+ },
34
+ targetPlatform: {
35
+ type: 'string',
36
+ description: 'Target development platform in the user\'s natural language, e.g. web, Android, 安卓, iOS, 微信小程序, or mini program.',
37
+ },
38
+ targetUnit: {
39
+ type: 'string',
40
+ description: 'Target unit when the user specifies one, e.g. px, rem, dp, pt, or rpx.',
41
+ },
42
+ customScale: {
43
+ type: 'number',
44
+ minimum: 0,
45
+ description: 'Custom platform scale when the user specifies a multiplier such as 0.75x or 2x.',
46
+ },
47
+ customWidth: {
48
+ type: 'number',
49
+ minimum: 0,
50
+ description: 'Custom platform width when the user specifies a target design width such as 1440px. The tool computes customWidth / source artboard width.',
51
+ },
52
+ remBasePx: {
53
+ type: 'number',
54
+ minimum: 0,
55
+ description: 'Pixels per rem when targetUnit is rem, e.g. 16 or 100.',
56
+ },
57
+ outputDir: {
58
+ type: 'string',
59
+ description: 'Target implementation directory, if the user provided one.',
60
+ },
61
+ }, ['sharingUrl']);
62
+ export function registerDesignToCodePrompt(server) {
63
+ server.registerPrompt('implement_codesign_page', {
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.',
66
+ argsSchema,
67
+ }, async ({ sharingUrl, password, artboardName, screenId, layerObjectId, layerName, selectionScope, targetPlatform, targetUnit, customScale, customWidth, remBasePx, outputDir, }) => ({
68
+ messages: [
69
+ {
70
+ role: 'user',
71
+ content: {
72
+ type: 'text',
73
+ text: buildPrompt({
74
+ sharingUrl,
75
+ password,
76
+ artboardName,
77
+ screenId,
78
+ layerObjectId,
79
+ layerName,
80
+ selectionScope,
81
+ targetPlatform,
82
+ targetUnit,
83
+ customScale,
84
+ customWidth,
85
+ remBasePx,
86
+ outputDir,
87
+ }),
88
+ },
89
+ },
90
+ ],
91
+ }));
92
+ }
93
+ function buildPrompt(args) {
94
+ const passwordLine = args.password ? `Password: ${args.password}\n` : '';
95
+ const artboardLine = args.artboardName ? `Preferred artboard: ${args.artboardName}\n` : '';
96
+ const screenIdLine = args.screenId != null ? `Screen ID: ${args.screenId}\n` : '';
97
+ const layerIdLine = args.layerObjectId ? `Layer object ID: ${args.layerObjectId}\n` : '';
98
+ const layerNameLine = args.layerName ? `Selected layer: ${args.layerName}\n` : '';
99
+ const effectiveSelectionScope = args.layerObjectId
100
+ ? (args.selectionScope ?? 'region')
101
+ : args.selectionScope;
102
+ const selectionScopeLine = effectiveSelectionScope
103
+ ? `Selection scope: ${effectiveSelectionScope}\n`
104
+ : '';
105
+ const platformLine = args.targetPlatform ? `Target platform: ${args.targetPlatform}\n` : '';
106
+ const unitLine = args.targetUnit ? `Target unit: ${args.targetUnit}\n` : '';
107
+ const customScaleLine = args.customScale != null ? `Custom scale: ${args.customScale}\n` : '';
108
+ const customWidthLine = args.customWidth != null ? `Custom width: ${args.customWidth}\n` : '';
109
+ const remBaseLine = args.remBasePx != null ? `Rem base px: ${args.remBasePx}\n` : '';
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.`;
128
+ }
@@ -0,0 +1,33 @@
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.
18
+ `;
19
+ export function registerWorkflowResource(server) {
20
+ server.registerResource('design-to-code-workflow', DESIGN_TO_CODE_WORKFLOW_URI, {
21
+ title: 'CoDesign Design-to-Code Workflow',
22
+ description: 'Read-only workflow guidance for using codesign-mcp tools to implement pages from Tencent CoDesign sharing links.',
23
+ mimeType: 'text/markdown',
24
+ }, async () => ({
25
+ contents: [
26
+ {
27
+ uri: DESIGN_TO_CODE_WORKFLOW_URI,
28
+ mimeType: 'text/markdown',
29
+ text: workflowMarkdown,
30
+ },
31
+ ],
32
+ }));
33
+ }
package/dist/server.js ADDED
@@ -0,0 +1,61 @@
1
+ import { McpServer, StdioServerTransport } from './mcp/server.js';
2
+ import { registerStatusTool } from './tools/status.js';
3
+ import { registerLoginTool } from './tools/login.js';
4
+ import { registerArtboardsTool } from './tools/artboards.js';
5
+ import { registerSpecTool } from './tools/spec.js';
6
+ import { registerImageTool } from './tools/image.js';
7
+ import { registerSlicesTool } from './tools/slices.js';
8
+ import { registerDiagnosticsTool } from './tools/diagnostics.js';
9
+ import { registerDesignToCodePrompt } from './prompts/design-to-code.js';
10
+ import { registerWorkflowResource } from './resources/workflow.js';
11
+ import { getLogger } from './logger.js';
12
+ import { browserManager } from './browser/manager.js';
13
+ import { config } from './config.js';
14
+ const log = getLogger();
15
+ export function buildServer() {
16
+ const server = new McpServer({
17
+ name: 'codesign-mcp',
18
+ version: config.packageVersion,
19
+ }, {
20
+ capabilities: {
21
+ tools: {},
22
+ prompts: {},
23
+ resources: {},
24
+ logging: {},
25
+ },
26
+ });
27
+ registerStatusTool(server);
28
+ registerLoginTool(server);
29
+ registerArtboardsTool(server);
30
+ registerSpecTool(server);
31
+ registerImageTool(server);
32
+ registerSlicesTool(server);
33
+ registerDiagnosticsTool(server);
34
+ registerDesignToCodePrompt(server);
35
+ registerWorkflowResource(server);
36
+ return server;
37
+ }
38
+ export async function startStdio() {
39
+ const server = buildServer();
40
+ const transport = new StdioServerTransport();
41
+ log.debug('starting stdio MCP server');
42
+ await server.connect(transport);
43
+ const shutdown = async (signal) => {
44
+ log.info({ signal }, 'received signal, shutting down');
45
+ try {
46
+ await browserManager.shutdown(`signal:${signal}`);
47
+ }
48
+ catch (err) {
49
+ log.warn({ err: err.message }, 'browser shutdown failed');
50
+ }
51
+ try {
52
+ await server.close();
53
+ }
54
+ catch (err) {
55
+ log.warn({ err: err.message }, 'server.close failed');
56
+ }
57
+ process.exit(0);
58
+ };
59
+ process.on('SIGINT', () => void shutdown('SIGINT'));
60
+ process.on('SIGTERM', () => void shutdown('SIGTERM'));
61
+ }
@@ -0,0 +1,96 @@
1
+ import { objectSchema } from '../mcp/schema.js';
2
+ import { browserManager } from '../browser/manager.js';
3
+ import { getCachedSharingDetail } from '../codesign/cache.js';
4
+ import { inspectSharingDetail, integrityView } from '../codesign/integrity.js';
5
+ import { parseSharingId } from '../utils/url.js';
6
+ import { getLogger } from '../logger.js';
7
+ import { toolSuccess, toolError as buildErrorResult } from '../mcp/result.js';
8
+ const log = getLogger();
9
+ const inputSchema = objectSchema({
10
+ sharingUrl: {
11
+ type: 'string',
12
+ minLength: 1,
13
+ description: 'CoDesign sharing URL (https://codesign.qq.com/app/s/<id>) or bare sharing id',
14
+ },
15
+ password: {
16
+ type: 'string',
17
+ description: 'Sharing password if required',
18
+ },
19
+ includeFullText: {
20
+ type: 'boolean',
21
+ default: false,
22
+ description: 'Set true only if your client cannot read structuredContent. Then content[0].text carries the full JSON instead of a short summary.',
23
+ },
24
+ }, ['sharingUrl']);
25
+ export function registerArtboardsTool(server) {
26
+ server.registerTool('list_artboards', {
27
+ title: 'List CoDesign Artboards',
28
+ description: 'Use this first when a task contains a CoDesign sharing URL or asks to implement/recreate a CoDesign design. ' +
29
+ 'It resolves the official CoDesign sharing data into designs and screens with id, object_id, name, size, image URLs, meta_url, and slices_url. ' +
30
+ 'For design-to-code work, select a screen from this result before calling get_artboard_spec. Do not infer screens by cropping preview images.',
31
+ inputSchema,
32
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
33
+ }, async ({ sharingUrl, password, includeFullText }) => {
34
+ let sharingId;
35
+ try {
36
+ sharingId = parseSharingId(sharingUrl);
37
+ }
38
+ catch (err) {
39
+ return errorResult(err);
40
+ }
41
+ const call = await browserManager.acquireHeadless();
42
+ try {
43
+ const { detail, stateKey } = await getCachedSharingDetail(call.page, sharingId, password);
44
+ const designs = (detail.designs ?? []).map((d) => ({
45
+ id: d.id,
46
+ name: d.name,
47
+ screens: (d.screens ?? []).map((s) => ({
48
+ id: s.id,
49
+ objectId: s.object_id,
50
+ name: s.name,
51
+ width: s.width,
52
+ height: s.height,
53
+ frame: s.frame,
54
+ slicesCount: s.slices_count,
55
+ metaUrl: s.meta_url,
56
+ slicesUrl: s.slices_url,
57
+ image: s.image && {
58
+ url: s.image.url,
59
+ coverUrl: s.image.cover_url,
60
+ slicesBaseUrl: s.image.slices_base_url,
61
+ width: s.image.width,
62
+ height: s.image.height,
63
+ mime: s.image.mime,
64
+ size: s.image.size,
65
+ },
66
+ })),
67
+ }));
68
+ const totalScreens = designs.reduce((acc, d) => acc + d.screens.length, 0);
69
+ return toolSuccess({
70
+ sharingId,
71
+ title: detail.title,
72
+ designCount: designs.length,
73
+ screenCount: totalScreens,
74
+ integrity: integrityView(inspectSharingDetail(detail)),
75
+ designs,
76
+ stateKey: stateKey ? '<acquired>' : null,
77
+ }, includeFullText);
78
+ }
79
+ catch (err) {
80
+ log.warn({ err: errMsg(err), sharingId }, 'list_artboards failed');
81
+ return errorResult(err);
82
+ }
83
+ finally {
84
+ await call.done();
85
+ }
86
+ });
87
+ }
88
+ // Re-exported for sibling tools that still import errorResult from here.
89
+ export function errorResult(err) {
90
+ return buildErrorResult(err);
91
+ }
92
+ function errMsg(err) {
93
+ if (err instanceof Error)
94
+ return err.message;
95
+ return String(err);
96
+ }