@becket-ui/mcp 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +111 -2
- package/dist/chunk-UWMYE5IA.js +780 -0
- package/dist/chunk-UWMYE5IA.js.map +1 -0
- package/dist/data/catalog.json +1838 -0
- package/dist/data/guidelines.md +285 -0
- package/dist/data/theme.json +448 -0
- package/dist/extractPDF-GMTNLU27.js +155 -0
- package/dist/extractPDF-GMTNLU27.js.map +1 -0
- package/dist/server.js +878 -0
- package/dist/server.js.map +1 -0
- package/package.json +55 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,878 @@
|
|
|
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";
|
|
13
|
+
|
|
14
|
+
// src/server.ts
|
|
15
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
16
|
+
|
|
17
|
+
// src/createServer.ts
|
|
18
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
|
|
21
|
+
// src/data.ts
|
|
22
|
+
import { readFileSync } from "fs";
|
|
23
|
+
import { dirname, join } from "path";
|
|
24
|
+
import { fileURLToPath } from "url";
|
|
25
|
+
function loadData(dataDir = join(dirname(fileURLToPath(import.meta.url)), "data")) {
|
|
26
|
+
const read = (file) => readFileSync(join(dataDir, file), "utf8");
|
|
27
|
+
return {
|
|
28
|
+
catalog: JSON.parse(read("catalog.json")),
|
|
29
|
+
theme: JSON.parse(read("theme.json")),
|
|
30
|
+
guidelines: read("guidelines.md")
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// src/review.ts
|
|
35
|
+
var LINE_RULES = [
|
|
36
|
+
{
|
|
37
|
+
rule: "no-chakra",
|
|
38
|
+
pattern: /from\s+['"]@chakra-ui\//,
|
|
39
|
+
message: "Imports Chakra UI.",
|
|
40
|
+
fix: "Import the equivalent from '@becket-ui/react'; Becket has no provider."
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
rule: "no-recipe-classes",
|
|
44
|
+
pattern: /beckui--[\w-]+/,
|
|
45
|
+
message: "Uses a generated .beckui--* class name.",
|
|
46
|
+
fix: "Use the component and its props; recipe classes are not API."
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
rule: "no-raw-flex-or-grid",
|
|
50
|
+
pattern: /display\s*:\s*['"]?(?:inline-)?(?:flex|grid)/,
|
|
51
|
+
message: "Lays out with an inline display: flex/grid style.",
|
|
52
|
+
fix: 'Use VStack / HStack / Flex (flex) or SimpleGrid (grid) with gap="xs|sm|md|lg|xl".'
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
rule: "no-raw-heading",
|
|
56
|
+
pattern: /<h[1-6][\s>]/,
|
|
57
|
+
message: "Uses a raw h1\u2013h6 element.",
|
|
58
|
+
fix: 'Use <Heading as="h1" size="2xl"> (as sets the level, size sets the look).'
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
rule: "no-raw-text",
|
|
62
|
+
pattern: /<(?:p|span)\s[^>]*style=\{\{[^}]*(?:fontSize|fontWeight|color)\s*:/,
|
|
63
|
+
message: "Styles text with an inline style on p/span.",
|
|
64
|
+
fix: 'Use <Text fontSize="sm" color="muted">, or <Text as="strong"> for bold.'
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
rule: "no-raw-divider",
|
|
68
|
+
pattern: /<hr[\s/>]|height\s*:\s*1(?:px)?\s*[,}]/,
|
|
69
|
+
message: "Draws a divider with hr or a 1px element.",
|
|
70
|
+
fix: 'Use <Separator /> (orientation="vertical" inside a row).'
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
rule: "no-raw-controls",
|
|
74
|
+
pattern: /<(?:button|input|select|textarea)[\s>/]/,
|
|
75
|
+
message: "Uses a raw form control.",
|
|
76
|
+
fix: "Use Button, TextField / Field + FieldControl, Select, Textarea, Checkbox, RadioGroup + Radio or Switch."
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
rule: "no-color-literals",
|
|
80
|
+
pattern: /['"`]#[0-9a-fA-F]{3,8}['"`]|\b(?:rgb|rgba|hsl|hsla)\(/,
|
|
81
|
+
message: "Uses a literal color.",
|
|
82
|
+
fix: 'Use tokens: color="muted" on Text, or var(--beckui--colors-<token>) in your own CSS (see get_theme).'
|
|
83
|
+
},
|
|
84
|
+
{
|
|
85
|
+
rule: "no-pixel-spacing",
|
|
86
|
+
pattern: /\b(?:gap|padding|margin|rowGap|columnGap)(?:Top|Bottom|Left|Right|Inline|Block)?\s*:\s*(?:['"]?\d+(?:px)?['"]?)\s*[,}]/,
|
|
87
|
+
message: "Sets spacing in pixels.",
|
|
88
|
+
fix: 'Use gap="xs|sm|md|lg|xl" on layout components, or var(--beckui--spacing-<token>) in your own CSS.'
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
rule: "theme-at-root",
|
|
92
|
+
pattern: /data-theme=/,
|
|
93
|
+
message: "Sets data-theme on an element in JSX.",
|
|
94
|
+
fix: 'Set the theme once on <html data-theme="dark|light"> at the app root.'
|
|
95
|
+
}
|
|
96
|
+
];
|
|
97
|
+
function unknownImports(code, data) {
|
|
98
|
+
const known = /* @__PURE__ */ new Set([
|
|
99
|
+
...data.catalog.components.flatMap((component) => [...component.exports, ...component.hooks, ...component.types]),
|
|
100
|
+
...data.catalog.helpers.flatMap((helper) => [...helper.exports, ...helper.types])
|
|
101
|
+
]);
|
|
102
|
+
const findings = [];
|
|
103
|
+
const statement = /import\s+(?:type\s+)?\{([^}]*)\}\s+from\s+['"]@becket-ui\/react['"]/g;
|
|
104
|
+
for (const match of code.matchAll(statement)) {
|
|
105
|
+
const line = code.slice(0, match.index).split("\n").length;
|
|
106
|
+
for (const raw of match[1].split(",")) {
|
|
107
|
+
const name = raw.replace(/^\s*type\s+/, "").split(/\s+as\s+/)[0].trim();
|
|
108
|
+
if (name && !known.has(name)) {
|
|
109
|
+
findings.push({
|
|
110
|
+
line,
|
|
111
|
+
rule: "unknown-export",
|
|
112
|
+
message: `"${name}" is not exported by @becket-ui/react.`,
|
|
113
|
+
fix: "Check list_components; compose existing components instead of inventing one."
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return findings;
|
|
119
|
+
}
|
|
120
|
+
function reviewUsage(code, data) {
|
|
121
|
+
const findings = [];
|
|
122
|
+
code.split("\n").forEach((text2, index) => {
|
|
123
|
+
if (/TODO\s*\(MAV-\d+\)/.test(text2)) return;
|
|
124
|
+
for (const rule of LINE_RULES) {
|
|
125
|
+
if (rule.pattern.test(text2)) findings.push({ line: index + 1, rule: rule.rule, message: rule.message, fix: rule.fix });
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
return [...findings, ...unknownImports(code, data)].sort((a, b) => a.line - b.line);
|
|
129
|
+
}
|
|
130
|
+
function formatReview(findings) {
|
|
131
|
+
if (findings.length === 0) {
|
|
132
|
+
return "No issues found. The code follows the Becket app-code guide for everything this check covers (layout, text, controls, colors, spacing, theme, imports).";
|
|
133
|
+
}
|
|
134
|
+
const rows = findings.map((finding) => `- line ${finding.line} [${finding.rule}] ${finding.message} Fix: ${finding.fix}`);
|
|
135
|
+
return `${findings.length} issue(s):
|
|
136
|
+
${rows.join("\n")}
|
|
137
|
+
|
|
138
|
+
Fix them and run review_usage again. A line with "TODO (MAV-\u2026)" is treated as an acknowledged gap.`;
|
|
139
|
+
}
|
|
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
|
+
|
|
645
|
+
// src/tools.ts
|
|
646
|
+
function installation(data) {
|
|
647
|
+
const { version } = data.catalog;
|
|
648
|
+
return `# Installing Becket UI (@becket-ui/react ${version})
|
|
649
|
+
|
|
650
|
+
pnpm add @becket-ui/react @becket-ui/tokens
|
|
651
|
+
|
|
652
|
+
1. Import the CSS once, at the app entry:
|
|
653
|
+
import '@becket-ui/tokens/index.css';
|
|
654
|
+
2. Put the theme on <html>: <html data-theme="dark"> (dark is the default) or "light".
|
|
655
|
+
Set it at the app root, never inside a screen. There is no provider and no theme wrapper.
|
|
656
|
+
3. Import components from '@becket-ui/react':
|
|
657
|
+
import { Button, Card, Container, Stack, Text } from '@becket-ui/react';
|
|
658
|
+
|
|
659
|
+
- Panda CSS is not required: styles ship prebuilt in index.css. Don't copy .beckui--* class names.
|
|
660
|
+
- index.css paints the page background, text color and font from the theme.
|
|
661
|
+
- Components marked client in list_components use state or effects ('use client'); the rest render in React Server Components.
|
|
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
|
+
|
|
665
|
+
Before writing UI, call get_guidelines (the app-code guide). Before finishing, call review_usage on your code.`;
|
|
666
|
+
}
|
|
667
|
+
function listComponents(data) {
|
|
668
|
+
const byGroup = /* @__PURE__ */ new Map();
|
|
669
|
+
for (const component of data.catalog.components) {
|
|
670
|
+
const group = component.group ?? "Other";
|
|
671
|
+
byGroup.set(group, [...byGroup.get(group) ?? [], component]);
|
|
672
|
+
}
|
|
673
|
+
const sections = [...byGroup.entries()].map(([group, components]) => {
|
|
674
|
+
const rows = components.map((component) => {
|
|
675
|
+
const parts = component.exports.filter((name) => name !== component.name);
|
|
676
|
+
const tags = [component.client ? "client" : "server-safe", component.examples.length ? `${component.examples.length} examples` : null].filter(Boolean).join(", ");
|
|
677
|
+
return `- ${component.name}${parts.length ? ` (also: ${parts.join(", ")})` : ""} [${tags}]${component.summary ? ` \u2014 ${component.summary.split("\n")[0]}` : ""}`;
|
|
678
|
+
});
|
|
679
|
+
return `## ${group}
|
|
680
|
+
${rows.join("\n")}`;
|
|
681
|
+
});
|
|
682
|
+
return `@becket-ui/react ${data.catalog.version}: ${data.catalog.components.length} component files.
|
|
683
|
+
Use get_component_props for exact props and get_component_example for usage.
|
|
684
|
+
|
|
685
|
+
${sections.join("\n\n")}`;
|
|
686
|
+
}
|
|
687
|
+
function findComponent(data, name) {
|
|
688
|
+
const wanted = name.trim().toLowerCase();
|
|
689
|
+
return data.catalog.components.find(
|
|
690
|
+
(component) => component.name.toLowerCase() === wanted || component.file.toLowerCase() === wanted || component.exports.some((exported) => exported.toLowerCase() === wanted)
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
function notFound(data, name) {
|
|
694
|
+
const names = data.catalog.components.map((component) => component.name).join(", ");
|
|
695
|
+
return `No Becket component named "${name}". Available: ${names}.`;
|
|
696
|
+
}
|
|
697
|
+
function componentProps(data, name) {
|
|
698
|
+
const component = findComponent(data, name);
|
|
699
|
+
if (!component) return notFound(data, name);
|
|
700
|
+
const variants = component.variants ? Object.entries(component.variants).map(([prop, values]) => `- ${prop}: ${values.map((value) => `"${value}"`).join(" | ")}`).join("\n") : null;
|
|
701
|
+
return [
|
|
702
|
+
`# ${component.name}${component.group ? ` (${component.group})` : ""}`,
|
|
703
|
+
component.summary,
|
|
704
|
+
`Exports: ${component.exports.join(", ")}${component.hooks.length ? `; hooks: ${component.hooks.join(", ")}` : ""}`,
|
|
705
|
+
`Rendering: ${component.client ? "client component ('use client': state, effects or browser APIs)" : "no client JS required; safe in React Server Components"}`,
|
|
706
|
+
variants ? `## Recipe variants (exact values)
|
|
707
|
+
${variants}` : null,
|
|
708
|
+
`## Type declarations
|
|
709
|
+
\`\`\`ts
|
|
710
|
+
${component.dts}
|
|
711
|
+
\`\`\``
|
|
712
|
+
].filter(Boolean).join("\n\n");
|
|
713
|
+
}
|
|
714
|
+
function componentExample(data, name, story) {
|
|
715
|
+
const component = findComponent(data, name);
|
|
716
|
+
if (!component) return notFound(data, name);
|
|
717
|
+
if (component.examples.length === 0) {
|
|
718
|
+
return `${component.name} has no examples yet. Read get_component_props for its API.`;
|
|
719
|
+
}
|
|
720
|
+
const chosen = story ? component.examples.filter((example) => example.name.toLowerCase() === story.trim().toLowerCase()) : component.examples;
|
|
721
|
+
if (chosen.length === 0) {
|
|
722
|
+
return `No example "${story}" for ${component.name}. Available: ${component.examples.map((example) => example.name).join(", ")}.`;
|
|
723
|
+
}
|
|
724
|
+
const note = 'These are Storybook stories. In app code, import from "@becket-ui/react", drop `args`/`Story` typing, and follow get_guidelines.';
|
|
725
|
+
return `# ${component.name} examples
|
|
726
|
+
${note}
|
|
727
|
+
|
|
728
|
+
${chosen.map((example) => `## ${example.name}
|
|
729
|
+
\`\`\`tsx
|
|
730
|
+
${example.code}
|
|
731
|
+
\`\`\``).join("\n\n")}`;
|
|
732
|
+
}
|
|
733
|
+
function theme(data, group) {
|
|
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]) => {
|
|
737
|
+
const rows = tokens.map((token) => `| ${token.token} | \`${token.cssVar}\` | ${token.value} | ${token.light ?? "same"} |`);
|
|
738
|
+
return `## ${name}
|
|
739
|
+
| token | CSS variable | dark (default) | light |
|
|
740
|
+
| --- | --- | --- | --- |
|
|
741
|
+
${rows.join("\n")}`;
|
|
742
|
+
});
|
|
743
|
+
return `Becket tokens. In components, pass token names as props (gap="md", color="muted"). In your own CSS, use the CSS variables. Never hex, rgb() or px.
|
|
744
|
+
|
|
745
|
+
${sections.join("\n\n")}`;
|
|
746
|
+
}
|
|
747
|
+
function guidelines(data, topic) {
|
|
748
|
+
const sections = data.guidelines.split(/\n(?=## )/);
|
|
749
|
+
if (!topic) return data.guidelines;
|
|
750
|
+
const wanted = topic.trim().toLowerCase();
|
|
751
|
+
const matches = sections.filter((section) => section.split("\n")[0].toLowerCase().includes(wanted));
|
|
752
|
+
if (matches.length > 0) return matches.join("\n\n");
|
|
753
|
+
const titles = sections.slice(1).map((section) => section.split("\n")[0].replace(/^## /, ""));
|
|
754
|
+
return `No section matches "${topic}". Sections:
|
|
755
|
+
${titles.map((title) => `- ${title}`).join("\n")}`;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// src/createServer.ts
|
|
759
|
+
var text = (value) => ({ content: [{ type: "text", text: value }] });
|
|
760
|
+
function createServer(data = loadData()) {
|
|
761
|
+
const server = new McpServer({ name: "becket-ui", version: data.catalog.version });
|
|
762
|
+
const readOnly = { readOnlyHint: true, openWorldHint: false };
|
|
763
|
+
server.registerTool(
|
|
764
|
+
"installation",
|
|
765
|
+
{
|
|
766
|
+
title: "Install Becket UI",
|
|
767
|
+
description: "How to install and set up Becket UI in a React app: packages, the one CSS import, and the theme on <html>.",
|
|
768
|
+
annotations: readOnly
|
|
769
|
+
},
|
|
770
|
+
async () => text(installation(data))
|
|
771
|
+
);
|
|
772
|
+
server.registerTool(
|
|
773
|
+
"list_components",
|
|
774
|
+
{
|
|
775
|
+
title: "List Becket components",
|
|
776
|
+
description: "Every public Becket UI component by group, with its parts and whether it needs client JS.",
|
|
777
|
+
annotations: readOnly
|
|
778
|
+
},
|
|
779
|
+
async () => text(listComponents(data))
|
|
780
|
+
);
|
|
781
|
+
server.registerTool(
|
|
782
|
+
"get_component_props",
|
|
783
|
+
{
|
|
784
|
+
title: "Get component props",
|
|
785
|
+
description: "Exact props of a Becket component (TypeScript declarations) and its recipe variant values. Accepts a component or part name, e.g. Button, CardHeader, SearchIcon.",
|
|
786
|
+
inputSchema: { name: z.string().describe('Component or part name, e.g. "Card" or "CardHeader"') },
|
|
787
|
+
annotations: readOnly
|
|
788
|
+
},
|
|
789
|
+
async ({ name }) => text(componentProps(data, name))
|
|
790
|
+
);
|
|
791
|
+
server.registerTool(
|
|
792
|
+
"get_component_example",
|
|
793
|
+
{
|
|
794
|
+
title: "Get component examples",
|
|
795
|
+
description: "Usage examples for a Becket component (its Storybook stories). Optionally pick one story by name.",
|
|
796
|
+
inputSchema: {
|
|
797
|
+
name: z.string().describe('Component name, e.g. "Dialog"'),
|
|
798
|
+
story: z.string().optional().describe('Story name, e.g. "Open"')
|
|
799
|
+
},
|
|
800
|
+
annotations: readOnly
|
|
801
|
+
},
|
|
802
|
+
async ({ name, story }) => text(componentExample(data, name, story))
|
|
803
|
+
);
|
|
804
|
+
server.registerTool(
|
|
805
|
+
"get_theme",
|
|
806
|
+
{
|
|
807
|
+
title: "Get theme tokens",
|
|
808
|
+
description: "Becket design tokens with dark and light values: colors, spacing, radii, sizes, font-sizes, shadows.",
|
|
809
|
+
inputSchema: {
|
|
810
|
+
group: z.enum(["colors", "spacing", "radii", "sizes", "font-sizes", "shadows"]).optional().describe("One token group; omit for all")
|
|
811
|
+
},
|
|
812
|
+
annotations: readOnly
|
|
813
|
+
},
|
|
814
|
+
async ({ group }) => text(theme(data, group))
|
|
815
|
+
);
|
|
816
|
+
server.registerTool(
|
|
817
|
+
"get_guidelines",
|
|
818
|
+
{
|
|
819
|
+
title: "Get the Becket app-code guide",
|
|
820
|
+
description: "Rules for writing app code with Becket: which component replaces each raw element, props-then-tokens styling, abstraction, state, accessibility. Read before writing UI.",
|
|
821
|
+
inputSchema: {
|
|
822
|
+
topic: z.string().optional().describe('Section filter, e.g. "component", "tokens", "accessibility", "example", "checklist"')
|
|
823
|
+
},
|
|
824
|
+
annotations: readOnly
|
|
825
|
+
},
|
|
826
|
+
async ({ topic }) => text(guidelines(data, topic))
|
|
827
|
+
);
|
|
828
|
+
server.registerTool(
|
|
829
|
+
"review_usage",
|
|
830
|
+
{
|
|
831
|
+
title: "Review Becket usage",
|
|
832
|
+
description: "Check React code against the Becket app-code guide: raw layout/text/controls, literal colors, pixel spacing, recipe classes, Chakra imports, unknown exports. Run before finishing.",
|
|
833
|
+
inputSchema: { code: z.string().describe("The TSX/JSX source to review") },
|
|
834
|
+
annotations: readOnly
|
|
835
|
+
},
|
|
836
|
+
async ({ code }) => text(formatReview(reviewUsage(code, data)))
|
|
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
|
+
);
|
|
873
|
+
return server;
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
// src/server.ts
|
|
877
|
+
await createServer().connect(new StdioServerTransport());
|
|
878
|
+
//# sourceMappingURL=server.js.map
|