@becket-ui/mcp 0.4.0 → 0.5.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/dist/server.js CHANGED
@@ -1,4 +1,15 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ BECKET_PUBLIC_COLOR_KEYS,
4
+ checkBecketThemeContrast,
5
+ colorDistance,
6
+ defineBecketTheme,
7
+ deriveBecketTheme,
8
+ extractImageColors,
9
+ formatHex,
10
+ neutralChroma,
11
+ parseColor
12
+ } from "./chunk-UWMYE5IA.js";
2
13
 
3
14
  // src/server.ts
4
15
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -127,6 +138,510 @@ ${rows.join("\n")}
127
138
  Fix them and run review_usage again. A line with "TODO (MAV-\u2026)" is treated as an acknowledged gap.`;
128
139
  }
129
140
 
141
+ // src/theme/setTheme.ts
142
+ var groups = ["colors", "fonts", "radii", "fontSizes", "spacing", "sizes", "density"];
143
+ function setTheme(input) {
144
+ if (!input.brand?.length && !groups.some((group) => input[group] && Object.keys(input[group]).length > 0)) {
145
+ return `Nothing to set. Pass brand colors (\`brand: ["#0a3d91"]\`) and/or exact tokens: ${groups.join(", ")}. To start from a logo, image URL or brand manual, call suggest_theme first.`;
146
+ }
147
+ const notes = [];
148
+ const theme2 = {};
149
+ for (const group of ["spacing", "fontSizes", "radii"]) {
150
+ if (!input[group]) continue;
151
+ const cleaned = {};
152
+ for (const [key, value] of Object.entries(input[group])) {
153
+ const px = value.trim().match(/^(-?\d*\.?\d+)px$/);
154
+ cleaned[key] = px ? `${Number((Number(px[1]) / 16).toFixed(4))}${group === "spacing" && key === "textUnit" ? "em" : "rem"}` : value;
155
+ if (px) {
156
+ notes.push({
157
+ token: `${group}.${key}`,
158
+ reason: `${value} written as ${cleaned[key]} so browser text-size settings still scale it (WCAG 1.4.4).`
159
+ });
160
+ }
161
+ }
162
+ theme2[group] = cleaned;
163
+ }
164
+ if (input.fonts) {
165
+ const generic = [
166
+ "sans-serif",
167
+ "serif",
168
+ "monospace",
169
+ "system-ui",
170
+ "ui-sans-serif",
171
+ "ui-monospace",
172
+ "ui-serif",
173
+ "cursive",
174
+ "fantasy"
175
+ ];
176
+ const fonts = {};
177
+ for (const [key, family] of Object.entries(input.fonts)) {
178
+ const names = family.split(",").map((name) => name.trim()).filter(Boolean);
179
+ const quoted = names.map(
180
+ (name) => /^['"]/.test(name) || !/\s/.test(name) || generic.includes(name) ? name : `'${name}'`
181
+ );
182
+ if (key !== "sans" && key !== "mono" || names.some((name) => generic.includes(name.toLowerCase()))) {
183
+ fonts[key] = quoted.join(", ");
184
+ continue;
185
+ }
186
+ fonts[key] = [
187
+ ...quoted,
188
+ key === "sans" ? "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" : "ui-monospace, 'SF Mono', Menlo, Consolas, monospace"
189
+ ].join(", ");
190
+ notes.push({
191
+ token: `fonts.${key}`,
192
+ reason: `System fallbacks added after ${family}, so text renders before (or without) the webfont.`
193
+ });
194
+ }
195
+ theme2.fonts = fonts;
196
+ notes.push({
197
+ token: "fonts",
198
+ reason: "Becket only names the font. Load the webfont in your app (@font-face or your font host) and check its license covers the web."
199
+ });
200
+ }
201
+ if (input.sizes) theme2.sizes = input.sizes;
202
+ if (input.density) theme2.density = input.density;
203
+ let contrast;
204
+ try {
205
+ if (input.brand?.length) {
206
+ const derived = deriveBecketTheme({
207
+ brand: input.brand,
208
+ // Same as above: defineBecketTheme validates the color keys.
209
+ pinned: input.colors
210
+ });
211
+ theme2.colors = derived.theme.colors;
212
+ notes.unshift(...derived.notes);
213
+ } else if (input.colors) {
214
+ theme2.colors = input.colors;
215
+ }
216
+ defineBecketTheme(theme2);
217
+ contrast = checkBecketThemeContrast(theme2);
218
+ } catch (error) {
219
+ const message = error instanceof Error ? error.message : String(error);
220
+ const path = message.match(/Unknown Becket theme key "(?:theme\.)?([^"]+)"/)?.[1];
221
+ if (!path) return `${message} Nothing was generated.`;
222
+ const [group] = path.split(".");
223
+ const keys = {
224
+ colors: [...BECKET_PUBLIC_COLOR_KEYS.filter((key) => !key.startsWith("light")), "neutral"],
225
+ fonts: ["sans", "mono"],
226
+ radii: ["none", "sm", "md", "lg", "xl", "full"],
227
+ fontSizes: ["base", "xs", "sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl", "6xl"],
228
+ spacing: ["unit", "textUnit", "xs", "sm", "md", "lg", "xl"],
229
+ sizes: ["field"]
230
+ };
231
+ return `${message}. Did you mean ${// What people call Becket tokens, mapped to the real key; otherwise list the group's keys.
232
+ (/* @__PURE__ */ new Map([
233
+ ["colors.brand", "brand (a top-level list of one to three colors)"],
234
+ ["colors.main", "colors.primary"],
235
+ ["colors.primaryColor", "colors.primary"],
236
+ ["colors.secondaryColor", "colors.secondary"],
237
+ ["colors.bg", "colors.background"],
238
+ ["colors.backgroundColor", "colors.background"],
239
+ ["colors.foreground", "colors.text"],
240
+ ["colors.textColor", "colors.text"],
241
+ ["colors.error", "colors.danger"],
242
+ ["colors.gray", "colors.neutral"],
243
+ ["colors.grey", "colors.neutral"],
244
+ ["fonts.body", "fonts.sans"],
245
+ ["fonts.heading", "fonts.sans (Becket uses one sans family for headings and body)"],
246
+ ["fonts.code", "fonts.mono"],
247
+ ["radii.default", "radii.md"],
248
+ ["fontSizes.root", "fontSizes.base"],
249
+ ["spacing.base", "spacing.unit"]
250
+ ])).get(path) ?? `one of ${(keys[group] ?? groups).map((key) => keys[group] ? `${group}.${key}` : key).join(", ")}`}? Nothing was generated.`;
251
+ }
252
+ const required = contrast.results.filter((result) => result.level === "required");
253
+ const flagged = [...contrast.failures, ...contrast.advisories];
254
+ return [
255
+ `# Becket theme${contrast.passes ? "" : " (contrast failures, see below)"}`,
256
+ "## Contrast",
257
+ [
258
+ contrast.passes ? `All ${required.length} required pairs pass WCAG 2.2 AA in dark and light.` : `${contrast.failures.length} of ${required.length} required pairs FAIL WCAG 2.2 AA. Don't ship this theme as is.`,
259
+ flagged.length ? [
260
+ "| theme | where | ratio | needs | result |",
261
+ "| --- | --- | --- | --- | --- |",
262
+ ...flagged.map(
263
+ (result) => `| ${result.theme} | ${result.use} | ${result.ratio}:1 | ${result.minimum}:1 | ${result.passes ? "pass" : result.level === "advisory" ? "advisory" : "**FAIL**"} |`
264
+ )
265
+ ].join("\n") : null,
266
+ contrast.advisories.length ? `Advisory rows aren't enforced because Becket's own default theme misses them too, but fix them when you can: ${[...new Set(contrast.advisories.map((result) => result.note))].join(" ")}` : null
267
+ ].filter(Boolean).join("\n\n"),
268
+ "## Theme CSS",
269
+ `Write this to a file such as \`src/becket-theme.css\` and import it right after \`@becket-ui/tokens/index.css\`. It's unlayered, so it wins over Becket's defaults. Keep \`data-theme\` on <html>.
270
+
271
+ \`\`\`css
272
+ ${defineBecketTheme(theme2)}\`\`\``,
273
+ "## Same theme in code",
274
+ `\`\`\`ts
275
+ import { defineBecketTheme } from '@becket-ui/tokens/theme';
276
+
277
+ export const becketTheme = defineBecketTheme(${JSON.stringify(theme2, null, 2)});
278
+ \`\`\`
279
+ Inject \`becketTheme\` in a <style> tag after index.css, or keep the CSS file above. Use one, not both.`,
280
+ notes.length ? `## Why each value
281
+ ${notes.map((note) => `- ${note.token}: ${note.reason}`).join("\n")}` : null,
282
+ "## Next",
283
+ contrast.passes ? "Show the user the brand colors and any value that was shaded for contrast, then write the CSS file. Don't hand-edit colors afterwards; call set_theme again so they stay checked." : `Tell the user which pairs fail and why. ${input.brand?.length ? "Offer to unpin the failing color so Becket shades it," : "Offer to pass the color as `brand` instead of an exact token, so Becket shades it,"} or to pick another value, then call set_theme again. Don't write a failing theme without the user's say-so.`
284
+ ].filter(Boolean).join("\n\n");
285
+ }
286
+
287
+ // src/theme/loadSource.ts
288
+ import { lookup as dnsLookup } from "dns";
289
+ import { readFile, stat } from "fs/promises";
290
+ import { request } from "https";
291
+ import { BlockList, isIP } from "net";
292
+ import { basename, resolve } from "path";
293
+ var maxBytes = 25 * 1024 * 1024;
294
+ var timeoutMs = 15e3;
295
+ var maxRedirects = 5;
296
+ function detectKind(bytes) {
297
+ if (bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
298
+ return "png";
299
+ if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "jpeg";
300
+ if (bytes.subarray(0, 5).toString("latin1") === "%PDF-") return "pdf";
301
+ if (bytes.subarray(0, 4).toString("latin1") === "RIFF" && bytes.subarray(8, 12).toString("latin1") === "WEBP")
302
+ return "webp";
303
+ if (bytes.subarray(0, 4).toString("latin1") === "GIF8") return "gif";
304
+ const head = bytes.subarray(0, 4096).toString("utf8").replace(/^/, "").trimStart();
305
+ if ((head.startsWith("<?xml") || head.startsWith("<svg") || head.startsWith("<!--") || head.startsWith("<!DOCTYPE svg")) && /<svg[\s>]/i.test(head))
306
+ return "svg";
307
+ return "unknown";
308
+ }
309
+ var blocked = new BlockList();
310
+ for (const [network, prefix] of [
311
+ ["0.0.0.0", 8],
312
+ ["10.0.0.0", 8],
313
+ ["100.64.0.0", 10],
314
+ ["127.0.0.0", 8],
315
+ ["169.254.0.0", 16],
316
+ ["172.16.0.0", 12],
317
+ ["192.0.0.0", 24],
318
+ ["192.0.2.0", 24],
319
+ ["192.168.0.0", 16],
320
+ ["198.18.0.0", 15],
321
+ ["198.51.100.0", 24],
322
+ ["203.0.113.0", 24],
323
+ ["224.0.0.0", 4],
324
+ ["240.0.0.0", 4]
325
+ ]) {
326
+ blocked.addSubnet(network, prefix, "ipv4");
327
+ }
328
+ for (const [network, prefix] of [
329
+ ["::", 128],
330
+ ["::1", 128],
331
+ ["fc00::", 7],
332
+ ["fe80::", 10],
333
+ ["ff00::", 8],
334
+ ["2001:db8::", 32],
335
+ ["64:ff9b::", 96]
336
+ ]) {
337
+ blocked.addSubnet(network, prefix, "ipv6");
338
+ }
339
+ function isPublicAddress(address) {
340
+ const family = isIP(address);
341
+ if (family === 0) return false;
342
+ if (family === 4) return !blocked.check(address, "ipv4");
343
+ const mapped = new URL(`http://[${address}]`).hostname.match(
344
+ /^\[::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})\]$/
345
+ );
346
+ if (mapped) {
347
+ const [high, low] = [Number.parseInt(mapped[1], 16), Number.parseInt(mapped[2], 16)];
348
+ return isPublicAddress([high >> 8, high & 255, low >> 8, low & 255].join("."));
349
+ }
350
+ return !blocked.check(address, "ipv6");
351
+ }
352
+ function download(raw, redirects) {
353
+ return new Promise((resolvePromise, reject) => {
354
+ let url;
355
+ try {
356
+ url = new URL(raw);
357
+ } catch {
358
+ throw new Error(`"${raw}" isn't a URL.`);
359
+ }
360
+ if (url.protocol !== "https:")
361
+ throw new Error(`Only https URLs are fetched, not ${url.protocol}//.`);
362
+ if (url.username || url.password) throw new Error("URLs with credentials are refused.");
363
+ const host = url.hostname.replace(/^\[|\]$/g, "");
364
+ if (isIP(host) && !isPublicAddress(host))
365
+ throw new Error(
366
+ `${host} is a private or reserved address; only public https URLs are fetched.`
367
+ );
368
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal")) {
369
+ throw new Error(`${host} is a local host name; only public https URLs are fetched.`);
370
+ }
371
+ const req = request(
372
+ url,
373
+ {
374
+ // Resolve, then refuse private addresses. This runs at connect time, so a DNS answer that
375
+ // changes between a check and the request (rebinding) can't reach an internal host.
376
+ lookup: (hostname, options, callback) => {
377
+ dnsLookup(hostname, { ...options, all: true }, (error, addresses) => {
378
+ if (error) return callback(error, "", 0);
379
+ const list = addresses;
380
+ const refused = list.find((entry) => !isPublicAddress(entry.address));
381
+ if (refused || list.length === 0) {
382
+ return callback(
383
+ new Error(
384
+ `${hostname} resolves to a private or reserved address (${refused?.address ?? "none"}); only public https URLs are fetched.`
385
+ ),
386
+ "",
387
+ 0
388
+ );
389
+ }
390
+ if (options.all) {
391
+ return callback(
392
+ null,
393
+ list
394
+ );
395
+ }
396
+ return callback(null, list[0].address, list[0].family);
397
+ });
398
+ },
399
+ timeout: timeoutMs,
400
+ headers: { accept: "image/*, application/pdf", "user-agent": "@becket-ui/mcp" }
401
+ },
402
+ (response) => {
403
+ const status = response.statusCode ?? 0;
404
+ if (status >= 300 && status < 400 && response.headers.location) {
405
+ response.resume();
406
+ if (redirects >= maxRedirects)
407
+ return reject(new Error(`More than ${maxRedirects} redirects.`));
408
+ try {
409
+ return resolvePromise(
410
+ download(new URL(response.headers.location, url).toString(), redirects + 1)
411
+ );
412
+ } catch (error) {
413
+ return reject(error);
414
+ }
415
+ }
416
+ if (status !== 200) {
417
+ response.resume();
418
+ return reject(new Error(`The server answered ${status}.`));
419
+ }
420
+ const declared = Number(response.headers["content-length"] ?? 0);
421
+ if (declared > maxBytes) {
422
+ response.destroy();
423
+ return reject(
424
+ new Error(
425
+ `The file is ${(declared / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`
426
+ )
427
+ );
428
+ }
429
+ const chunks = [];
430
+ let size = 0;
431
+ response.on("data", (chunk) => {
432
+ size += chunk.length;
433
+ if (size > maxBytes) {
434
+ response.destroy();
435
+ reject(new Error(`The file is over the ${maxBytes / 1048576} MB limit.`));
436
+ return;
437
+ }
438
+ chunks.push(chunk);
439
+ });
440
+ response.on("end", () => resolvePromise(Buffer.concat(chunks)));
441
+ response.on("error", reject);
442
+ }
443
+ );
444
+ req.on("timeout", () => req.destroy(new Error(`No answer within ${timeoutMs / 1e3} s.`)));
445
+ req.on("error", reject);
446
+ req.end();
447
+ });
448
+ }
449
+ async function loadSource(input) {
450
+ if ([input.path, input.url, input.base64].filter(Boolean).length !== 1)
451
+ throw new Error("Pass exactly one of path, url or base64.");
452
+ let bytes;
453
+ let label;
454
+ if (input.path) {
455
+ const path = resolve(input.path);
456
+ const info = await stat(path).catch(() => null);
457
+ if (!info?.isFile()) throw new Error(`No file at ${path}.`);
458
+ if (info.size > maxBytes)
459
+ throw new Error(
460
+ `${basename(path)} is ${(info.size / 1048576).toFixed(1)} MB; the limit is ${maxBytes / 1048576} MB.`
461
+ );
462
+ bytes = await readFile(path);
463
+ label = basename(path);
464
+ } else if (input.url) {
465
+ bytes = await download(input.url, 0);
466
+ label = input.url;
467
+ } else {
468
+ const data = (input.base64 ?? "").replace(/^data:[^;,]+;base64,/, "").replace(/\s+/g, "");
469
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error("base64 isn't valid base64.");
470
+ if (data.length * 3 / 4 > maxBytes)
471
+ throw new Error(`The data is over the ${maxBytes / 1048576} MB limit.`);
472
+ bytes = Buffer.from(data, "base64");
473
+ label = "base64 data";
474
+ }
475
+ if (bytes.length === 0) throw new Error("The file is empty.");
476
+ return { bytes, kind: detectKind(bytes), label };
477
+ }
478
+
479
+ // src/theme/suggestTheme.ts
480
+ function pickBrand(findings) {
481
+ const candidates = [
482
+ ...(findings.stated?.colors ?? []).flatMap((entry) => {
483
+ const color = parseColor(entry.hex);
484
+ return color ? [{ hex: entry.hex, color }] : [];
485
+ }),
486
+ ...findings.colors.filter((color) => color.role !== "background").map((entry, _, sampled) => ({
487
+ ...entry,
488
+ family: sampled.filter((other) => colorDistance(other.color, entry.color) < 0.1).reduce((sum, other) => sum + other.share, 0)
489
+ })).filter((entry) => entry.family >= 0.05).toSorted((a, b) => b.family - a.family)
490
+ ];
491
+ const picked = [];
492
+ for (const candidate of candidates) {
493
+ if (candidate.color.C < neutralChroma) continue;
494
+ if (picked.some((other) => {
495
+ const gap = Math.abs(other.color.h - candidate.color.h);
496
+ return Math.min(gap, 360 - gap) < 30;
497
+ }))
498
+ continue;
499
+ picked.push(candidate);
500
+ if (picked.length === 3) break;
501
+ }
502
+ if (picked.length > 0) return picked.map((entry) => entry.hex);
503
+ const darkest = candidates.filter((entry) => entry.color.L < 0.9).toSorted((a, b) => a.color.L - b.color.L)[0];
504
+ return darkest ? [darkest.hex] : [];
505
+ }
506
+ function formatSuggestion(findings) {
507
+ const brand = pickBrand(findings);
508
+ const stated = findings.stated;
509
+ const lines = [
510
+ `# Brand suggestion from ${findings.label}`,
511
+ `Read as: ${findings.method}.`
512
+ ];
513
+ if (stated?.colors.length) {
514
+ lines.push(
515
+ "## Colors the source states",
516
+ // One entry: sections are joined with blank lines, which would break a Markdown table apart.
517
+ [
518
+ "| color | name | page |",
519
+ "| --- | --- | --- |",
520
+ ...stated.colors.map((entry) => `| ${entry.hex} | ${entry.name ?? ""} | ${entry.page} |`)
521
+ ].join("\n")
522
+ );
523
+ }
524
+ if (findings.colors.length) {
525
+ lines.push(
526
+ stated ? "## Colors sampled from its artwork" : "## Colors found",
527
+ [
528
+ "| color | share | role |",
529
+ "| --- | --- | --- |",
530
+ ...findings.colors.slice(0, 10).map((color) => `| ${color.hex} | ${Math.round(color.share * 100)}% | ${color.role} |`)
531
+ ].join("\n")
532
+ );
533
+ }
534
+ if (findings.skipped.length)
535
+ lines.push(
536
+ `Skipped (not a color Becket can read): ${findings.skipped.slice(0, 10).join(", ")}.`
537
+ );
538
+ if (brand.length === 0) {
539
+ lines.push(
540
+ "## Next",
541
+ "No brand color found. Ask the user for their brand colors (hex is best), then call set_theme with `brand`."
542
+ );
543
+ return lines.join("\n\n");
544
+ }
545
+ const fonts = stated?.fonts ?? [];
546
+ const steps = [
547
+ "brand colors",
548
+ fonts.length ? "brand font" : null,
549
+ stated?.radii.length || stated?.baseSize.length ? "corners and text size" : null
550
+ ].filter(Boolean);
551
+ lines.push(
552
+ "## Guided setup",
553
+ `Ask the user one step at a time and wait for each answer. ${steps.length} step${steps.length > 1 ? "s" : ""}: ${steps.join(", then ")}.`,
554
+ `### Step 1 of ${steps.length}: brand colors`,
555
+ `Ask: "These look like your brand colors: ${brand.join(", ")}. Which should Becket use, most important first?" Offer:`,
556
+ ...[
557
+ { label: "Recommended", brand },
558
+ ...brand.length >= 2 ? [
559
+ { label: "Swap the first two", brand: [brand[1], brand[0], ...brand.slice(2)] },
560
+ { label: "First color only", brand: [brand[0]] }
561
+ ] : []
562
+ ].map((option, index) => {
563
+ const { theme: theme2, contrast, notes } = deriveBecketTheme({ brand: option.brand });
564
+ const [button, link] = [
565
+ theme2.colors?.primary,
566
+ typeof theme2.colors?.link === "object" ? theme2.colors.link.light : theme2.colors?.link
567
+ ].map((value) => {
568
+ const color = typeof value === "string" ? parseColor(value) : null;
569
+ return color ? formatHex(color) : String(value);
570
+ });
571
+ return `${index + 1}. ${option.label}: \`${JSON.stringify(option.brand)}\` \u2014 buttons ${button}${notes.some((note) => note.token === "primary" && /lightened/.test(note.reason)) ? ` (lightened from ${option.brand[0]} for readable labels)` : ""}, light-theme links ${link}; ${contrast.passes ? "passes AA in dark and light" : `${contrast.failures.length} AA failures`}`;
572
+ }),
573
+ "Or the user gives their own hex values. Becket shades any color that would fail contrast and says why."
574
+ );
575
+ let step = 1;
576
+ if (fonts.length) {
577
+ step += 1;
578
+ const families = [...new Set(fonts.map((font) => font.family))];
579
+ lines.push(
580
+ `### Step ${step} of ${steps.length}: brand font`,
581
+ `Ask: "Your manual uses ${families.slice(0, 3).join(", ")}. Use ${families[0]} for Becket's text?" Offer: yes (\`fonts: { "sans": "${families[0]}" }\`), another of those, or keep Becket's system font. Mention the app must load the webfont and its license must cover the web.`
582
+ );
583
+ }
584
+ if (stated?.radii.length || stated?.baseSize.length) {
585
+ step += 1;
586
+ const radius = stated.radii[0];
587
+ const base = stated.baseSize[0];
588
+ lines.push(
589
+ `### Step ${step} of ${steps.length}: corners and text size`,
590
+ `Ask: "Your manual sets ${[
591
+ radius && `corner radius ${radius.value} (page ${radius.page})`,
592
+ base && `body text ${base.value} (page ${base.page})`
593
+ ].filter(Boolean).join(" and ")}. Apply ${radius && base ? "them" : "it"} to Becket?" If yes, add ${[
594
+ radius && `radii: { "md": "${radius.value}" }`,
595
+ base && `fontSizes: { "base": "${base.value}" }`
596
+ ].filter(Boolean).join(", ")}. Otherwise keep Becket's defaults.`
597
+ );
598
+ }
599
+ if (!fonts.length) {
600
+ lines.push(
601
+ stated ? "No font name found in the manual." : "An image has no font name to read.",
602
+ 'If the user mentions a brand font, add `fonts: { "sans": "<family>" }`; otherwise keep Becket\'s system font. Don\'t guess a font from a logo.'
603
+ );
604
+ }
605
+ lines.push(
606
+ "### Finish",
607
+ `Call set_theme with only what the user confirmed, e.g. \`${JSON.stringify({ brand })}\`. It returns the CSS to write and a contrast report. Don't call set_theme before the user confirms the brand colors.`
608
+ );
609
+ return lines.join("\n\n");
610
+ }
611
+ async function suggestTheme(input) {
612
+ try {
613
+ if (input.colors?.length && !input.path && !input.url && !input.base64) {
614
+ return formatSuggestion({
615
+ label: "the colors you read from the image",
616
+ method: "colors passed by the agent, in the order given",
617
+ colors: input.colors.map((value, _, all) => {
618
+ const color = parseColor(value);
619
+ if (!color)
620
+ throw new Error(`Can't read the color "${value}". Use hex, rgb(), hsl() or oklch().`);
621
+ return {
622
+ hex: formatHex(color),
623
+ color,
624
+ share: 1 / all.length,
625
+ role: color.C < neutralChroma ? "neutral" : "brand"
626
+ };
627
+ }),
628
+ skipped: []
629
+ });
630
+ }
631
+ const source = await loadSource(input);
632
+ if (source.kind === "pdf") {
633
+ const { extractPDF } = await import("./extractPDF-GMTNLU27.js");
634
+ return formatSuggestion(await extractPDF(source));
635
+ }
636
+ const { colors, method, skipped } = extractImageColors(source);
637
+ return formatSuggestion({ label: source.label, method, colors, skipped });
638
+ } catch (error) {
639
+ return `Couldn't read that source: ${error instanceof Error ? error.message : String(error)}
640
+
641
+ If the image is only in the chat (pasted), read its main colors yourself and call suggest_theme with \`colors: ["#\u2026", "#\u2026"]\`, or ask the user for the file path.`;
642
+ }
643
+ }
644
+
130
645
  // src/tools.ts
