@base-screen/mcp-server 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 zhouan190
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,53 @@
1
- # Temporary Holding Version
1
+ # @base-screen/mcp-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An optional stdio MCP server for working with a local Screen Document. It exposes Base Screen's public document, core, and host-kit APIs to an agent without connecting to a running application or saving changes to the host project.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install --save-dev @base-screen/mcp-server
9
+ ```
10
+
11
+ The package also installs `base-screen`, the MCP SDK, and Zod. Node.js 22.20 or newer is required.
12
+
13
+ ## Configure an MCP client
14
+
15
+ Point the server at a Screen Document JSON file in the consuming project. For MCP clients that read a project `.mcp.json`, use:
16
+
17
+ ```json
18
+ {
19
+ "mcpServers": {
20
+ "base-screen": {
21
+ "command": "npx",
22
+ "args": [
23
+ "--no-install",
24
+ "@base-screen/mcp-server",
25
+ "--screen",
26
+ ".base-screen/screen.json"
27
+ ]
28
+ }
29
+ }
30
+ }
31
+ ```
32
+
33
+ The `--screen` path is resolved from the client's working directory. When omitted, the server reads `.base-screen/screen.json` from that directory. The file must contain a Screen Document, not a project envelope.
34
+
35
+ ## Available capabilities
36
+
37
+ The server provides 17 tools and three JSON resources. Tools cover document reading, validation, command-based candidate generation, diffs, layout and accessibility audits, resolution fitting, intent compilation, dataset profiling, candidate enumeration, blueprint simulation, layout solving, and canonical import/export.
38
+
39
+ The server never queries host datasets or project APIs. Dataset samples, material catalogs, references, and granted Blueprint capabilities must be supplied by the caller. `apply_screen_commands` returns a candidate document, and `export_screen` returns canonical JSON. The host application decides whether and how to persist that result.
40
+
41
+ For live application access, authentication, or project persistence, connect the MCP server to the host's own authorized project and data adapters. This package provides the document-level operations.
42
+
43
+ ## Local development
44
+
45
+ From the Base Screen repository, run:
46
+
47
+ ```bash
48
+ pnpm install --frozen-lockfile
49
+ pnpm build
50
+ pnpm --filter @base-screen/mcp-server test
51
+ ```
52
+
53
+ The smoke test starts a real stdio MCP client and checks the resource and tool surface, document operations, intent compilation, data profiling, and Blueprint simulation.
package/apis.mjs ADDED
@@ -0,0 +1,51 @@
1
+ import * as contracts from 'base-screen/contracts';
2
+ import * as core from 'base-screen/core';
3
+ import * as hostKit from 'base-screen/host-kit';
4
+
5
+ const CONTRACTS_EXPORTS = [
6
+ 'diagnoseDataSourceCycles',
7
+ 'migrateScreenDocument',
8
+ 'parseScreenDocument',
9
+ 'SCREEN_DOCUMENT_JSON_SCHEMA',
10
+ 'serializeScreenDocument',
11
+ 'sortScreenDiagnostics',
12
+ 'screenJsonEquals',
13
+ ];
14
+
15
+ const CORE_EXPORTS = [
16
+ 'applyScreenDocumentTransaction',
17
+ 'buildComponentIndex',
18
+ 'calculateScreenAlignment',
19
+ 'calculateScreenDistribution',
20
+ 'getAncestorIds',
21
+ 'getScreenComponentBounds',
22
+ 'validateScreenDocumentSemantics',
23
+ 'parseCssColor',
24
+ 'contrastRatio',
25
+ 'minimumContrastRatio',
26
+ 'suggestReadableColor',
27
+ 'formatCssColor',
28
+ 'diffScreenDocuments',
29
+ 'auditScreenLayout',
30
+ 'resolveScreenFontFloorPx',
31
+ // 从数据出发:字段画像与候选枚举,纯函数。
32
+ 'profileScreenDataset',
33
+ 'enumerateScreenDataCandidates',
34
+ // 行为:蓝图级联模拟与设计器工作台、智能体采纳前校验同一份实现。
35
+ 'simulateScreenBlueprint',
36
+ ];
37
+
38
+ /** 意图层:编译与布局求解与设计器宿主前端同一份实现。 */
39
+ const HOST_KIT_EXPORTS = ['mapDocumentIssues', 'prepareIntent', 'repairKey', 'solveLayout'];
40
+
41
+ export async function loadScreenApis() {
42
+ assertExports(contracts, CONTRACTS_EXPORTS, '@base-screen/contracts');
43
+ assertExports(core, CORE_EXPORTS, '@base-screen/core');
44
+ assertExports(hostKit, HOST_KIT_EXPORTS, '@base-screen/host-kit');
45
+ return { ...contracts, ...core, intent: hostKit };
46
+ }
47
+
48
+ function assertExports(module, names, specifier) {
49
+ const missing = names.filter((name) => module[name] === undefined);
50
+ if (missing.length > 0) throw new Error(`Missing ${specifier} exports: ${missing.join(', ')}`);
51
+ }
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@base-screen/mcp-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "MCP tools for validating and preparing Base Screen document changes",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public",
8
+ "registry": "https://registry.npmjs.org/"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/translateServers/base-screen.git",
13
+ "directory": "tooling/screen-mcp-server"
14
+ },
15
+ "homepage": "https://github.com/translateServers/base-screen/tree/master/tooling/screen-mcp-server",
16
+ "bugs": "https://github.com/translateServers/base-screen/issues",
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=22.20.0"
20
+ },
21
+ "files": [
22
+ "apis.mjs",
23
+ "provider.mjs",
24
+ "server.mjs",
25
+ "README.md"
26
+ ],
27
+ "bin": {
28
+ "base-screen-mcp": "./server.mjs"
29
+ },
30
+ "dependencies": {
31
+ "@modelcontextprotocol/sdk": "^1.30.0",
32
+ "zod": "^4.4.3",
33
+ "base-screen": "^0.4.2"
34
+ },
35
+ "scripts": {
36
+ "lint": "biome check apis.mjs provider.mjs server.mjs",
37
+ "test": "node smoke.mjs"
38
+ }
6
39
  }
package/provider.mjs ADDED
@@ -0,0 +1,807 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { resolve } from 'node:path';
4
+ import { loadScreenApis } from './apis.mjs';
5
+ import {
6
+ collectDocumentDiagnostics,
7
+ formatDiagnostic,
8
+ normalizeScreenDocument,
9
+ } from './document.mjs';
10
+
11
+ const CANVAS_DIFF_FIELDS = [
12
+ 'width',
13
+ 'height',
14
+ 'backgroundColor',
15
+ 'background',
16
+ 'backgroundImage',
17
+ 'backgroundImageFit',
18
+ ];
19
+
20
+ const COMPONENT_DIFF_FIELDS = [
21
+ 'type',
22
+ 'name',
23
+ 'parentId',
24
+ 'position',
25
+ 'size',
26
+ 'rotation',
27
+ 'zIndex',
28
+ 'status',
29
+ 'props',
30
+ 'style',
31
+ 'states',
32
+ 'dataSource',
33
+ 'dataValue',
34
+ 'dataBinding',
35
+ ];
36
+
37
+ /** Constrained layout intents reuse the designer's alignment/distribution math verbatim. */
38
+ const LAYOUT_OPERATIONS = {
39
+ 'align-left': { kind: 'align', axis: 'x', mode: 'start' },
40
+ 'align-h-center': { kind: 'align', axis: 'x', mode: 'center' },
41
+ 'align-right': { kind: 'align', axis: 'x', mode: 'end' },
42
+ 'align-top': { kind: 'align', axis: 'y', mode: 'start' },
43
+ 'align-v-center': { kind: 'align', axis: 'y', mode: 'center' },
44
+ 'align-bottom': { kind: 'align', axis: 'y', mode: 'end' },
45
+ 'distribute-horizontal': { kind: 'distribute', axis: 'x' },
46
+ 'distribute-vertical': { kind: 'distribute', axis: 'y' },
47
+ };
48
+
49
+ export async function createScreenProvider(screenFile) {
50
+ const file = resolve(screenFile);
51
+ const apis = await loadScreenApis();
52
+ let input;
53
+ try {
54
+ input = JSON.parse(await readFile(file, 'utf8'));
55
+ } catch (error) {
56
+ throw new Error(
57
+ `Screen document could not be read: ${error instanceof Error ? error.message : String(error)}`,
58
+ );
59
+ }
60
+ const loaded = normalizeScreenDocument(apis, input);
61
+ if (!loaded.ok)
62
+ throw new Error(
63
+ `Screen document is invalid: ${loaded.diagnostics.map(formatDiagnostic).join(', ')}`,
64
+ );
65
+ const document = loaded.document;
66
+ const source = Object.freeze({
67
+ file,
68
+ migrated: loaded.migrated,
69
+ migrationDecisions: loaded.decisions,
70
+ });
71
+
72
+ return Object.freeze({
73
+ source,
74
+ getScreen({ view = 'summary' } = {}) {
75
+ return ok({
76
+ source,
77
+ data: view === 'full' ? document : summarizeScreenDocument(apis, document),
78
+ });
79
+ },
80
+ /**
81
+ * 对比度校验:输入是**渲染采样**(文本色、有效背景、字号、字重),不是声明样式。
82
+ * 复用 core 的 WCAG 纯函数,判定与设计器内的守卫同源。
83
+ */
84
+ checkA11y({ samples, minRatio } = {}) {
85
+ const issues = [];
86
+ for (const sample of samples) {
87
+ const componentId =
88
+ typeof sample?.componentId === 'string' ? sample.componentId : 'unknown';
89
+ const text = apis.parseCssColor(String(sample?.textColor ?? ''));
90
+ const background = apis.parseCssColor(String(sample?.backgroundColor ?? ''));
91
+ if (text === undefined || background === undefined) {
92
+ issues.push({
93
+ componentId,
94
+ code: 'A11Y_COLOR_UNPARSEABLE',
95
+ message: 'textColor and backgroundColor must be opaque hex or rgb colors.',
96
+ });
97
+ continue;
98
+ }
99
+ const fontSizePx = Number(sample?.fontSizePx ?? 16);
100
+ const fontWeight = Number(sample?.fontWeight ?? 400);
101
+ const requiredRatio =
102
+ typeof minRatio === 'number' && minRatio > 0
103
+ ? minRatio
104
+ : apis.minimumContrastRatio(fontSizePx, fontWeight);
105
+ const ratio = apis.contrastRatio(text, background);
106
+ if (ratio >= requiredRatio) continue;
107
+ const suggested = apis.suggestReadableColor(text, background, requiredRatio);
108
+ issues.push({
109
+ componentId,
110
+ ratio: Math.round(ratio * 100) / 100,
111
+ requiredRatio,
112
+ textColor: apis.formatCssColor(text),
113
+ backgroundColor: apis.formatCssColor(background),
114
+ suggestedColor:
115
+ suggested === null || suggested === undefined ? null : apis.formatCssColor(suggested),
116
+ });
117
+ }
118
+ return ok({
119
+ checked: samples.length,
120
+ failed: issues.length,
121
+ issues,
122
+ });
123
+ },
124
+ getScreenSchema() {
125
+ return ok(apis.SCREEN_DOCUMENT_JSON_SCHEMA);
126
+ },
127
+ validateScreen({ document: candidate } = {}) {
128
+ const target =
129
+ candidate === undefined
130
+ ? snapshotTarget(document)
131
+ : normalizeScreenDocument(apis, candidate);
132
+ if (!target.ok)
133
+ return failure({ valid: false, migrated: false, diagnostics: target.diagnostics });
134
+ const diagnostics = collectDocumentDiagnostics(apis, target.document);
135
+ return ok({
136
+ valid: diagnostics.length === 0,
137
+ migrated: target.migrated,
138
+ migrationDecisions: target.decisions,
139
+ diagnostics,
140
+ });
141
+ },
142
+ applyScreenCommands({ commands }) {
143
+ // Commands are applied to the immutable snapshot only: the candidate document is returned,
144
+ // never persisted. Persisting stays with the host that owns the document.
145
+ const result = apis.applyScreenDocumentTransaction(document, { commands });
146
+ if (!result.ok)
147
+ return failure({
148
+ applied: false,
149
+ changedComponentIds: [],
150
+ failedCommandIndex: result.failedCommandIndex,
151
+ diagnostics: result.diagnostics,
152
+ });
153
+ return ok({
154
+ applied: true,
155
+ document: result.document,
156
+ changedComponentIds: result.changedComponentIds,
157
+ diagnostics: result.diagnostics,
158
+ });
159
+ },
160
+ diffScreens({ before: base, after }) {
161
+ const beforeTarget =
162
+ base === undefined ? snapshotTarget(document) : normalizeScreenDocument(apis, base);
163
+ const afterTarget = normalizeScreenDocument(apis, after);
164
+ if (!beforeTarget.ok || !afterTarget.ok)
165
+ return failure({
166
+ equal: false,
167
+ diagnostics: apis.sortScreenDiagnostics([
168
+ ...(beforeTarget.ok ? [] : beforeTarget.diagnostics),
169
+ ...(afterTarget.ok ? [] : afterTarget.diagnostics),
170
+ ]),
171
+ });
172
+ const changes = diffScreenDocuments(apis, beforeTarget.document, afterTarget.document);
173
+ return ok({
174
+ equal: screenChangesEqual(changes),
175
+ migrated: { before: beforeTarget.migrated, after: afterTarget.migrated },
176
+ changes,
177
+ diagnostics: [],
178
+ });
179
+ },
180
+ proposeLayout({ document: candidate, componentIds, operation }) {
181
+ const target =
182
+ candidate === undefined
183
+ ? snapshotTarget(document)
184
+ : normalizeScreenDocument(apis, candidate);
185
+ if (!target.ok) return failure({ proposed: false, diagnostics: target.diagnostics });
186
+ const source = target.document;
187
+ const intent = LAYOUT_OPERATIONS[operation];
188
+ if (intent === undefined)
189
+ return failure({
190
+ proposed: false,
191
+ reason: `unsupported-operation: ${String(operation)}`,
192
+ diagnostics: [],
193
+ });
194
+ const byId = new Map(source.components.map((component) => [component.id, component]));
195
+ const missing = componentIds.filter((id) => !byId.has(id));
196
+ if (missing.length > 0)
197
+ return failure({
198
+ proposed: false,
199
+ reason: 'component-not-found',
200
+ missing,
201
+ diagnostics: [],
202
+ });
203
+ const components = componentIds.map((id) => byId.get(id));
204
+ const deltas =
205
+ intent.kind === 'align'
206
+ ? apis.calculateScreenAlignment(components, intent.axis, intent.mode)
207
+ : apis.calculateScreenDistribution(components, intent.axis);
208
+ if (deltas.length === 0)
209
+ return ok({
210
+ proposed: false,
211
+ reason: 'no-change',
212
+ commands: [],
213
+ changedComponentIds: [],
214
+ diagnostics: [],
215
+ });
216
+ const commands = deltas.map(({ componentId, delta }) => {
217
+ const component = byId.get(componentId);
218
+ return {
219
+ type: 'update-components',
220
+ componentIds: [componentId],
221
+ patch: {
222
+ position: { x: component.position.x + delta.x, y: component.position.y + delta.y },
223
+ },
224
+ };
225
+ });
226
+ const applied = apis.applyScreenDocumentTransaction(source, { commands });
227
+ if (!applied.ok)
228
+ return failure({ proposed: false, commands, diagnostics: applied.diagnostics });
229
+ return ok({
230
+ proposed: true,
231
+ operation,
232
+ commands,
233
+ document: applied.document,
234
+ changedComponentIds: applied.changedComponentIds,
235
+ geometry: auditGeometry(apis, applied.document),
236
+ diagnostics: applied.diagnostics,
237
+ });
238
+ },
239
+ auditScreen({ document: candidate, target, minComponentPx } = {}) {
240
+ const audited =
241
+ candidate === undefined
242
+ ? snapshotTarget(document)
243
+ : normalizeScreenDocument(apis, candidate);
244
+ if (!audited.ok)
245
+ return failure({
246
+ valid: false,
247
+ diagnostics: audited.diagnostics,
248
+ geometry: null,
249
+ fit: null,
250
+ complexity: null,
251
+ });
252
+ const diagnostics = collectDocumentDiagnostics(apis, audited.document);
253
+ return ok({
254
+ valid: diagnostics.length === 0,
255
+ diagnostics,
256
+ geometry: auditGeometry(apis, audited.document),
257
+ fit: target === undefined ? null : auditFit(audited.document, target, minComponentPx),
258
+ complexity: auditComplexity(apis, audited.document),
259
+ });
260
+ },
261
+ /**
262
+ * 复杂度预算:只做计数与阈值比较,不声称是渲染耗时。
263
+ * 阈值可被调用方覆盖,默认值集中在这里,避免散落在文档里。
264
+ */
265
+ estimatePerf({ document: candidate, budget } = {}) {
266
+ const target =
267
+ candidate === undefined
268
+ ? snapshotTarget(document)
269
+ : normalizeScreenDocument(apis, candidate);
270
+ if (!target.ok)
271
+ return failure({
272
+ valid: false,
273
+ diagnostics: target.diagnostics,
274
+ metrics: null,
275
+ budget: null,
276
+ });
277
+ const doc = target.document;
278
+ const index = apis.buildComponentIndex(doc);
279
+ let maxDepth = 0;
280
+ let bindings = 0;
281
+ let componentStates = 0;
282
+ for (const component of doc.components) {
283
+ maxDepth = Math.max(maxDepth, apis.getAncestorIds(index, component.id).length);
284
+ if (component.dataSource !== null && component.dataSource !== undefined) bindings += 1;
285
+ componentStates += component.states?.items.length ?? 0;
286
+ }
287
+ const limits = {
288
+ maxComponents: 160,
289
+ maxDepth: 6,
290
+ maxBindings: 120,
291
+ maxComponentStates: 400,
292
+ ...(budget ?? {}),
293
+ };
294
+ const metrics = {
295
+ components: doc.components.length,
296
+ maxDepth,
297
+ dataBindings: bindings,
298
+ componentStates,
299
+ blueprintNodes: doc.blueprint.nodes.length,
300
+ blueprintEdges: doc.blueprint.edges.length,
301
+ };
302
+ const violations = [];
303
+ if (metrics.components > limits.maxComponents)
304
+ violations.push({
305
+ code: 'PERF_COMPONENTS',
306
+ actual: metrics.components,
307
+ limit: limits.maxComponents,
308
+ });
309
+ if (metrics.maxDepth > limits.maxDepth)
310
+ violations.push({ code: 'PERF_DEPTH', actual: metrics.maxDepth, limit: limits.maxDepth });
311
+ if (metrics.dataBindings > limits.maxBindings)
312
+ violations.push({
313
+ code: 'PERF_BINDINGS',
314
+ actual: metrics.dataBindings,
315
+ limit: limits.maxBindings,
316
+ });
317
+ if (metrics.componentStates > limits.maxComponentStates)
318
+ violations.push({
319
+ code: 'PERF_COMPONENT_STATES',
320
+ actual: metrics.componentStates,
321
+ limit: limits.maxComponentStates,
322
+ });
323
+ return ok({ valid: violations.length === 0, metrics, budget: { limits, violations } });
324
+ },
325
+ /**
326
+ * 分辨率适配:等比缩放 + 居中,画布与组件一起换算成命令。
327
+ * 返回的是命令而不是已改文档——调用方仍需走 apply_screen_commands 才生效。
328
+ */
329
+ fitResolution({ document: candidate, target, minComponentPx } = {}) {
330
+ const normalized =
331
+ candidate === undefined
332
+ ? snapshotTarget(document)
333
+ : normalizeScreenDocument(apis, candidate);
334
+ if (!normalized.ok)
335
+ return failure({ fit: null, commands: [], diagnostics: normalized.diagnostics });
336
+ const doc = normalized.document;
337
+ const scale = Math.min(target.width / doc.canvas.width, target.height / doc.canvas.height);
338
+ const dx = (target.width - doc.canvas.width * scale) / 2;
339
+ const dy = (target.height - doc.canvas.height * scale) / 2;
340
+ const commands = [
341
+ { type: 'update-canvas', patch: { width: target.width, height: target.height } },
342
+ ];
343
+ const below = [];
344
+ for (const component of doc.components) {
345
+ const width = Math.max(1, Math.round(component.size.width * scale));
346
+ const height = Math.max(1, Math.round(component.size.height * scale));
347
+ commands.push({
348
+ type: 'update-components',
349
+ componentIds: [component.id],
350
+ patch: {
351
+ position: {
352
+ x: Math.round(component.position.x * scale + dx),
353
+ y: Math.round(component.position.y * scale + dy),
354
+ },
355
+ size: { width, height },
356
+ },
357
+ });
358
+ if (minComponentPx !== undefined && (width < minComponentPx || height < minComponentPx))
359
+ below.push({ id: component.id, effective: { width, height } });
360
+ }
361
+ return ok({
362
+ fit: { scale: round2(scale), offset: { x: round2(dx), y: round2(dy) }, below },
363
+ commands,
364
+ });
365
+ },
366
+ /**
367
+ * 与基线快照做属性级 diff:回答「这份候选到底改了哪些字段」。
368
+ * 与设计器内的变更卡共用 core 的同一份 diff 实现。
369
+ */
370
+ diffAgainstBaseline({ baseline, document: candidate } = {}) {
371
+ const before = normalizeScreenDocument(apis, baseline);
372
+ if (!before.ok) return failure({ equal: null, rows: [], diagnostics: before.diagnostics });
373
+ const after =
374
+ candidate === undefined
375
+ ? snapshotTarget(document)
376
+ : normalizeScreenDocument(apis, candidate);
377
+ if (!after.ok) return failure({ equal: null, rows: [], diagnostics: after.diagnostics });
378
+ const rows = apis.diffScreenDocuments(before.document, after.document);
379
+ return ok({
380
+ equal: rows.length === 0,
381
+ rows,
382
+ changedComponentIds: rows.map((row) => row.componentId),
383
+ });
384
+ },
385
+ exportScreen({ document: candidate } = {}) {
386
+ const target =
387
+ candidate === undefined
388
+ ? snapshotTarget(document)
389
+ : normalizeScreenDocument(apis, candidate);
390
+ if (!target.ok) return failure({ diagnostics: target.diagnostics });
391
+ const text = apis.serializeScreenDocument(target.document);
392
+ return ok({ text, bytes: Buffer.byteLength(text, 'utf8') });
393
+ },
394
+ /**
395
+ * 意图层编译:模型原文或已解析的意图 + 目录 → 文档候选与按模型路径整理的诊断。
396
+ * 与设计器宿主前端的 `prepareIntent` 是同一份实现;不读也不改已加载的快照。
397
+ */
398
+ compileScreenIntent({ intent, catalog, references, mode = 'llm', capabilities }) {
399
+ const prepared = apis.intent.prepareIntent({
400
+ output: typeof intent === 'string' ? intent : JSON.stringify(intent),
401
+ catalog: { materials: catalog.materials, assets: catalog.assets ?? [] },
402
+ ...(references === undefined ? {} : { references }),
403
+ mode,
404
+ ...(capabilities === undefined ? {} : { capabilities }),
405
+ });
406
+ const warnings = prepared.warnings;
407
+ if (prepared.compiled === undefined) {
408
+ return failure({
409
+ compiled: false,
410
+ issues: prepared.issues,
411
+ warnings,
412
+ diagnostics: prepared.issues.map((issue) => ({
413
+ severity: 'error',
414
+ code: issue.code,
415
+ path: issue.path,
416
+ message: `The intent could not be compiled at ${issue.path === '' ? 'the whole output' : issue.path}.`,
417
+ })),
418
+ });
419
+ }
420
+ const normalized = normalizeScreenDocument(apis, prepared.compiled.document);
421
+ if (!normalized.ok) {
422
+ return failure({
423
+ compiled: false,
424
+ issues: prepared.issues,
425
+ warnings,
426
+ diagnostics: normalized.diagnostics,
427
+ });
428
+ }
429
+ const audit = apis
430
+ .auditScreenLayout(normalized.document)
431
+ .filter((issue) => issue.severity === 'error');
432
+ const auditIssues = apis.intent.mapDocumentIssues(
433
+ audit,
434
+ normalized.document.components.map((component) => component.id),
435
+ prepared.compiled.sources,
436
+ );
437
+ return ok({
438
+ compiled: true,
439
+ document: normalized.document,
440
+ sources: prepared.compiled.sources,
441
+ materials: prepared.compiled.materials,
442
+ behaviors: prepared.compiled.behaviors,
443
+ issues: [...prepared.issues, ...auditIssues],
444
+ warnings,
445
+ deliverable: prepared.deliverable && audit.length === 0,
446
+ audit,
447
+ });
448
+ },
449
+ /**
450
+ * 字段画像:describe 结果 + 调用方给的样本 → 确定性画像。
451
+ * MCP 服务不取数——谁接触数据由宿主决定(上位),样本由调用方传入。
452
+ */
453
+ profileDataset({ definition, sample }) {
454
+ return ok({ profile: apis.profileScreenDataset(definition, sample) });
455
+ },
456
+ /** 候选枚举:画像 × 物料绑定角色 → 合法的(事实, 物料, 角色绑定)。 */
457
+ enumerateDataCandidates({ profiles, materials, maxPerDataset }) {
458
+ return ok({
459
+ candidates: apis.enumerateScreenDataCandidates(
460
+ profiles,
461
+ materials,
462
+ maxPerDataset === undefined ? {} : { maxPerDataset },
463
+ ),
464
+ });
465
+ },
466
+ /**
467
+ * 蓝图级联模拟:与设计器工作台、智能体采纳前校验同一份实现(core
468
+ * `simulateScreenBlueprint`)。只登记请求、不取数;不读写已加载快照之外的任何东西。
469
+ */
470
+ simulateBlueprint({ document: candidate, event, capabilities } = {}) {
471
+ const target =
472
+ candidate === undefined
473
+ ? snapshotTarget(document)
474
+ : normalizeScreenDocument(apis, candidate);
475
+ if (!target.ok) return failure({ simulated: false, diagnostics: target.diagnostics });
476
+ const { type = 'material-event', ...rest } = event;
477
+ const runtimeEvent = type === 'material-event' ? rest : { type, ...rest };
478
+ const granted = capabilities === undefined ? undefined : new Set(capabilities);
479
+ const result = apis.simulateScreenBlueprint(target.document, runtimeEvent, {
480
+ ...(granted === undefined
481
+ ? {}
482
+ : { capabilities: { hasBlueprintCapability: (id) => granted.has(id) } }),
483
+ });
484
+ if (!result.ok) return failure({ simulated: false, diagnostics: result.diagnostics });
485
+ const simulation = result.value;
486
+ const summary = {
487
+ simulated: true,
488
+ dispatches: simulation.dispatches.map((dispatch) => ({
489
+ depth: dispatch.depth,
490
+ event: dispatch.event,
491
+ rules: dispatch.ruleTraces
492
+ .filter((trace) => trace.triggerMatched)
493
+ .map((trace) => ({
494
+ ruleId: trace.ruleId,
495
+ conditions: trace.conditions,
496
+ actions: trace.actions.map((action) => ({
497
+ type: action.type,
498
+ edgeId: action.edgeId,
499
+ output: action.output,
500
+ })),
501
+ })),
502
+ })),
503
+ variables: simulation.variables,
504
+ changedVariableIds: simulation.changedVariableIds,
505
+ visibility: simulation.visibility,
506
+ dataSourceChanges: simulation.dataSourceChanges,
507
+ openPopupIds: simulation.openPopupIds,
508
+ currentPageId: simulation.currentPageId,
509
+ variableRequests: simulation.variableRequests,
510
+ componentDataRequests: simulation.componentDataRequests,
511
+ };
512
+ if (simulation.failure === undefined) return ok(summary);
513
+ return failure({
514
+ ...summary,
515
+ failure: simulation.failure,
516
+ diagnostics: [
517
+ {
518
+ severity: 'error',
519
+ code:
520
+ simulation.failure.kind === 'depth-exceeded'
521
+ ? 'BLUEPRINT_SIMULATION_DEPTH_EXCEEDED'
522
+ : 'BLUEPRINT_SIMULATION_FAILED',
523
+ path: [],
524
+ message: simulation.failure.message,
525
+ },
526
+ ],
527
+ });
528
+ },
529
+ /** 布局求解:区域序列 + 每格内容量 → 像素矩形,装不下返回带差额的容量冲突。 */
530
+ solveLayout({ regions }) {
531
+ const invalid = regions.flatMap((region, index) => validateLayoutRegion(region, index));
532
+ if (invalid.length > 0) return failure({ solved: false, diagnostics: invalid });
533
+ const outcome = apis.intent.solveLayout(regions);
534
+ if (outcome.ok) return ok({ solved: true, regions: outcome.regions });
535
+ return failure({
536
+ solved: false,
537
+ issues: outcome.issues,
538
+ diagnostics: outcome.issues.map((issue) => ({
539
+ severity: 'error',
540
+ code: 'LAYOUT_CAPACITY_EXCEEDED',
541
+ path: `regions[${issue.regionIndex}]`,
542
+ message: `Needs ${issue.requiredPx}px but ${issue.availablePx}px is available (${issue.reason}).`,
543
+ })),
544
+ });
545
+ },
546
+ importScreen({ document: candidate }) {
547
+ const target = normalizeScreenDocument(apis, candidate);
548
+ if (!target.ok)
549
+ return failure({
550
+ migrated: false,
551
+ migrationDecisions: target.decisions,
552
+ diagnostics: target.diagnostics,
553
+ });
554
+ return ok({
555
+ document: target.document,
556
+ migrated: target.migrated,
557
+ migrationDecisions: target.decisions,
558
+ diagnostics: target.diagnostics,
559
+ });
560
+ },
561
+ });
562
+ }
563
+
564
+ /** 求解器入参的形状校验:宿主调用方给的是原始 JSON,进求解器之前先挡一道。 */
565
+ function validateLayoutRegion(region, index) {
566
+ const path = `regions[${index}]`;
567
+ const bad = (message) => [{ severity: 'error', code: 'INTENT_REGION_INVALID', path, message }];
568
+ if (typeof region !== 'object' || region === null) return bad('A region must be an object.');
569
+ const isCell = (cell) =>
570
+ typeof cell === 'object' && cell !== null && typeof cell.data === 'boolean';
571
+ if (region.kind === 'band') {
572
+ return Number.isInteger(region.count) && region.count >= 1 && region.count <= 8
573
+ ? []
574
+ : bad('A band needs an integer count from 1 to 8.');
575
+ }
576
+ if (region.kind === 'grid') {
577
+ return Array.isArray(region.slots) &&
578
+ region.slots.length >= 1 &&
579
+ region.slots.length <= 8 &&
580
+ region.slots.every((slot) => isCell(slot) && Number.isFinite(slot.span))
581
+ ? []
582
+ : bad('A grid needs 1 to 8 slots, each with a numeric span and a boolean data flag.');
583
+ }
584
+ if (region.kind === 'split') {
585
+ const stack = (cells) =>
586
+ Array.isArray(cells) && cells.length >= 1 && cells.length <= 8 && cells.every(isCell);
587
+ return stack(region.main) &&
588
+ stack(region.rail) &&
589
+ ['wide-narrow', 'even'].includes(region.ratio) &&
590
+ ['left', 'right'].includes(region.railSide)
591
+ ? []
592
+ : bad('A split needs ratio, railSide and 1 to 8 cells in both main and rail.');
593
+ }
594
+ return bad('A region kind must be band, grid or split.');
595
+ }
596
+
597
+ function snapshotTarget(document) {
598
+ return { ok: true, document, migrated: false, decisions: [], diagnostics: [] };
599
+ }
600
+
601
+ function diffScreenDocuments(apis, before, after) {
602
+ return {
603
+ canvas: diffFields(apis, before.canvas, after.canvas, CANVAS_DIFF_FIELDS),
604
+ components: diffComponents(apis, before.components, after.components),
605
+ dataSources: diffById(apis, before.dataSources ?? [], after.dataSources ?? []),
606
+ variables: diffById(apis, before.variables ?? [], after.variables ?? []),
607
+ blueprint: {
608
+ changed: !apis.screenJsonEquals(before.blueprint, after.blueprint),
609
+ beforeNodes: before.blueprint.nodes.length,
610
+ afterNodes: after.blueprint.nodes.length,
611
+ beforeEdges: before.blueprint.edges.length,
612
+ afterEdges: after.blueprint.edges.length,
613
+ },
614
+ };
615
+ }
616
+
617
+ function diffFields(apis, before, after, fields) {
618
+ if (apis.screenJsonEquals(before, after)) return null;
619
+ return {
620
+ changedFields: fields.filter(
621
+ (field) => !apis.screenJsonEquals(before?.[field], after?.[field]),
622
+ ),
623
+ };
624
+ }
625
+
626
+ function diffComponents(apis, before, after) {
627
+ const beforeById = new Map(before.map((component) => [component.id, component]));
628
+ const identity = diffById(apis, before, after);
629
+ const changed = [];
630
+ for (const component of after) {
631
+ const previous = beforeById.get(component.id);
632
+ if (previous === undefined || apis.screenJsonEquals(previous, component)) continue;
633
+ changed.push({
634
+ id: component.id,
635
+ fields: COMPONENT_DIFF_FIELDS.filter(
636
+ (field) => !apis.screenJsonEquals(previous[field], component[field]),
637
+ ),
638
+ });
639
+ }
640
+ return { added: identity.added, removed: identity.removed, changed };
641
+ }
642
+
643
+ function diffById(apis, before, after) {
644
+ const beforeById = new Map(before.map((entry) => [entry.id, entry]));
645
+ const afterById = new Map(after.map((entry) => [entry.id, entry]));
646
+ return {
647
+ added: after.filter((entry) => !beforeById.has(entry.id)).map((entry) => entry.id),
648
+ removed: before.filter((entry) => !afterById.has(entry.id)).map((entry) => entry.id),
649
+ changed: after
650
+ .filter((entry) => !apis.screenJsonEquals(beforeById.get(entry.id), entry))
651
+ .map((entry) => entry.id),
652
+ };
653
+ }
654
+
655
+ function screenChangesEqual(changes) {
656
+ return (
657
+ changes.canvas === null &&
658
+ changes.components.added.length === 0 &&
659
+ changes.components.removed.length === 0 &&
660
+ changes.components.changed.length === 0 &&
661
+ changes.dataSources.added.length === 0 &&
662
+ changes.dataSources.removed.length === 0 &&
663
+ changes.dataSources.changed.length === 0 &&
664
+ changes.variables.added.length === 0 &&
665
+ changes.variables.removed.length === 0 &&
666
+ changes.variables.changed.length === 0 &&
667
+ !changes.blueprint.changed
668
+ );
669
+ }
670
+
671
+ function auditGeometry(apis, document) {
672
+ const outsideCanvas = [];
673
+ for (const component of document.components) {
674
+ const bounds = apis.getScreenComponentBounds(component);
675
+ const overflow = {
676
+ left: round2(Math.max(0, -bounds.left)),
677
+ top: round2(Math.max(0, -bounds.top)),
678
+ right: round2(Math.max(0, bounds.right - document.canvas.width)),
679
+ bottom: round2(Math.max(0, bounds.bottom - document.canvas.height)),
680
+ };
681
+ if (overflow.left > 0 || overflow.top > 0 || overflow.right > 0 || overflow.bottom > 0)
682
+ outsideCanvas.push({ id: component.id, overflow });
683
+ }
684
+ return { outsideCanvas };
685
+ }
686
+
687
+ /**
688
+ * Uniform-scale projection only (`fit`/`fill`). A layout re-solve for a target screen needs a
689
+ * solver this snapshot-side check deliberately does not pretend to be; it answers "what would
690
+ * uniform scaling do to this canvas at the target size". `minComponentPx` is an optional policy:
691
+ * report components whose declared box would render below that many target pixels.
692
+ */
693
+ function auditFit(document, target, minComponentPx) {
694
+ const canvas = document.canvas;
695
+ const fitScale = Math.min(target.width / canvas.width, target.height / canvas.height);
696
+ const fillScale = Math.max(target.width / canvas.width, target.height / canvas.height);
697
+ const fitWidth = canvas.width * fitScale;
698
+ const fitHeight = canvas.height * fitScale;
699
+ const canvasAspect = canvas.width / canvas.height;
700
+ const targetAspect = target.width / target.height;
701
+ const report = {
702
+ target,
703
+ targetMegapixels: round2((target.width * target.height) / 1_000_000),
704
+ fitScale: round2(fitScale),
705
+ fillScale: round2(fillScale),
706
+ fitRendered: { width: round2(fitWidth), height: round2(fitHeight) },
707
+ letterbox: {
708
+ x: round2((target.width - fitWidth) / 2),
709
+ y: round2((target.height - fitHeight) / 2),
710
+ },
711
+ fillCropped: {
712
+ width: round2(canvas.width * fillScale - target.width),
713
+ height: round2(canvas.height * fillScale - target.height),
714
+ },
715
+ aspectDeltaPercent: round2(Math.abs(targetAspect / canvasAspect - 1) * 100),
716
+ };
717
+ if (minComponentPx === undefined) return report;
718
+ const below = [];
719
+ for (const component of document.components) {
720
+ const width = round2(component.size.width * fitScale);
721
+ const height = round2(component.size.height * fitScale);
722
+ if (width < minComponentPx || height < minComponentPx)
723
+ below.push({ id: component.id, effective: { width, height } });
724
+ }
725
+ return {
726
+ ...report,
727
+ minComponentPx,
728
+ belowMinComponentPx: { count: below.length, items: below.slice(0, 50) },
729
+ };
730
+ }
731
+
732
+ /** Counts only — inputs for an agent's judgment, not measured render cost. */
733
+ function auditComplexity(apis, document) {
734
+ const index = apis.buildComponentIndex(document);
735
+ const materialTypes = {};
736
+ let maxDepth = 0;
737
+ let componentStates = 0;
738
+ for (const component of document.components) {
739
+ materialTypes[component.type] = (materialTypes[component.type] ?? 0) + 1;
740
+ maxDepth = Math.max(maxDepth, apis.getAncestorIds(index, component.id).length);
741
+ componentStates += component.states?.items.length ?? 0;
742
+ }
743
+ const dataSources = document.dataSources ?? [];
744
+ const variables = document.variables ?? [];
745
+ return {
746
+ components: document.components.length,
747
+ canvasMegapixels: round2((document.canvas.width * document.canvas.height) / 1_000_000),
748
+ maxDepth,
749
+ materialTypes,
750
+ dataSources: dataSources.length,
751
+ variables: variables.length,
752
+ blueprintNodes: document.blueprint.nodes.length,
753
+ blueprintEdges: document.blueprint.edges.length,
754
+ componentStates,
755
+ };
756
+ }
757
+
758
+ function summarizeScreenDocument(apis, document) {
759
+ const index = apis.buildComponentIndex(document);
760
+ const dataSources = document.dataSources ?? [];
761
+ const variables = document.variables ?? [];
762
+ return {
763
+ canvas: document.canvas,
764
+ counts: {
765
+ components: document.components.length,
766
+ dataSources: dataSources.length,
767
+ variables: variables.length,
768
+ blueprintNodes: document.blueprint.nodes.length,
769
+ blueprintEdges: document.blueprint.edges.length,
770
+ },
771
+ components: document.components.map((component) => ({
772
+ id: component.id,
773
+ type: component.type,
774
+ name: component.name,
775
+ parentId: component.parentId,
776
+ depth: apis.getAncestorIds(index, component.id).length,
777
+ position: component.position,
778
+ size: component.size,
779
+ rotation: component.rotation,
780
+ zIndex: component.zIndex,
781
+ status: component.status,
782
+ hasDataSource: component.dataSource !== null && component.dataSource !== undefined,
783
+ hasStates: component.states !== undefined,
784
+ hasValue: component.dataValue !== null && component.dataValue !== undefined,
785
+ hasBinding: component.dataBinding !== null && component.dataBinding !== undefined,
786
+ })),
787
+ dataSources: dataSources.map((instance) => ({
788
+ id: instance.id,
789
+ name: instance.name,
790
+ sourceKind: instance.source.kind,
791
+ readOnly: instance.readOnly === true,
792
+ })),
793
+ variables: variables.map((variable) => ({ id: variable.id, name: variable.name })),
794
+ };
795
+ }
796
+
797
+ function round2(value) {
798
+ return Math.round(value * 100) / 100;
799
+ }
800
+
801
+ function ok(value) {
802
+ return { ok: true, value, diagnostics: [] };
803
+ }
804
+
805
+ function failure(value) {
806
+ return { ok: false, value, diagnostics: value.diagnostics ?? [] };
807
+ }
package/server.mjs ADDED
@@ -0,0 +1,399 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFile } from 'node:fs/promises';
4
+ import { resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
+ import * as z from 'zod/v4';
9
+ import { createScreenProvider } from './provider.mjs';
10
+
11
+ const SCREEN_VIEW = z.enum(['summary', 'full']);
12
+ const packageManifest = JSON.parse(
13
+ await readFile(new URL('./package.json', import.meta.url), 'utf8'),
14
+ );
15
+
16
+ export function createScreenMcpServer(provider) {
17
+ const server = new McpServer({
18
+ name: 'base-screen-mcp-server',
19
+ version: packageManifest.version,
20
+ });
21
+
22
+ registerJsonResource(server, 'screen-document', 'base-screen://screen/document', () =>
23
+ unwrap(provider.getScreen({ view: 'full' })),
24
+ );
25
+ registerJsonResource(server, 'screen-summary', 'base-screen://screen/summary', () =>
26
+ unwrap(provider.getScreen({ view: 'summary' })),
27
+ );
28
+ registerJsonResource(server, 'screen-schema', 'base-screen://screen/schema', () =>
29
+ unwrap(provider.getScreenSchema()),
30
+ );
31
+
32
+ registerTool(
33
+ server,
34
+ 'get_screen',
35
+ { view: SCREEN_VIEW.optional().default('summary') },
36
+ 'Read the loaded Screen Document snapshot. summary returns a derived index (canvas, component tree, data sources, variables, blueprint relation count); full returns the canonical document.',
37
+ (input) => provider.getScreen(input),
38
+ );
39
+ registerTool(
40
+ server,
41
+ 'validate_screen',
42
+ { document: z.unknown().optional() },
43
+ 'Validate a Screen Document against the fail-closed schema, core semantic invariants and data-source cycle rules. Omit document to validate the loaded snapshot; diagnostics use stable code/path fields.',
44
+ (input) => provider.validateScreen(input),
45
+ );
46
+ registerTool(
47
+ server,
48
+ 'check_a11y',
49
+ {
50
+ samples: z
51
+ .array(
52
+ z.object({
53
+ componentId: z.string().min(1).max(128).optional(),
54
+ textColor: z.string().min(1).max(64),
55
+ backgroundColor: z.string().min(1).max(64),
56
+ fontSizePx: z.number().positive().max(1000).optional(),
57
+ fontWeight: z.number().min(100).max(900).optional(),
58
+ }),
59
+ )
60
+ .min(1)
61
+ .max(2000),
62
+ minRatio: z.number().positive().max(21).optional(),
63
+ },
64
+ 'Check text contrast from rendered samples. Each sample carries the resolved text color, the effective background behind it, font size and weight; colors must be opaque hex or rgb. Returns per-component ratio, required ratio and a minimal suggested color. This is deterministic WCAG math, not a model judgement — text contrast cannot be checked from declared styles alone.',
65
+ (input) => provider.checkA11y(input),
66
+ );
67
+ registerTool(
68
+ server,
69
+ 'apply_screen_commands',
70
+ { commands: z.array(z.unknown()).min(1).max(1000) },
71
+ 'Validate and apply a batch of Screen Document commands to the loaded snapshot without persisting. Returns the candidate document plus changedComponentIds and diagnostics; on failure the batch is rejected at failedCommandIndex. Command types: update-canvas, add-component, update-components, remove-components, reparent-components, replace-blueprint, replace-data-sources, replace-variables, rename-variable.',
72
+ (input) => provider.applyScreenCommands(input),
73
+ );
74
+ registerTool(
75
+ server,
76
+ 'diff_screens',
77
+ { before: z.unknown().optional(), after: z.unknown() },
78
+ 'Structurally diff two Screen Documents by id. Omit before to diff against the loaded snapshot, which answers "what did this candidate change". Reports canvas fields, added/removed/changed components with changed field names, data sources, variables and blueprint node / edge counts. Both sides pass the same migration + schema read path.',
79
+ (input) => provider.diffScreens(input),
80
+ );
81
+ registerTool(
82
+ server,
83
+ 'propose_layout',
84
+ {
85
+ document: z.unknown().optional(),
86
+ componentIds: z.array(z.string().min(1).max(128)).min(2).max(200),
87
+ operation: z.enum([
88
+ 'align-left',
89
+ 'align-h-center',
90
+ 'align-right',
91
+ 'align-top',
92
+ 'align-v-center',
93
+ 'align-bottom',
94
+ 'distribute-horizontal',
95
+ 'distribute-vertical',
96
+ ]),
97
+ },
98
+ 'Propose a constrained layout candidate for two or more components, using the same alignment/distribution math as the designer: align their union to start/center/end on one axis, or distribute even gaps between them. Returns the command batch, the candidate document and a canvas-overflow re-audit. It does not invent a layout from scratch or re-solve for other screen sizes; persist the candidate yourself.',
99
+ (input) => provider.proposeLayout(input),
100
+ );
101
+ registerTool(
102
+ server,
103
+ 'audit_screen',
104
+ {
105
+ document: z.unknown().optional(),
106
+ target: z
107
+ .object({ width: z.number().positive(), height: z.number().positive() })
108
+ .strict()
109
+ .optional(),
110
+ minComponentPx: z.number().positive().optional(),
111
+ },
112
+ 'Audit a Screen Document without rendering: contract diagnostics plus geometry (components whose rotated bounds exceed the canvas) and, when target is given, uniform fit/fill projection (scale, letterbox, crop, aspect delta, target megapixels) with an optional minComponentPx policy listing components that would render below that many target pixels. Complexity counts (components, canvas megapixels, depth, material types, style rules) are proxies, not measured render cost. Text contrast needs rendered output: use the screen probe.',
113
+ (input) => provider.auditScreen(input),
114
+ );
115
+ registerTool(
116
+ server,
117
+ 'estimate_perf',
118
+ {
119
+ document: z.unknown().optional(),
120
+ budget: z
121
+ .object({
122
+ maxComponents: z.number().int().positive().optional(),
123
+ maxDepth: z.number().int().positive().optional(),
124
+ maxBindings: z.number().int().positive().optional(),
125
+ maxComponentStates: z.number().int().positive().optional(),
126
+ })
127
+ .optional(),
128
+ },
129
+ 'Count structural cost (components, nesting depth, data bindings, style rules) and compare it with a budget. Thresholds have defaults and can be overridden per call. These are counts, not measured render time — use the screen probe for real timing.',
130
+ (input) => provider.estimatePerf(input),
131
+ );
132
+ registerTool(
133
+ server,
134
+ 'fit_resolution',
135
+ {
136
+ document: z.unknown().optional(),
137
+ target: z.object({
138
+ width: z.number().int().positive().max(20000),
139
+ height: z.number().int().positive().max(20000),
140
+ }),
141
+ minComponentPx: z.number().positive().optional(),
142
+ },
143
+ 'Compute a proportional fit to a target resolution and return the commands that apply it: canvas resize plus integer-rounded component positions and sizes, centred with letterbox offset. The snapshot is not modified — pass the commands to apply_screen_commands. Optionally lists components that fall below minComponentPx after scaling.',
144
+ (input) => provider.fitResolution(input),
145
+ );
146
+ registerTool(
147
+ server,
148
+ 'diff_against_baseline',
149
+ {
150
+ baseline: z.unknown(),
151
+ document: z.unknown().optional(),
152
+ },
153
+ 'Attribute-level diff between a baseline snapshot and a candidate. Answers "what exactly changed" with per-component rows: added/removed, or changed fields with before/after values. Uses the same diff implementation as the designer change cards. Omit document to compare the loaded snapshot against the baseline.',
154
+ (input) => provider.diffAgainstBaseline(input),
155
+ );
156
+ registerTool(
157
+ server,
158
+ 'compile_screen_intent',
159
+ {
160
+ intent: z.unknown(),
161
+ catalog: z
162
+ .object({
163
+ materials: z.array(z.unknown()).min(1).max(200),
164
+ assets: z.array(z.object({ id: z.string().min(1), name: z.string() })).optional(),
165
+ })
166
+ .strict(),
167
+ references: z
168
+ .object({
169
+ assets: z.array(z.object({ id: z.string().min(1), name: z.string() })),
170
+ datasets: z.array(
171
+ z.object({
172
+ datasetId: z.string().min(1),
173
+ name: z.string(),
174
+ columns: z.array(
175
+ z.object({
176
+ id: z.string().min(1),
177
+ type: z.string(),
178
+ label: z.string().optional(),
179
+ unit: z.string().optional(),
180
+ }),
181
+ ),
182
+ // 参数定义与画像行数,编译器据此写默认参数、判缺参、拒绝多行结果绑指标卡。
183
+ parameters: z
184
+ .array(
185
+ z.object({
186
+ name: z.string().min(1),
187
+ required: z.boolean(),
188
+ valueType: z.enum(['string', 'number', 'boolean', 'date']).optional(),
189
+ defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
190
+ allowedValues: z
191
+ .array(z.union([z.string(), z.number(), z.boolean()]))
192
+ .optional(),
193
+ }),
194
+ )
195
+ .optional(),
196
+ rows: z
197
+ .object({
198
+ sampled: z.number().int().min(0),
199
+ total: z.number().int().min(0).optional(),
200
+ })
201
+ .optional(),
202
+ // 样本里各字段出现过的取值,联动采纳前模拟用。
203
+ values: z
204
+ .record(z.string(), z.array(z.union([z.string(), z.number(), z.boolean()])).max(24))
205
+ .optional(),
206
+ }),
207
+ ),
208
+ })
209
+ .optional(),
210
+ mode: z.enum(['llm', 'deterministic']).optional().default('llm'),
211
+ // 已授权的蓝图能力;给了就跳过缺能力的联动并记 AGENT_INTERACTION_CAPABILITY_MISSING。
212
+ capabilities: z.array(z.string().min(1)).max(64).optional(),
213
+ },
214
+ 'Compile an agent intent (the model output: title, subtitle, style, and either regions of band / grid / split or the flat kpis + blocks shape) into a Screen Document candidate, with the same parser, compiler and layout solver the designer host runs. Needs the material catalog (type, data kind, props, binding roles, defaults, and children for shell containers). The intent may also carry behaviors: a key on blocks / KPI cards, interactions (filter: a source event value written into a target dataset parameter; show: show / hide / toggle a target block), threshold states on dataset-bound KPI cards, and gaps for requests that cannot be met. Variables and blueprint wiring are derived by the compiler, and every filter is simulated against the sample values before it is compiled; materials need their events (name, label, payload top-level kinds) for interactions, and optionally statePreset for state styles. Pass capabilities (granted blueprint capability ids) to skip interactions the host has not granted. Returns the candidate document, the component-id → model-path source table, the compiled behaviors, repair issues keyed by model path (dropped items, LAYOUT_CAPACITY_EXCEEDED, unsatisfiable bindings, interactions with no effect, layout audit errors) and warnings (including INTENT_BLOCK_SUBSTITUTED and INTENT_BEHAVIOR_GAP). Does not touch the loaded snapshot; persist the candidate yourself.',
215
+ (input) => provider.compileScreenIntent(input),
216
+ );
217
+ registerTool(
218
+ server,
219
+ 'profile_dataset',
220
+ {
221
+ definition: z.object({
222
+ datasetId: z.string().min(1),
223
+ name: z.string(),
224
+ description: z.string().nullable().optional().default(null),
225
+ fields: z
226
+ .array(
227
+ z.object({
228
+ id: z.string().min(1),
229
+ label: z.string(),
230
+ valueType: z.enum(['string', 'number', 'boolean', 'date']),
231
+ nullable: z.boolean().optional(),
232
+ unit: z.string().optional(),
233
+ format: z.string().optional(),
234
+ }),
235
+ )
236
+ .max(512),
237
+ parameters: z
238
+ .array(
239
+ z.object({
240
+ name: z.string().min(1),
241
+ label: z.string(),
242
+ valueType: z.enum(['string', 'number', 'boolean', 'date']),
243
+ required: z.boolean(),
244
+ defaultValue: z.union([z.string(), z.number(), z.boolean()]).optional(),
245
+ allowedValues: z.array(z.union([z.string(), z.number(), z.boolean()])).optional(),
246
+ }),
247
+ )
248
+ .optional()
249
+ .default([]),
250
+ }),
251
+ sample: z
252
+ .object({
253
+ rows: z.array(z.record(z.string(), z.unknown())).max(5000),
254
+ totalRowCount: z.number().int().min(0).optional(),
255
+ })
256
+ .optional(),
257
+ },
258
+ 'Profile a dataset deterministically from its describe result and a sample of rows the caller already fetched: per field kind (measure / dimension / time / identifier / empty), distinct count, null ratio, numeric range, time granularity; grain (whether the rows are already aggregated by their dimension and time keys); parameters that still need a value. This server never queries data itself; pass the sample in. Up to 1000 rows are used.',
259
+ (input) =>
260
+ provider.profileDataset({
261
+ definition: input.definition,
262
+ ...(input.sample === undefined
263
+ ? {}
264
+ : { sample: { fields: input.definition.fields, ...input.sample } }),
265
+ }),
266
+ );
267
+ registerTool(
268
+ server,
269
+ 'enumerate_data_candidates',
270
+ {
271
+ profiles: z.array(z.unknown()).min(1).max(4),
272
+ materials: z
273
+ .array(
274
+ z.object({
275
+ type: z.string().min(1),
276
+ name: z.string(),
277
+ roles: z.array(
278
+ z.object({
279
+ id: z.string().min(1),
280
+ minFields: z.number().int().min(0),
281
+ maxFields: z.number().int().min(1),
282
+ valueTypes: z.array(z.enum(['string', 'number', 'boolean', 'date'])).min(1),
283
+ }),
284
+ ),
285
+ }),
286
+ )
287
+ .min(1)
288
+ .max(200),
289
+ maxPerDataset: z.number().int().min(1).max(32).optional(),
290
+ },
291
+ "Enumerate legal (fact, material, role binding) candidates from dataset profiles (output of profile_dataset) and the materials' binding roles. Facts are value, trend, categorization, proportion, rank, association and detail; detail-level (non-aggregated) data only yields detail and single-value candidates. Bindings follow the declared valueTypes and field counts, never role names. Candidates are numbered c1, c2, ... for the intent to reference.",
292
+ (input) => provider.enumerateDataCandidates(input),
293
+ );
294
+ registerTool(
295
+ server,
296
+ 'simulate_blueprint',
297
+ {
298
+ document: z.unknown().optional(),
299
+ event: z
300
+ .object({
301
+ type: z
302
+ .enum([
303
+ 'material-event',
304
+ 'variable-event',
305
+ 'lifecycle',
306
+ 'timer',
307
+ 'canvas-event',
308
+ 'page-changed',
309
+ 'component-state-changed',
310
+ ])
311
+ .optional()
312
+ .default('material-event'),
313
+ componentId: z.string().min(1).optional(),
314
+ variableId: z.string().min(1).optional(),
315
+ canvasId: z.string().min(1).optional(),
316
+ intervalSeconds: z.number().positive().optional(),
317
+ name: z.string().min(1),
318
+ payload: z.unknown().optional().default(null),
319
+ })
320
+ .strict(),
321
+ capabilities: z.array(z.string().min(1)).max(64).optional(),
322
+ },
323
+ 'Simulate one blueprint event and its cascade (variable data-updated, sub-canvas open / close, page changes) with the same implementation the designer workbench and the agent pre-adoption check use. Request actions are only recorded; nothing is fetched and no host action runs. Returns the rules fired per cascade depth, a failure when the cascade exceeds 32 levels or an expression fails, and the end state: changed variables, components whose visibility changed, data source parameters that reference a variable and changed (those instances would refetch), open popups and the current page. Omit document to simulate on the loaded snapshot; pass capabilities to compile the blueprint with only those granted.',
324
+ (input) => provider.simulateBlueprint(input),
325
+ );
326
+ registerTool(
327
+ server,
328
+ 'solve_layout',
329
+ { regions: z.array(z.unknown()).min(1).max(6) },
330
+ 'Solve the layout of a region sequence without any content: band (count of equal KPI cards), grid (slots with span 1-4 and a data flag) and split (main + rail stacks, ratio wide-narrow | even, railSide left | right). Returns pixel boxes per region on the 1920x1080 canvas, or LAYOUT_CAPACITY_EXCEEDED with the required and available pixels when the regions do not fit. Pure function; propose_layout (align / distribute existing components) is unrelated.',
331
+ (input) => provider.solveLayout(input),
332
+ );
333
+ registerTool(
334
+ server,
335
+ 'export_screen',
336
+ { document: z.unknown().optional() },
337
+ 'Serialize a Screen Document to canonical JSON text, the artifact a host persists and compares. Omit document to export the loaded snapshot.',
338
+ (input) => provider.exportScreen(input),
339
+ );
340
+ registerTool(
341
+ server,
342
+ 'import_screen',
343
+ { document: z.unknown() },
344
+ 'Normalize an external Screen Document into the canonical form. Current documents pass through unchanged; legacy documents go through the one-way migration and report decisions.',
345
+ (input) => provider.importScreen(input),
346
+ );
347
+
348
+ return server;
349
+ }
350
+
351
+ function registerJsonResource(server, name, uri, read) {
352
+ server.registerResource(name, uri, { mimeType: 'application/json' }, async (requested) => ({
353
+ contents: [{ uri: requested.href, mimeType: 'application/json', text: json(read()) }],
354
+ }));
355
+ }
356
+
357
+ function registerTool(server, name, shape, description, call) {
358
+ server.registerTool(
359
+ name,
360
+ { description, inputSchema: z.object(shape).strict(), annotations: { readOnlyHint: true } },
361
+ async (input) => toolResult(call(input)),
362
+ );
363
+ }
364
+
365
+ function toolResult(result) {
366
+ const payload = result.value ?? { valid: false, diagnostics: result.diagnostics };
367
+ return {
368
+ isError: !result.ok,
369
+ structuredContent: payload,
370
+ content: [{ type: 'text', text: json(payload) }],
371
+ };
372
+ }
373
+
374
+ function unwrap(result) {
375
+ if (!result.ok) throw new Error(result.diagnostics.map((item) => item.code).join(', '));
376
+ return result.value;
377
+ }
378
+
379
+ function json(value) {
380
+ return JSON.stringify(value, null, 2);
381
+ }
382
+
383
+ async function main() {
384
+ const index = process.argv.indexOf('--screen');
385
+ const screen = index === -1 ? '.base-screen/screen.json' : process.argv[index + 1];
386
+ if (screen === undefined) throw new Error('--screen requires a file path.');
387
+ const provider = await createScreenProvider(screen);
388
+ const server = createScreenMcpServer(provider);
389
+ await server.connect(new StdioServerTransport());
390
+ }
391
+
392
+ if (
393
+ process.argv[1] !== undefined &&
394
+ import.meta.url === pathToFileURL(resolve(process.argv[1])).href
395
+ )
396
+ main().catch((error) => {
397
+ console.error(error instanceof Error ? error.message : String(error));
398
+ process.exitCode = 1;
399
+ });