codesign-mcp-next 0.0.0-stage → 0.3.2
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/CHANGELOG.md +121 -0
- package/LICENSE +21 -0
- package/README.md +458 -3
- package/dist/browser/manager.js +204 -0
- package/dist/browser/session.js +62 -0
- package/dist/codesign/cache.js +85 -0
- package/dist/codesign/errors.js +47 -0
- package/dist/codesign/integrity.js +197 -0
- package/dist/codesign/meta.js +57 -0
- package/dist/codesign/parser.js +56 -0
- package/dist/codesign/platform.js +232 -0
- package/dist/codesign/selection.js +205 -0
- package/dist/codesign/sharing.js +153 -0
- package/dist/codesign/slices.js +34 -0
- package/dist/codesign/types.js +1 -0
- package/dist/config.js +94 -0
- package/dist/index.js +16 -0
- package/dist/logger.js +68 -0
- package/dist/mcp/result.js +151 -0
- package/dist/mcp/schema.js +122 -0
- package/dist/mcp/server.js +313 -0
- package/dist/prompts/design-to-code.js +128 -0
- package/dist/resources/workflow.js +33 -0
- package/dist/server.js +61 -0
- package/dist/tools/artboards.js +96 -0
- package/dist/tools/diagnostics.js +192 -0
- package/dist/tools/image.js +134 -0
- package/dist/tools/login.js +136 -0
- package/dist/tools/slices.js +228 -0
- package/dist/tools/spec.js +236 -0
- package/dist/tools/status.js +62 -0
- package/dist/utils/download.js +290 -0
- package/dist/utils/filename.js +16 -0
- package/dist/utils/http.js +54 -0
- package/dist/utils/rate-limit.js +120 -0
- package/dist/utils/redact.js +110 -0
- package/dist/utils/retry.js +97 -0
- package/dist/utils/url.js +98 -0
- package/package.json +58 -6
- package/userscripts/codesign-ai-selection.user.js +445 -0
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
2
|
+
import { browserManager } from '../browser/manager.js';
|
|
3
|
+
import { getSharingDetail } from '../codesign/sharing.js';
|
|
4
|
+
import { parseSharingId } from '../utils/url.js';
|
|
5
|
+
import { redactUrl, redactHeaderValue, topLevelKeys, isSensitiveHeader } from '../utils/redact.js';
|
|
6
|
+
import { errorResult } from './artboards.js';
|
|
7
|
+
import { toolSuccessFull } from '../mcp/result.js';
|
|
8
|
+
import { getLogger } from '../logger.js';
|
|
9
|
+
import { config } from '../config.js';
|
|
10
|
+
const log = getLogger();
|
|
11
|
+
const inputSchema = objectSchema({
|
|
12
|
+
sharingUrl: { type: 'string', minLength: 1 },
|
|
13
|
+
password: { type: 'string' },
|
|
14
|
+
timeoutMs: { type: 'integer', minimum: 1_000, maximum: 60_000, default: 15_000 },
|
|
15
|
+
includeHeaders: { type: 'boolean', default: false },
|
|
16
|
+
maxBodyKeyDepth: { type: 'integer', minimum: 0, maximum: 3, default: 0 },
|
|
17
|
+
}, ['sharingUrl']);
|
|
18
|
+
export function registerDiagnosticsTool(server) {
|
|
19
|
+
server.registerTool('debug_collect_network', {
|
|
20
|
+
title: 'Collect CoDesign Network (Diagnostics)',
|
|
21
|
+
description: 'Open the sharing page in a headless browser, record all network responses for `timeoutMs`, and return a REDACTED summary. ' +
|
|
22
|
+
'Use this to discover unknown endpoints or to debug why a tool fails. ' +
|
|
23
|
+
'Output never contains Cookie, Authorization, password, state-key values, or response bodies — only JSON key paths.',
|
|
24
|
+
inputSchema,
|
|
25
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
26
|
+
}, async (args) => {
|
|
27
|
+
const { sharingUrl, password, timeoutMs, includeHeaders, maxBodyKeyDepth } = args;
|
|
28
|
+
let sharingId;
|
|
29
|
+
try {
|
|
30
|
+
sharingId = parseSharingId(sharingUrl);
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
return errorResult(err);
|
|
34
|
+
}
|
|
35
|
+
const call = await browserManager.acquireHeadless();
|
|
36
|
+
const records = new Map();
|
|
37
|
+
const finishedResponses = [];
|
|
38
|
+
const onRequest = (req) => {
|
|
39
|
+
records.set(req, {
|
|
40
|
+
startedAt: Date.now(),
|
|
41
|
+
url: redactUrl(req.url()),
|
|
42
|
+
method: req.method(),
|
|
43
|
+
status: null,
|
|
44
|
+
mimeType: null,
|
|
45
|
+
size: null,
|
|
46
|
+
durationMs: null,
|
|
47
|
+
requestHeaders: includeHeaders ? headersToList(req.headers()) : [],
|
|
48
|
+
responseHeaders: [],
|
|
49
|
+
bodyTopKeys: null,
|
|
50
|
+
bodyKind: 'empty',
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
const onResponse = async (resp) => {
|
|
54
|
+
const req = resp.request();
|
|
55
|
+
const rec = records.get(req);
|
|
56
|
+
const now = Date.now();
|
|
57
|
+
const status = resp.status();
|
|
58
|
+
const mime = resp.headers()['content-type'] ?? null;
|
|
59
|
+
const headersList = includeHeaders ? headersToList(resp.headers()) : [];
|
|
60
|
+
let bodyKind = 'empty';
|
|
61
|
+
let bodyTopKeys = null;
|
|
62
|
+
let size = null;
|
|
63
|
+
try {
|
|
64
|
+
if (mime && mime.includes('json')) {
|
|
65
|
+
const text = await resp.text();
|
|
66
|
+
size = text.length;
|
|
67
|
+
try {
|
|
68
|
+
const parsed = JSON.parse(text);
|
|
69
|
+
if (Array.isArray(parsed)) {
|
|
70
|
+
bodyKind = 'array';
|
|
71
|
+
bodyTopKeys = parsed.length > 0 ? topLevelKeys(parsed[0], maxBodyKeyDepth) : [];
|
|
72
|
+
}
|
|
73
|
+
else if (parsed && typeof parsed === 'object') {
|
|
74
|
+
bodyKind = 'object';
|
|
75
|
+
bodyTopKeys = topLevelKeys(parsed, maxBodyKeyDepth);
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
bodyKind = 'text';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
bodyKind = 'parse-error';
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
else if (mime && mime.startsWith('text/')) {
|
|
86
|
+
const text = await resp.text();
|
|
87
|
+
size = text.length;
|
|
88
|
+
bodyKind = 'text';
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
// 二进制、不读 body 内容(避免大流量)
|
|
92
|
+
bodyKind = 'binary';
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
rec && (rec.errorMessage = err.message);
|
|
97
|
+
}
|
|
98
|
+
const merged = {
|
|
99
|
+
startedAt: rec?.startedAt ?? now,
|
|
100
|
+
url: redactUrl(resp.url()),
|
|
101
|
+
method: resp.request().method(),
|
|
102
|
+
status,
|
|
103
|
+
mimeType: mime,
|
|
104
|
+
size,
|
|
105
|
+
durationMs: rec ? now - rec.startedAt : null,
|
|
106
|
+
requestHeaders: rec?.requestHeaders ?? [],
|
|
107
|
+
responseHeaders: headersList,
|
|
108
|
+
bodyTopKeys,
|
|
109
|
+
bodyKind,
|
|
110
|
+
};
|
|
111
|
+
if (rec?.errorMessage)
|
|
112
|
+
merged.errorMessage = rec.errorMessage;
|
|
113
|
+
finishedResponses.push(merged);
|
|
114
|
+
records.delete(req);
|
|
115
|
+
};
|
|
116
|
+
const onResponseEvent = (resp) => {
|
|
117
|
+
void onResponse(resp);
|
|
118
|
+
};
|
|
119
|
+
call.page.on('request', onRequest);
|
|
120
|
+
call.page.on('response', onResponseEvent);
|
|
121
|
+
const detach = () => {
|
|
122
|
+
call.page.off('request', onRequest);
|
|
123
|
+
call.page.off('response', onResponseEvent);
|
|
124
|
+
};
|
|
125
|
+
try {
|
|
126
|
+
// 导航 + 必要时密码换 key,复用同一 page
|
|
127
|
+
const page = call.page;
|
|
128
|
+
await page.goto(`${config.origin}/app/s/${sharingId}`, {
|
|
129
|
+
waitUntil: 'domcontentloaded',
|
|
130
|
+
timeout: config.navTimeoutMs,
|
|
131
|
+
});
|
|
132
|
+
if (password) {
|
|
133
|
+
try {
|
|
134
|
+
await getSharingDetail(page, sharingId, password);
|
|
135
|
+
}
|
|
136
|
+
catch (err) {
|
|
137
|
+
log.warn({ err: err.message }, 'diagnostic sharing fetch warned');
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
// 静置等待,让前端继续触发请求
|
|
141
|
+
await new Promise((r) => setTimeout(r, timeoutMs));
|
|
142
|
+
const summary = summarizeRecords(finishedResponses);
|
|
143
|
+
return toolSuccessFull({
|
|
144
|
+
sharingId,
|
|
145
|
+
timeoutMs,
|
|
146
|
+
recordedCount: finishedResponses.length,
|
|
147
|
+
inFlightAtEnd: records.size,
|
|
148
|
+
...summary,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
log.warn({ err: errMsg(err), sharingId }, 'debug_collect_network failed');
|
|
153
|
+
return errorResult(err);
|
|
154
|
+
}
|
|
155
|
+
finally {
|
|
156
|
+
detach();
|
|
157
|
+
await call.done();
|
|
158
|
+
}
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function headersToList(h) {
|
|
162
|
+
return Object.entries(h).map(([name, value]) => ({
|
|
163
|
+
name,
|
|
164
|
+
value: isSensitiveHeader(name) ? '<redacted>' : redactHeaderValue(name, value),
|
|
165
|
+
}));
|
|
166
|
+
}
|
|
167
|
+
function summarizeRecords(records) {
|
|
168
|
+
const hostMap = new Map();
|
|
169
|
+
const statusMap = new Map();
|
|
170
|
+
for (const r of records) {
|
|
171
|
+
let host = '<unknown>';
|
|
172
|
+
try {
|
|
173
|
+
host = new URL(r.url).host;
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
/* ignore */
|
|
177
|
+
}
|
|
178
|
+
hostMap.set(host, (hostMap.get(host) ?? 0) + 1);
|
|
179
|
+
const key = r.status ?? 'unknown';
|
|
180
|
+
statusMap.set(key, (statusMap.get(key) ?? 0) + 1);
|
|
181
|
+
}
|
|
182
|
+
return {
|
|
183
|
+
records,
|
|
184
|
+
byHost: Array.from(hostMap.entries()).map(([host, count]) => ({ host, count })),
|
|
185
|
+
byStatus: Array.from(statusMap.entries()).map(([status, count]) => ({ status, count })),
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
function errMsg(err) {
|
|
189
|
+
if (err instanceof Error)
|
|
190
|
+
return err.message;
|
|
191
|
+
return String(err);
|
|
192
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
2
|
+
import { browserManager } from '../browser/manager.js';
|
|
3
|
+
import { getCachedSharingDetail } from '../codesign/cache.js';
|
|
4
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
5
|
+
import { parseSharingId } from '../utils/url.js';
|
|
6
|
+
import { downloadToArtifact } from '../utils/download.js';
|
|
7
|
+
import { errorResult } from './artboards.js';
|
|
8
|
+
import { toolSuccess } from '../mcp/result.js';
|
|
9
|
+
import { pickScreen, summarizeScreens } from './spec.js';
|
|
10
|
+
import { getLogger } from '../logger.js';
|
|
11
|
+
const log = getLogger();
|
|
12
|
+
const inputSchema = objectSchema({
|
|
13
|
+
sharingUrl: { type: 'string', minLength: 1 },
|
|
14
|
+
password: { type: 'string' },
|
|
15
|
+
screenId: { anyOf: [{ type: 'integer' }, { type: 'string' }] },
|
|
16
|
+
objectId: { type: 'string' },
|
|
17
|
+
screenName: { type: 'string' },
|
|
18
|
+
variant: { type: 'string', enum: ['full', 'cover'], default: 'full' },
|
|
19
|
+
download: { type: 'boolean', default: false },
|
|
20
|
+
includeFullText: {
|
|
21
|
+
type: 'boolean',
|
|
22
|
+
default: false,
|
|
23
|
+
description: 'Set true only if your client cannot read structuredContent. Then content[0].text carries the full JSON instead of a short summary.',
|
|
24
|
+
},
|
|
25
|
+
}, ['sharingUrl']);
|
|
26
|
+
export function registerImageTool(server) {
|
|
27
|
+
server.registerTool('get_artboard_image', {
|
|
28
|
+
title: 'Get CoDesign Artboard Image',
|
|
29
|
+
description: 'Returns the CoDesign preview or cover image for visual comparison only. ' +
|
|
30
|
+
'For implementation, prefer get_artboard_spec for layout/text/CSS and download_slice for designer-exported assets; do not crop this preview image to create production slices. ' +
|
|
31
|
+
'When download=true, stores the image under <workspaceRoot>/.codesign-mcp/artifacts/<sharingId>/screens/. Selector precedence: screenId > objectId > screenName.',
|
|
32
|
+
inputSchema,
|
|
33
|
+
}, async (args) => {
|
|
34
|
+
const { sharingUrl, password, screenId, objectId, screenName, variant, download, includeFullText } = args;
|
|
35
|
+
let sharingId;
|
|
36
|
+
try {
|
|
37
|
+
sharingId = parseSharingId(sharingUrl);
|
|
38
|
+
}
|
|
39
|
+
catch (err) {
|
|
40
|
+
return errorResult(err);
|
|
41
|
+
}
|
|
42
|
+
const call = await browserManager.acquireHeadless();
|
|
43
|
+
try {
|
|
44
|
+
const { detail } = await getCachedSharingDetail(call.page, sharingId, password);
|
|
45
|
+
const allScreens = [];
|
|
46
|
+
for (const d of detail.designs ?? []) {
|
|
47
|
+
for (const s of d.screens ?? [])
|
|
48
|
+
allScreens.push(s);
|
|
49
|
+
}
|
|
50
|
+
if (allScreens.length === 0) {
|
|
51
|
+
return errorResult(new CodesignError('SHARING_NOT_FOUND', 'sharing has no screens', { sharingId }));
|
|
52
|
+
}
|
|
53
|
+
const selector = { screenId, objectId, screenName };
|
|
54
|
+
const picked = pickScreen(allScreens, selector);
|
|
55
|
+
if (!picked) {
|
|
56
|
+
if (selector.screenId == null && !selector.objectId && !selector.screenName) {
|
|
57
|
+
return errorResult(new CodesignError('SCREEN_SELECTOR_REQUIRED', 'multiple screens present; specify a selector', { available: summarizeScreens(allScreens) }));
|
|
58
|
+
}
|
|
59
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'no screen matches the given selector', {
|
|
60
|
+
selector,
|
|
61
|
+
available: summarizeScreens(allScreens),
|
|
62
|
+
}));
|
|
63
|
+
}
|
|
64
|
+
const url = variant === 'cover' ? picked.image?.cover_url : picked.image?.url;
|
|
65
|
+
if (!url) {
|
|
66
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', `screen has no ${variant} image url`, {
|
|
67
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
const result = {
|
|
71
|
+
sharingId,
|
|
72
|
+
variant,
|
|
73
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
74
|
+
image: {
|
|
75
|
+
url,
|
|
76
|
+
width: picked.image?.width,
|
|
77
|
+
height: picked.image?.height,
|
|
78
|
+
mime: picked.image?.mime,
|
|
79
|
+
size: picked.image?.size,
|
|
80
|
+
},
|
|
81
|
+
};
|
|
82
|
+
if (download) {
|
|
83
|
+
try {
|
|
84
|
+
const dl = await downloadToArtifact(url, `${sharingId}/screens`, `${picked.id}-${variant}${guessExt(url, picked.image?.mime)}`, 'META_FETCH_FAILED', {
|
|
85
|
+
expectedBytes: picked.image?.size,
|
|
86
|
+
});
|
|
87
|
+
result.download = {
|
|
88
|
+
path: dl.path,
|
|
89
|
+
bytes: dl.bytes,
|
|
90
|
+
mime: dl.mime,
|
|
91
|
+
reusedExisting: dl.reusedExisting,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
catch (err) {
|
|
95
|
+
log.warn({ err: err.message }, 'image download failed');
|
|
96
|
+
return errorResult(err);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return toolSuccess(result, includeFullText);
|
|
100
|
+
}
|
|
101
|
+
catch (err) {
|
|
102
|
+
log.warn({ err: errMsg(err), sharingId }, 'get_artboard_image failed');
|
|
103
|
+
return errorResult(err);
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
await call.done();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
function guessExt(url, mime) {
|
|
111
|
+
if (mime) {
|
|
112
|
+
if (mime.includes('png'))
|
|
113
|
+
return '.png';
|
|
114
|
+
if (mime.includes('jpeg') || mime.includes('jpg'))
|
|
115
|
+
return '.jpg';
|
|
116
|
+
if (mime.includes('webp'))
|
|
117
|
+
return '.webp';
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
const u = new URL(url);
|
|
121
|
+
const m = u.pathname.match(/\.([a-z0-9]+)$/i);
|
|
122
|
+
if (m)
|
|
123
|
+
return `.${m[1].toLowerCase()}`;
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
/* ignore */
|
|
127
|
+
}
|
|
128
|
+
return '.png';
|
|
129
|
+
}
|
|
130
|
+
function errMsg(err) {
|
|
131
|
+
if (err instanceof Error)
|
|
132
|
+
return err.message;
|
|
133
|
+
return String(err);
|
|
134
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { rmSync, existsSync } from 'node:fs';
|
|
2
|
+
import { relative, resolve } from 'node:path';
|
|
3
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
4
|
+
import { config } from '../config.js';
|
|
5
|
+
import { getLogger } from '../logger.js';
|
|
6
|
+
import { toolSuccess, toolFailure } from '../mcp/result.js';
|
|
7
|
+
import { browserManager } from '../browser/manager.js';
|
|
8
|
+
import { probeLoggedIn, waitForLogin } from '../browser/session.js';
|
|
9
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
10
|
+
const log = getLogger();
|
|
11
|
+
const loginInputSchema = objectSchema({
|
|
12
|
+
waitMs: {
|
|
13
|
+
type: 'integer',
|
|
14
|
+
minimum: 10_000,
|
|
15
|
+
maximum: 20 * 60 * 1000,
|
|
16
|
+
description: 'Max wait time for the user to finish scanning. Defaults to 10 min.',
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
export function registerLoginTool(server) {
|
|
20
|
+
server.registerTool('codesign_login', {
|
|
21
|
+
title: 'CoDesign Login',
|
|
22
|
+
description: 'Open a visible Chromium window pointed at codesign.qq.com so the user can scan-login. ' +
|
|
23
|
+
'If already logged in, returns immediately without opening a window. ' +
|
|
24
|
+
'The session is persisted under profileDir and reused by subsequent tools.',
|
|
25
|
+
inputSchema: loginInputSchema,
|
|
26
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
27
|
+
}, async ({ waitMs }) => {
|
|
28
|
+
// 1) 先尝试 headless 静默 probe
|
|
29
|
+
log.info('login: probing existing session (headless)');
|
|
30
|
+
const headless = await browserManager.acquireHeadless();
|
|
31
|
+
try {
|
|
32
|
+
const probe = await probeLoggedIn(headless.page);
|
|
33
|
+
if (probe.loggedIn) {
|
|
34
|
+
return toolSuccess({
|
|
35
|
+
stage: 'already-logged-in',
|
|
36
|
+
user: probe.user,
|
|
37
|
+
profileDir: config.profileDir,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
finally {
|
|
42
|
+
await headless.done();
|
|
43
|
+
}
|
|
44
|
+
// 2) 静默未登录 → 打开 headed 窗口
|
|
45
|
+
log.info('login: opening headed window for QR scan');
|
|
46
|
+
const headed = await browserManager.acquireHeaded();
|
|
47
|
+
try {
|
|
48
|
+
await headed.page.goto(`${config.origin}${config.homePath}`, {
|
|
49
|
+
waitUntil: 'domcontentloaded',
|
|
50
|
+
timeout: config.navTimeoutMs,
|
|
51
|
+
});
|
|
52
|
+
const result = await waitForLogin(headed.page, {
|
|
53
|
+
timeoutMs: waitMs ?? 10 * 60 * 1000,
|
|
54
|
+
pollMs: 2000,
|
|
55
|
+
});
|
|
56
|
+
if (!result.loggedIn) {
|
|
57
|
+
return toolFailure({
|
|
58
|
+
stage: 'timeout-or-cancelled',
|
|
59
|
+
lastStatus: result.status,
|
|
60
|
+
profileDir: config.profileDir,
|
|
61
|
+
hint: 'Re-run codesign_login. The browser window will reopen.',
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return toolSuccess({
|
|
65
|
+
stage: 'just-logged-in',
|
|
66
|
+
user: result.user,
|
|
67
|
+
profileDir: config.profileDir,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
await headed.done();
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
const logoutInputSchema = objectSchema({
|
|
75
|
+
confirm: {
|
|
76
|
+
const: true,
|
|
77
|
+
description: 'Must be true. Wipes the persistent profile.',
|
|
78
|
+
},
|
|
79
|
+
}, ['confirm']);
|
|
80
|
+
server.registerTool('codesign_logout', {
|
|
81
|
+
title: 'CoDesign Logout',
|
|
82
|
+
description: 'Close any running browser and wipe the persistent profile directory. ' +
|
|
83
|
+
'Pass { confirm: true }. The target path is included in the result so the caller can verify before re-running.',
|
|
84
|
+
inputSchema: logoutInputSchema,
|
|
85
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
86
|
+
}, async ({ confirm }) => {
|
|
87
|
+
if (!confirm) {
|
|
88
|
+
return toolFailure({ stage: 'no-confirm', profileDir: config.profileDir });
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
assertProfileDirCanBeCleared();
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
const error = err instanceof CodesignError ? err.toJSON() : { code: 'INTERNAL', message: errMsg(err) };
|
|
95
|
+
return toolFailure({ stage: 'unsafe-profile-dir', profileDir: config.profileDir, error });
|
|
96
|
+
}
|
|
97
|
+
await browserManager.shutdown('logout');
|
|
98
|
+
const existed = existsSync(config.profileDir);
|
|
99
|
+
if (existed) {
|
|
100
|
+
try {
|
|
101
|
+
rmSync(config.profileDir, { recursive: true, force: true });
|
|
102
|
+
}
|
|
103
|
+
catch (err) {
|
|
104
|
+
log.warn({ err: err.message }, 'failed to remove profileDir');
|
|
105
|
+
return toolFailure({
|
|
106
|
+
stage: 'rm-failed',
|
|
107
|
+
profileDir: config.profileDir,
|
|
108
|
+
error: err.message,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return toolSuccess({ stage: 'cleared', profileDir: config.profileDir, hadProfile: existed });
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
export function assertProfileDirCanBeCleared() {
|
|
116
|
+
const profileDir = resolve(config.profileDir);
|
|
117
|
+
const allowedProfileDirs = [
|
|
118
|
+
resolve(config.dataDir, 'profile'),
|
|
119
|
+
resolve(config.workspaceRoot, '.codesign-mcp', 'profile'),
|
|
120
|
+
];
|
|
121
|
+
if (allowedProfileDirs.some((allowed) => isSamePath(allowed, profileDir))) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
throw new CodesignError('PROFILE_DIR_UNSAFE', 'profileDir is outside the allowed runtime directories', {
|
|
125
|
+
profileDir,
|
|
126
|
+
allowedProfileDirs,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function isSamePath(left, right) {
|
|
130
|
+
return relative(left, right) === '';
|
|
131
|
+
}
|
|
132
|
+
function errMsg(err) {
|
|
133
|
+
if (err instanceof Error)
|
|
134
|
+
return err.message;
|
|
135
|
+
return String(err);
|
|
136
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { objectSchema } from '../mcp/schema.js';
|
|
3
|
+
import { browserManager } from '../browser/manager.js';
|
|
4
|
+
import { getCachedSharingDetail, fetchCachedSliceManifest } from '../codesign/cache.js';
|
|
5
|
+
import { findSliceByObjectId } from '../codesign/slices.js';
|
|
6
|
+
import { inspectManifest, integrityView } from '../codesign/integrity.js';
|
|
7
|
+
import { CodesignError } from '../codesign/errors.js';
|
|
8
|
+
import { normalizeCodesignAssetUrl, parseSharingId } from '../utils/url.js';
|
|
9
|
+
import { downloadToArtifact } from '../utils/download.js';
|
|
10
|
+
import { encodeFilenameComponent } from '../utils/filename.js';
|
|
11
|
+
import { errorResult } from './artboards.js';
|
|
12
|
+
import { toolSuccess } from '../mcp/result.js';
|
|
13
|
+
import { pickScreen, summarizeScreens } from './spec.js';
|
|
14
|
+
import { getLogger } from '../logger.js';
|
|
15
|
+
const log = getLogger();
|
|
16
|
+
const SLICE_DOWNLOAD_HEADERS = {
|
|
17
|
+
Accept: 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
|
|
18
|
+
Referer: 'https://codesign.qq.com/',
|
|
19
|
+
};
|
|
20
|
+
const inputSchema = objectSchema({
|
|
21
|
+
sharingUrl: { type: 'string', minLength: 1 },
|
|
22
|
+
password: { type: 'string' },
|
|
23
|
+
screenId: { anyOf: [{ type: 'integer' }, { type: 'string' }] },
|
|
24
|
+
objectId: { type: 'string' },
|
|
25
|
+
screenName: { type: 'string' },
|
|
26
|
+
layerObjectId: {
|
|
27
|
+
type: 'string',
|
|
28
|
+
minLength: 1,
|
|
29
|
+
description: 'object_id of the slice layer',
|
|
30
|
+
},
|
|
31
|
+
format: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'Filter exportables by format (png, jpg, svg, etc.)',
|
|
34
|
+
},
|
|
35
|
+
scales: {
|
|
36
|
+
type: 'array',
|
|
37
|
+
items: { type: 'number' },
|
|
38
|
+
description: 'Filter exportables by scale list, e.g. [1, 2]',
|
|
39
|
+
},
|
|
40
|
+
includeFullText: {
|
|
41
|
+
type: 'boolean',
|
|
42
|
+
default: false,
|
|
43
|
+
description: 'Set true only if your client cannot read structuredContent. Then content[0].text carries the full JSON instead of a short summary.',
|
|
44
|
+
},
|
|
45
|
+
}, ['sharingUrl', 'layerObjectId']);
|
|
46
|
+
export function registerSlicesTool(server) {
|
|
47
|
+
server.registerTool('download_slice', {
|
|
48
|
+
title: 'Download CoDesign Slice',
|
|
49
|
+
description: 'Downloads designer-exported CoDesign slice assets from the official slice manifest, matched by layer object_id. ' +
|
|
50
|
+
'Use this for implementation assets instead of using Python/PIL or screenshot cropping. ' +
|
|
51
|
+
'Returns local paths under <workspaceRoot>/.codesign-mcp/artifacts/<sharingId>/slices/. Optional filters: format and scales.',
|
|
52
|
+
inputSchema,
|
|
53
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
54
|
+
}, async (args) => {
|
|
55
|
+
const { sharingUrl, password, screenId, objectId, screenName, layerObjectId, format, scales, includeFullText } = args;
|
|
56
|
+
let sharingId;
|
|
57
|
+
try {
|
|
58
|
+
sharingId = parseSharingId(sharingUrl);
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
return errorResult(err);
|
|
62
|
+
}
|
|
63
|
+
const call = await browserManager.acquireHeadless();
|
|
64
|
+
try {
|
|
65
|
+
const { detail } = await getCachedSharingDetail(call.page, sharingId, password);
|
|
66
|
+
const allScreens = [];
|
|
67
|
+
for (const d of detail.designs ?? []) {
|
|
68
|
+
for (const s of d.screens ?? [])
|
|
69
|
+
allScreens.push(s);
|
|
70
|
+
}
|
|
71
|
+
if (allScreens.length === 0) {
|
|
72
|
+
return errorResult(new CodesignError('SHARING_NOT_FOUND', 'sharing has no screens', { sharingId }));
|
|
73
|
+
}
|
|
74
|
+
const selector = { screenId, objectId, screenName };
|
|
75
|
+
const picked = pickScreen(allScreens, selector);
|
|
76
|
+
if (!picked) {
|
|
77
|
+
if (selector.screenId == null && !selector.objectId && !selector.screenName) {
|
|
78
|
+
return errorResult(new CodesignError('SCREEN_SELECTOR_REQUIRED', 'multiple screens present; specify a selector', { available: summarizeScreens(allScreens) }));
|
|
79
|
+
}
|
|
80
|
+
return errorResult(new CodesignError('SCREEN_NOT_FOUND', 'no screen matches the given selector', {
|
|
81
|
+
selector,
|
|
82
|
+
available: summarizeScreens(allScreens),
|
|
83
|
+
}));
|
|
84
|
+
}
|
|
85
|
+
if (!picked.slices_url) {
|
|
86
|
+
return errorResult(new CodesignError('SLICE_NOT_FOUND', 'screen has no slices_url', {
|
|
87
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
const manifest = await fetchCachedSliceManifest(picked.slices_url);
|
|
91
|
+
const slice = findSliceByObjectId(manifest, layerObjectId);
|
|
92
|
+
if (!slice) {
|
|
93
|
+
return errorResult(new CodesignError('SLICE_NOT_FOUND', 'no slice matches layerObjectId', {
|
|
94
|
+
layerObjectId,
|
|
95
|
+
availableObjectIds: manifest.map((m) => m.object_id),
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
const filteredExportables = slice.exportables.filter((e) => acceptExportable(e, { format, scales }));
|
|
99
|
+
if (filteredExportables.length === 0) {
|
|
100
|
+
return errorResult(new CodesignError('SLICE_NOT_FOUND', 'no exportable matches the filters', {
|
|
101
|
+
layerObjectId,
|
|
102
|
+
filters: { format, scales },
|
|
103
|
+
availableExports: slice.exportables.map((e) => ({
|
|
104
|
+
format: e.format,
|
|
105
|
+
scale: e.scale,
|
|
106
|
+
name: e.name,
|
|
107
|
+
})),
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
const integrity = integrityView(inspectManifest(manifest));
|
|
111
|
+
const downloads = [];
|
|
112
|
+
const skipped = [];
|
|
113
|
+
const usedFilenames = new Set();
|
|
114
|
+
for (const e of filteredExportables) {
|
|
115
|
+
const url = e.screenshot?.url;
|
|
116
|
+
if (!url) {
|
|
117
|
+
const reason = 'exportable has no screenshot.url';
|
|
118
|
+
log.warn({ exportable: e.name }, reason);
|
|
119
|
+
skipped.push({
|
|
120
|
+
name: e.name,
|
|
121
|
+
objectId: e.object_id,
|
|
122
|
+
format: e.format,
|
|
123
|
+
scale: e.scale,
|
|
124
|
+
reason,
|
|
125
|
+
});
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const downloadUrl = normalizeCodesignAssetUrl(url);
|
|
129
|
+
const ext = e.format ?? extFromMime(e.screenshot?.mime) ?? 'png';
|
|
130
|
+
const baseName = `${encodeFilenameComponent(slice.object_id)}-${e.scale ?? 1}x.${ext}`;
|
|
131
|
+
// 真实数据中 exportable.size 是倍率而非字节数,不能当作 expectedBytes。
|
|
132
|
+
const expectedBytes = declaredByteLength(e.screenshot?.length) ?? declaredByteLength(e.screenshot?.size);
|
|
133
|
+
const filename = usedFilenames.has(baseName)
|
|
134
|
+
? `${baseName.slice(0, -ext.length - 1)}-${urlHash(url)}.${ext}`
|
|
135
|
+
: baseName;
|
|
136
|
+
usedFilenames.add(filename);
|
|
137
|
+
const dl = await downloadToArtifact(downloadUrl, `${sharingId}/slices`, filename, 'SLICE_FETCH_FAILED', {
|
|
138
|
+
request: call.context.request,
|
|
139
|
+
headers: SLICE_DOWNLOAD_HEADERS,
|
|
140
|
+
expectedBytes,
|
|
141
|
+
expectedMime: e.screenshot?.mime,
|
|
142
|
+
expectedFormat: e.format,
|
|
143
|
+
});
|
|
144
|
+
downloads.push({
|
|
145
|
+
format: e.format,
|
|
146
|
+
scale: e.scale,
|
|
147
|
+
url,
|
|
148
|
+
downloadUrl: downloadUrl === url ? undefined : downloadUrl,
|
|
149
|
+
path: dl.path,
|
|
150
|
+
bytes: dl.bytes,
|
|
151
|
+
mime: dl.mime,
|
|
152
|
+
reusedExisting: dl.reusedExisting,
|
|
153
|
+
verified: dl.verified,
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
if (downloads.length === 0) {
|
|
157
|
+
return errorResult(new CodesignError('SLICE_FETCH_FAILED', 'matched exportables did not contain downloadable screenshot URLs', {
|
|
158
|
+
layerObjectId,
|
|
159
|
+
filters: { format, scales },
|
|
160
|
+
skipped,
|
|
161
|
+
integrity,
|
|
162
|
+
}));
|
|
163
|
+
}
|
|
164
|
+
const reused = downloads.filter((d) => d.reusedExisting).length;
|
|
165
|
+
return toolSuccess({
|
|
166
|
+
sharingId,
|
|
167
|
+
screen: { id: picked.id, objectId: picked.object_id, name: picked.name },
|
|
168
|
+
slice: {
|
|
169
|
+
name: slice.name,
|
|
170
|
+
objectId: slice.object_id,
|
|
171
|
+
rect: slice.rect,
|
|
172
|
+
},
|
|
173
|
+
requested: filteredExportables.length,
|
|
174
|
+
downloaded: downloads.length,
|
|
175
|
+
reused,
|
|
176
|
+
skipped,
|
|
177
|
+
integrity,
|
|
178
|
+
downloads,
|
|
179
|
+
}, includeFullText);
|
|
180
|
+
}
|
|
181
|
+
catch (err) {
|
|
182
|
+
log.warn({ err: errMsg(err), sharingId }, 'download_slice failed');
|
|
183
|
+
return errorResult(err);
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
await call.done();
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
export function declaredByteLength(value) {
|
|
191
|
+
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : undefined;
|
|
192
|
+
}
|
|
193
|
+
function urlHash(url) {
|
|
194
|
+
return createHash('sha256').update(url).digest('hex').slice(0, 8);
|
|
195
|
+
}
|
|
196
|
+
function acceptExportable(e, filters) {
|
|
197
|
+
if (filters.format) {
|
|
198
|
+
if (!e.format)
|
|
199
|
+
return false;
|
|
200
|
+
if (e.format.toLowerCase() !== filters.format.toLowerCase())
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
if (filters.scales && filters.scales.length > 0) {
|
|
204
|
+
if (e.scale == null)
|
|
205
|
+
return false;
|
|
206
|
+
if (!filters.scales.includes(e.scale))
|
|
207
|
+
return false;
|
|
208
|
+
}
|
|
209
|
+
return true;
|
|
210
|
+
}
|
|
211
|
+
function extFromMime(mime) {
|
|
212
|
+
if (!mime)
|
|
213
|
+
return undefined;
|
|
214
|
+
if (mime.includes('png'))
|
|
215
|
+
return 'png';
|
|
216
|
+
if (mime.includes('jpeg') || mime.includes('jpg'))
|
|
217
|
+
return 'jpg';
|
|
218
|
+
if (mime.includes('webp'))
|
|
219
|
+
return 'webp';
|
|
220
|
+
if (mime.includes('svg'))
|
|
221
|
+
return 'svg';
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
function errMsg(err) {
|
|
225
|
+
if (err instanceof Error)
|
|
226
|
+
return err.message;
|
|
227
|
+
return String(err);
|
|
228
|
+
}
|