131
646
  function installation(data) {
132
647
  const { version } = data.catalog;
@@ -145,6 +660,8 @@ pnpm add @becket-ui/react @becket-ui/tokens
145
660
  - index.css paints the page background, text color and font from the theme.
146
661
  - Components marked client in list_components use state or effects ('use client'); the rest render in React Server Components.
147
662
 
663
+ To brand Becket, call set_theme with brand colors or tokens, or suggest_theme with a logo, image URL or brand manual.
664
+
148
665
  Before writing UI, call get_guidelines (the app-code guide). Before finishing, call review_usage on your code.`;
149
666
  }
150
667
  function listComponents(data) {
@@ -214,9 +731,9 @@ ${example.code}
214
731
  \`\`\``).join("\n\n")}`;
215
732
  }
216
733
  function theme(data, group) {
217
- const groups = group ? Object.entries(data.theme).filter(([name]) => name === group) : Object.entries(data.theme);
218
- if (groups.length === 0) return `Unknown token group "${group}". Groups: ${Object.keys(data.theme).join(", ")}.`;
219
- const sections = groups.map(([name, tokens]) => {
734
+ const groups2 = group ? Object.entries(data.theme).filter(([name]) => name === group) : Object.entries(data.theme);
735
+ if (groups2.length === 0) return `Unknown token group "${group}". Groups: ${Object.keys(data.theme).join(", ")}.`;
736
+ const sections = groups2.map(([name, tokens]) => {
220
737
  const rows = tokens.map((token) => `| ${token.token} | \`${token.cssVar}\` | ${token.value} | ${token.light ?? "same"} |`);
221
738
  return `## ${name}
222
739
  | token | CSS variable | dark (default) | light |
@@ -318,6 +835,41 @@ function createServer(data = loadData()) {
318
835
  },
319
836
  async ({ code }) => text(formatReview(reviewUsage(code, data)))
320
837
  );
838
+ const tokens = z.record(z.string(), z.string());
839
+ server.registerTool(
840
+ "set_theme",
841
+ {
842
+ title: "Set a brand theme",
843
+ description: "Turn brand tokens into Becket theme CSS that passes WCAG 2.2 AA in dark and light. Give one to three brand colors (Becket derives every color token) and/or exact tokens. Returns the CSS to write, the same theme as defineBecketTheme() code, why each value was chosen, and a contrast report. Writes nothing; you write the file. For a logo, image URL or brand manual, call suggest_theme first.",
844
+ inputSchema: {
845
+ brand: z.array(z.string()).min(1).max(3).optional().describe("Brand colors, most important first: hex, rgb(), hsl() or oklch()"),
846
+ colors: z.record(z.string(), z.union([z.string(), z.record(z.string(), z.string())])).optional().describe('Exact color tokens to keep, e.g. { "background": { "dark": "#101820", "light": "#ffffff" } }. With brand, these are pinned and the rest is derived.'),
847
+ fonts: tokens.optional().describe('{ "sans": "Inter", "mono": "JetBrains Mono" }'),
848
+ radii: tokens.optional().describe('none, sm, md, lg, xl, full, e.g. { "md": "0.25rem" }'),
849
+ fontSizes: tokens.optional().describe('{ "base": "1rem" } resizes all text; xs\u20136xl override single steps'),
850
+ spacing: tokens.optional().describe('{ "unit": "0.25rem" } resizes all spacing; textUnit (em) spacing inside text'),
851
+ sizes: tokens.optional().describe('{ "field": "16rem" }'),
852
+ density: z.record(z.string(), z.record(z.string(), z.object({ px: z.string().optional(), py: z.string().optional() }))).optional().describe('Component padding, e.g. { "button": { "md": { "px": "0.75rem" } } }')
853
+ },
854
+ annotations: readOnly
855
+ },
856
+ async (input) => text(setTheme(input))
857
+ );
858
+ server.registerTool(
859
+ "suggest_theme",
860
+ {
861
+ title: "Suggest a brand theme",
862
+ description: "Read a logo (PNG, JPEG, SVG) or a brand manual (PDF) and suggest Becket brand tokens: colors, plus fonts, corner radius and text size when a manual states them. Returns what it found and a step-by-step script: ask the user one decision at a time, then call set_theme with what they confirm. Pass exactly one of path, url (public https) or base64. For an image only pasted in chat, pass the colors you see in `colors` instead.",
863
+ inputSchema: {
864
+ path: z.string().optional().describe("Local file path, absolute or relative to the working directory"),
865
+ url: z.string().optional().describe("Public https URL of the image or PDF"),
866
+ base64: z.string().optional().describe("File contents as base64 or a data: URL"),
867
+ colors: z.array(z.string()).min(1).max(8).optional().describe("Colors you read from an image you can see but cannot pass as a file, most prominent first")
868
+ },
869
+ annotations: { readOnlyHint: true, openWorldHint: true }
870
+ },
871
+ async (input) => text(await suggestTheme(input))
872
+ );
321
873
  return server;
322
874
  }
323
875