@prismora/mcp 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 Aravind Kumar and Prismora contributors
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,12 @@
1
- # Temporary Holding Version
1
+ # @prismora/mcp
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
+ Prismora MCP server: component APIs, tokens, theme generation and markup validation for AI coding agents.
4
+
5
+ ```sh
6
+ claude mcp add prismora -- npx -y @prismora/mcp
7
+ ```
8
+
9
+ Any MCP client works: run `npx -y @prismora/mcp` as a stdio server. Tools: `list_components`, `get_component`,
10
+ `search_tokens`, `generate_theme`, `validate_markup`, `scaffold_page` and more.
11
+
12
+ Documentation: [prismora.design/docs/ai](https://prismora.design/docs/ai) · Part of [Prismora](https://github.com/axxra/prismora), one seed, every theme. MIT licence.
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ /** Command-line entry of the MCP server (stdio). `npx @prismora/mcp` or `bunx @prismora/mcp`. */
3
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
+ import { createServer } from './server.js';
5
+ await createServer().connect(new StdioServerTransport());
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env bun
2
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
+ export declare function createServer(): McpServer;
package/dist/server.js ADDED
@@ -0,0 +1,110 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Prismora MCP server (stdio).
4
+ * claude mcp add prismora -- bunx @prismora/mcp
5
+ */
6
+ import { createRequire } from 'node:module';
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
9
+ import { z } from 'zod';
10
+ import { FRAMEWORKS, PATTERN_IDS, SITE, generateTheme, getComponent, importThemeUrl, listComponents, scaffoldPage, searchTokens, validateMarkup, } from './tools.js';
11
+ const framework = z.enum(FRAMEWORKS).default('html').describe('Output flavour: html, react, vue, svelte, solid or angular.');
12
+ const json = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] });
13
+ const fail = (e) => ({ isError: true, content: [{ type: 'text', text: e instanceof Error ? e.message : String(e) }] });
14
+ export function createServer() {
15
+ const server = new McpServer({ name: 'prismora', version: createRequire(import.meta.url)('../package.json').version }, {
16
+ instructions: `Prismora is a framework-agnostic design system (<pm-*> web components + --pm-* tokens, wrappers for React/Vue/Svelte/Solid).
17
+ Workflow: list_components → get_component (with your framework) → write markup → validate_markup. Never hard-code colours; use search_tokens.
18
+ Shared attributes on every component: variant, tone, size, surface, radius, density, motion. Docs: ${SITE}/llms.txt`,
19
+ });
20
+ const ro = { readOnlyHint: true, openWorldHint: false };
21
+ const tool = server.registerTool.bind(server);
22
+ tool('list_components', {
23
+ title: 'List components',
24
+ description: 'All Prismora components with tag, wrapper name, category and one-line summary.',
25
+ annotations: ro,
26
+ }, async () => json(listComponents()));
27
+ tool('get_component', {
28
+ title: 'Get component API',
29
+ description: 'Full API (attributes with enums/defaults, events, slots, CSS parts, methods) plus an idiomatic example for the requested framework.',
30
+ inputSchema: { name: z.string().describe('Tag or name: "pm-button", "button", "Button", "RadioGroup"…'), framework },
31
+ annotations: ro,
32
+ }, async ({ name, framework: fw }) => {
33
+ try {
34
+ return json(getComponent(name, fw));
35
+ }
36
+ catch (e) {
37
+ return fail(e);
38
+ }
39
+ });
40
+ tool('search_tokens', {
41
+ title: 'Search design tokens',
42
+ description: 'Find --pm-* CSS custom properties by name or purpose (e.g. "muted text", "card background", "danger border", "spacing", "focus ring").',
43
+ inputSchema: { query: z.string(), limit: z.number().int().min(1).max(100).default(25) },
44
+ annotations: ro,
45
+ }, async ({ query, limit }) => json(searchTokens(query, limit)));
46
+ tool('generate_theme', {
47
+ title: 'Generate theme',
48
+ description: 'Generate theme CSS from a seed colour, with a WCAG contrast audit and a generator share URL. Same engine as the online generator.',
49
+ inputSchema: {
50
+ seed: z.string().describe('Brand colour: hex, rgb(), hsl() or oklch().'),
51
+ name: z.string().optional(),
52
+ secondary: z.string().optional(),
53
+ harmony: z.enum(['mono', 'analogous', 'complementary', 'triadic', 'split']).optional(),
54
+ neutralChroma: z.number().min(0).max(0.05).optional(),
55
+ contrast: z.enum(['normal', 'more']).optional(),
56
+ surface: z.enum(['flat', 'outline', 'gradient', 'glass', 'neumorphic']).optional(),
57
+ radius: z.enum(['none', 'sharp', 'rounded', 'soft', 'pill']).optional(),
58
+ density: z.enum(['compact', 'comfortable', 'spacious']).optional(),
59
+ motion: z.enum(['none', 'reduced', 'full']).optional(),
60
+ themes: z.record(z.string(), z.object({ seed: z.string().optional(), scheme: z.enum(['both', 'light', 'dark']).optional() }).passthrough()).optional()
61
+ .describe('Extra named themes, e.g. { "midnight": { "seed": "#8b5cf6", "scheme": "dark" } }'),
62
+ includeCss: z.boolean().default(true),
63
+ },
64
+ annotations: ro,
65
+ }, async ({ includeCss, ...config }) => {
66
+ try {
67
+ const r = await generateTheme(config);
68
+ return json({ ...r, css: includeCss ? r.css : `(${r.css.length} chars omitted)` });
69
+ }
70
+ catch (e) {
71
+ return fail(e);
72
+ }
73
+ });
74
+ tool('import_theme_url', {
75
+ title: 'Import generator link',
76
+ description: `Turn a theme generator share link (${SITE}/generator#t=1.…) or bare code into its config and CSS.`,
77
+ inputSchema: { url: z.string() },
78
+ annotations: ro,
79
+ }, async ({ url }) => {
80
+ try {
81
+ return json(await importThemeUrl(url));
82
+ }
83
+ catch (e) {
84
+ return fail(e);
85
+ }
86
+ });
87
+ tool('validate_markup', {
88
+ title: 'Validate markup',
89
+ description: 'Check HTML or JSX using Prismora: unknown tags, invalid attribute values, missing labels, broken id references, hard-coded colours.',
90
+ inputSchema: { markup: z.string() },
91
+ annotations: ro,
92
+ }, async ({ markup }) => json(validateMarkup(markup)));
93
+ tool('scaffold_page', {
94
+ title: 'Scaffold page',
95
+ description: `Starter page built from Prismora components. Patterns: ${PATTERN_IDS.join(', ')}.`,
96
+ inputSchema: { pattern: z.enum(PATTERN_IDS), framework },
97
+ annotations: ro,
98
+ }, async ({ pattern, framework: fw }) => {
99
+ try {
100
+ return json(scaffoldPage(pattern, fw));
101
+ }
102
+ catch (e) {
103
+ return fail(e);
104
+ }
105
+ });
106
+ return server;
107
+ }
108
+ if (import.meta.main) {
109
+ await createServer().connect(new StdioServerTransport());
110
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Pure tool implementations shared by the MCP server and the `prismora` CLI.
3
+ * No I/O here: everything is derived from components.json, the catalog and @prismora/theme.
4
+ */
5
+ import { COMPONENTS, type ApiComponent } from '@prismora/elements/manifest';
6
+ import { FRAMEWORKS, type Framework } from '@prismora/elements/catalog';
7
+ import { type ThemeConfig } from '@prismora/theme';
8
+ export declare const SITE = "https://prismora.design";
9
+ export type { ApiAttribute, ApiComponent } from '@prismora/elements/manifest';
10
+ export { COMPONENTS };
11
+ /** Accepts `pm-button`, `button`, `Button`, `ButtonGroup`, `button-group`. */
12
+ export declare function findComponent(name: string): ApiComponent | undefined;
13
+ export declare function listComponents(): {
14
+ summary: string | undefined;
15
+ formAssociated: boolean;
16
+ childOf?: string | undefined;
17
+ tag: string;
18
+ name: string;
19
+ category: "Actions" | "Forms" | "Display" | "Data" | "Overlays" | "Navigation";
20
+ }[];
21
+ export declare function getComponent(name: string, framework?: Framework): {
22
+ children: string[];
23
+ docs: string;
24
+ framework: Framework;
25
+ example: string | undefined;
26
+ events: {
27
+ prop: string;
28
+ name: string;
29
+ description?: string;
30
+ }[];
31
+ childOf?: string | undefined;
32
+ attributes: import("@prismora/elements/manifest").ApiAttribute[];
33
+ contextAttributes: string[];
34
+ category: "Actions" | "Forms" | "Display" | "Data" | "Overlays" | "Navigation" | undefined;
35
+ tag: string;
36
+ className: string;
37
+ module: string;
38
+ description: string;
39
+ formAssociated: boolean;
40
+ slots: import("@prismora/elements/manifest").ApiMember[];
41
+ parts: import("@prismora/elements/manifest").ApiMember[];
42
+ methods: string[];
43
+ examples: string[];
44
+ };
45
+ export interface TokenInfo {
46
+ name: string;
47
+ value: string;
48
+ category: string;
49
+ }
50
+ export declare function tokenIndex(): TokenInfo[];
51
+ export declare function searchTokens(query: string, limit?: number): TokenInfo[];
52
+ export declare function auditSummary(config: ThemeConfig): {
53
+ checks: number;
54
+ failures: {
55
+ theme: string;
56
+ mode: "light" | "dark";
57
+ fg: string;
58
+ bg: string;
59
+ ratio: number;
60
+ required: number;
61
+ }[];
62
+ };
63
+ export declare function generateTheme(config: Partial<ThemeConfig> & {
64
+ seed: string;
65
+ }): Promise<{
66
+ config: ThemeConfig;
67
+ css: string;
68
+ audit: {
69
+ checks: number;
70
+ failures: {
71
+ theme: string;
72
+ mode: "light" | "dark";
73
+ fg: string;
74
+ bg: string;
75
+ ratio: number;
76
+ required: number;
77
+ }[];
78
+ };
79
+ shareUrl: string;
80
+ }>;
81
+ export declare function importThemeUrl(urlOrCode: string): Promise<{
82
+ config: ThemeConfig;
83
+ css: string;
84
+ audit: {
85
+ checks: number;
86
+ failures: {
87
+ theme: string;
88
+ mode: "light" | "dark";
89
+ fg: string;
90
+ bg: string;
91
+ ratio: number;
92
+ required: number;
93
+ }[];
94
+ };
95
+ }>;
96
+ export interface Issue {
97
+ level: 'error' | 'warning';
98
+ line: number;
99
+ message: string;
100
+ tag?: string;
101
+ }
102
+ /** Static checks for agent-generated markup (HTML or JSX-ish): unknown tags, bad enum values, missing labels, hard-coded colours. */
103
+ export declare function validateMarkup(markup: string): {
104
+ valid: boolean;
105
+ errors: number;
106
+ warnings: number;
107
+ issues: Issue[];
108
+ };
109
+ export declare function scaffoldPage(pattern: string, framework?: Framework): {
110
+ id: string;
111
+ title: string;
112
+ description: string;
113
+ framework: Framework;
114
+ setup: string;
115
+ code: string;
116
+ };
117
+ export declare const PATTERN_IDS: string[];
118
+ export { FRAMEWORKS, type Framework };
package/dist/tools.js ADDED
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Pure tool implementations shared by the MCP server and the `prismora` CLI.
3
+ * No I/O here: everything is derived from components.json, the catalog and @prismora/theme.
4
+ */
5
+ import { COMPONENTS } from '@prismora/elements/manifest';
6
+ import { CATALOG, FRAMEWORKS, catalogEntry, pascalName, snippet } from '@prismora/elements/catalog';
7
+ import { PATTERNS } from '@prismora/elements/patterns';
8
+ import { DEFAULT_THEME, auditTheme, buildThemeCss, decodeTheme, encodeTheme, themeParamFromUrl, } from '@prismora/theme';
9
+ export const SITE = 'https://prismora.design';
10
+ export { COMPONENTS };
11
+ /** Accepts `pm-button`, `button`, `Button`, `ButtonGroup`, `button-group`. */
12
+ export function findComponent(name) {
13
+ const n = name.trim().replace(/^<|>$/g, '');
14
+ const kebab = n.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
15
+ const tag = kebab.startsWith('pm-') ? kebab : `pm-${kebab}`;
16
+ return COMPONENTS.find((c) => c.tag === tag);
17
+ }
18
+ /* ------------------------------------------------------------------ */
19
+ export function listComponents() {
20
+ return CATALOG.map((e) => {
21
+ const c = COMPONENTS.find((x) => x.tag === e.tag);
22
+ return {
23
+ tag: e.tag,
24
+ name: pascalName(e.tag),
25
+ category: e.category,
26
+ ...(e.childOf && { childOf: e.childOf }),
27
+ summary: c.description.split('\n')[0],
28
+ formAssociated: c.formAssociated,
29
+ };
30
+ });
31
+ }
32
+ /* ------------------------------------------------------------------ */
33
+ export function getComponent(name, framework = 'html') {
34
+ const c = findComponent(name);
35
+ if (!c) {
36
+ const suggestions = COMPONENTS.filter((x) => x.tag.includes(name.toLowerCase().replace(/^pm-/, ''))).map((x) => x.tag);
37
+ throw new Error(`Unknown component "${name}".${suggestions.length ? ` Did you mean ${suggestions.join(', ')}?` : ''} Use list_components.`);
38
+ }
39
+ const entry = catalogEntry(c.tag);
40
+ const parent = entry?.childOf ? catalogEntry(entry.childOf) : undefined;
41
+ const demo = parent?.demo ?? entry?.demo;
42
+ return {
43
+ ...c,
44
+ attributes: c.attributes.filter((a) => !a.context),
45
+ contextAttributes: c.attributes.filter((a) => a.context).map((a) => a.name),
46
+ category: entry?.category,
47
+ ...(entry?.childOf && { childOf: entry.childOf }),
48
+ children: CATALOG.filter((e) => e.childOf === c.tag).map((e) => e.tag),
49
+ docs: `${SITE}/components/${(entry?.childOf ?? c.tag).slice(3)}`,
50
+ framework,
51
+ example: demo ? snippet(demo, framework) : undefined,
52
+ events: c.events.map((e) => ({ ...e, prop: framework === 'react' || framework === 'svelte' ? `on${e.name.split('-').map((p) => p[0].toUpperCase() + p.slice(1)).join('')}` : framework === 'solid' ? `on:${e.name}` : framework === 'angular' ? `(${e.name})` : framework === 'vue' ? `@${e.name}` : e.name })),
53
+ };
54
+ }
55
+ const CATEGORY_RULES = [
56
+ [/^--pm-color-/, 'semantic colour'],
57
+ [/^--pm-(accent|secondary|neutral|success|warning|danger|info)-\d+$/, 'colour scale'],
58
+ [/^--pm-tone-/, 'tone context'],
59
+ [/^--pm-sf-/, 'surface'],
60
+ [/^--pm-space-/, 'space'],
61
+ [/^--pm-radius-/, 'radius'],
62
+ [/^--pm-font-size-/, 'type size'],
63
+ [/^--pm-font-/, 'font'],
64
+ [/^--pm-line-height-/, 'line height'],
65
+ [/^--pm-elevation-|^--pm-shadow-/, 'elevation'],
66
+ [/^--pm-(duration|ease)-/, 'motion'],
67
+ [/^--pm-z-/, 'z-index'],
68
+ [/^--pm-control-height-/, 'control size'],
69
+ [/^--pm-default-/, 'component default'],
70
+ ];
71
+ let tokenCache;
72
+ export function tokenIndex() {
73
+ if (tokenCache)
74
+ return tokenCache;
75
+ const css = buildThemeCss(DEFAULT_THEME, { layer: false });
76
+ const seen = new Map();
77
+ for (const m of css.matchAll(/(--pm-[\w-]+):\s*([^;]+);/g)) {
78
+ const name = m[1];
79
+ if (seen.has(name))
80
+ continue;
81
+ const category = CATEGORY_RULES.find(([re]) => re.test(name))?.[1] ?? 'other';
82
+ seen.set(name, { name, value: m[2].trim().replace(/\s+/g, ' ').slice(0, 160), category });
83
+ }
84
+ for (const k of ['solid', 'solid-hover', 'on-solid', 'soft', 'soft-hover', 'soft-active', 'border', 'border-strong', 'text', 'text-strong']) {
85
+ seen.set(`--pm-tone-${k}`, { name: `--pm-tone-${k}`, value: `var(--pm-color-<tone>-${k})`, category: 'tone context' });
86
+ }
87
+ tokenCache = [...seen.values()];
88
+ return tokenCache;
89
+ }
90
+ const SYNONYMS = {
91
+ background: ['bg'], text: ['fg', 'text'], foreground: ['fg'], primary: ['accent'], brand: ['accent'], error: ['danger'],
92
+ gap: ['space'], spacing: ['space'], padding: ['space'], margin: ['space'], corner: ['radius'], rounded: ['radius'],
93
+ shadow: ['elevation', 'shadow'], animation: ['duration', 'ease'], transition: ['duration', 'ease'], font: ['font'],
94
+ outline: ['border', 'ring'], focus: ['ring'], hover: ['hover'], muted: ['muted'], card: ['surface', 'sf'],
95
+ };
96
+ export function searchTokens(query, limit = 25) {
97
+ const words = query.toLowerCase().split(/[\s,]+/).filter(Boolean);
98
+ const terms = words.flatMap((w) => [w, ...(SYNONYMS[w] ?? [])]);
99
+ const scored = tokenIndex().map((t) => {
100
+ const hay = `${t.name} ${t.category}`.toLowerCase();
101
+ let score = 0;
102
+ for (const term of terms)
103
+ if (hay.includes(term))
104
+ score += t.name.includes(term) ? 2 : 1;
105
+ if (words.every((w) => hay.includes(w)))
106
+ score += 3;
107
+ return { t, score };
108
+ });
109
+ return scored.filter((s) => s.score > 0).sort((a, b) => b.score - a.score || a.t.name.length - b.t.name.length).slice(0, limit).map((s) => s.t);
110
+ }
111
+ /* ------------------------------------------------------------------ */
112
+ export function auditSummary(config) {
113
+ const groups = auditTheme(config);
114
+ const failures = groups.flatMap((g) => g.checks.filter((c) => !c.pass).map((c) => ({ theme: g.theme, mode: g.mode, fg: c.fg, bg: c.bg, ratio: +c.ratio.toFixed(2), required: c.required })));
115
+ return { checks: groups.reduce((n, g) => n + g.checks.length, 0), failures };
116
+ }
117
+ export async function generateTheme(config) {
118
+ const full = { ...DEFAULT_THEME, ...config };
119
+ const code = await encodeTheme(full);
120
+ return {
121
+ config: full,
122
+ css: buildThemeCss(full),
123
+ audit: auditSummary(full),
124
+ shareUrl: `${SITE}/generator#t=${code}`,
125
+ };
126
+ }
127
+ export async function importThemeUrl(urlOrCode) {
128
+ const code = /^https?:/.test(urlOrCode) ? themeParamFromUrl(urlOrCode) : urlOrCode.replace(/^#?t=/, '');
129
+ if (!code)
130
+ throw new Error('No theme found in that URL (expected …/generator#t=1.xxxxx).');
131
+ const config = await decodeTheme(code);
132
+ return { config, css: buildThemeCss(config), audit: auditSummary(config) };
133
+ }
134
+ const GLOBAL_ATTRS = new Set([
135
+ 'id', 'class', 'style', 'slot', 'hidden', 'title', 'lang', 'dir', 'tabindex', 'role', 'part', 'exportparts', 'inert', 'autofocus',
136
+ 'popover', 'popovertarget', 'popovertargetaction', 'commandfor', 'command', 'interestfor', 'is', 'translate', 'draggable', 'key', 'ref',
137
+ ]);
138
+ const LABELLED = new Set(['pm-input', 'pm-textarea', 'pm-select', 'pm-slider', 'pm-radio-group']);
139
+ const TEXT_LABELLED = new Set(['pm-checkbox', 'pm-switch']);
140
+ const HARD_COLOUR = /#[0-9a-f]{3,8}\b|\b(rgb|rgba|hsl|hsla|oklch|oklab|lab|lch)\(/i;
141
+ /**
142
+ * Opening tags with their attributes. Values may be quoted, or {…} expressions with nested braces and strings
143
+ * (JSX `columns={[{"key":"a"}]}`, Svelte `label={"{count} new"}`), which a regular expression cannot match.
144
+ */
145
+ function* openTags(markup) {
146
+ const n = markup.length;
147
+ for (let i = markup.indexOf('<'); i !== -1; i = markup.indexOf('<', i + 1)) {
148
+ const name = /^<([A-Za-z][\w.-]*)/.exec(markup.slice(i, i + 200));
149
+ if (!name)
150
+ continue;
151
+ const attrs = new Map();
152
+ let j = i + name[0].length;
153
+ let ok = false;
154
+ while (j < n) {
155
+ while (j < n && /\s/.test(markup[j]))
156
+ j++;
157
+ if (markup[j] === '>' || markup.startsWith('/>', j)) {
158
+ ok = true;
159
+ break;
160
+ }
161
+ const an = /^[^\s=>/]+/.exec(markup.slice(j, j + 200));
162
+ if (!an)
163
+ break;
164
+ j += an[0].length;
165
+ if (markup[j] !== '=') {
166
+ attrs.set(an[0], true);
167
+ continue;
168
+ }
169
+ j++;
170
+ const q = markup[j];
171
+ if (q === '"' || q === "'") {
172
+ const end = markup.indexOf(q, j + 1);
173
+ if (end === -1)
174
+ break;
175
+ attrs.set(an[0], markup.slice(j + 1, end));
176
+ j = end + 1;
177
+ }
178
+ else if (q === '{') {
179
+ let depth = 0;
180
+ let k = j;
181
+ for (; k < n; k++) {
182
+ const ch = markup[k];
183
+ if (ch === '"' || ch === "'" || ch === '`') {
184
+ const e = markup.indexOf(ch, k + 1);
185
+ if (e === -1) {
186
+ k = n;
187
+ break;
188
+ }
189
+ k = e;
190
+ continue;
191
+ }
192
+ if (ch === '{')
193
+ depth++;
194
+ else if (ch === '}' && --depth === 0)
195
+ break;
196
+ }
197
+ if (k >= n)
198
+ break;
199
+ attrs.set(an[0], markup.slice(j, k + 1));
200
+ j = k + 1;
201
+ }
202
+ else {
203
+ const v = /^[^\s>]+/.exec(markup.slice(j, j + 500));
204
+ if (!v)
205
+ break;
206
+ attrs.set(an[0], v[0]);
207
+ j += v[0].length;
208
+ }
209
+ }
210
+ if (ok) {
211
+ const sc = markup[j] === '/';
212
+ yield { raw: name[1], index: i, end: j + (sc ? 2 : 1), selfClosing: sc, attrs };
213
+ }
214
+ }
215
+ }
216
+ /** Static checks for agent-generated markup (HTML or JSX-ish): unknown tags, bad enum values, missing labels, hard-coded colours. */
217
+ export function validateMarkup(markup) {
218
+ const issues = [];
219
+ const lineAt = (i) => markup.slice(0, i).split('\n').length;
220
+ const ids = new Set([...markup.matchAll(/\bid=["']([^"']+)["']/g)].map((m) => m[1]));
221
+ for (const { raw, index, end, selfClosing, attrs } of openTags(markup)) {
222
+ const line = lineAt(index);
223
+ // Map JSX wrapper names (Button) to tags (pm-button).
224
+ const isWrapper = /^[A-Z]/.test(raw) && findComponent(raw);
225
+ const tag = isWrapper ? findComponent(raw).tag : raw.toLowerCase();
226
+ const style = attrs.get('style');
227
+ if (typeof style === 'string' && HARD_COLOUR.test(style)) {
228
+ issues.push({ level: 'warning', line, tag, message: `Hard-coded colour in style on <${raw}>. Use --pm-* tokens (search_tokens) so themes and dark mode work.` });
229
+ }
230
+ if (tag === 'img' && !attrs.has('alt'))
231
+ issues.push({ level: 'error', line, tag, message: '<img> needs alt text (alt="" if decorative).' });
232
+ for (const ref of ['popovertarget', 'commandfor', 'for']) {
233
+ const v = attrs.get(ref);
234
+ if (typeof v === 'string' && !v.startsWith('{') && (tag.startsWith('pm-') || ref !== 'for') && !ids.has(v)) {
235
+ issues.push({ level: 'warning', line, tag, message: `${ref}="${v}" on <${raw}> refers to an id not found in this markup.` });
236
+ }
237
+ }
238
+ if (!tag.startsWith('pm-'))
239
+ continue;
240
+ const c = COMPONENTS.find((x) => x.tag === tag);
241
+ if (!c) {
242
+ const near = COMPONENTS.filter((x) => x.tag.split('-')[1]?.[0] === tag.split('-')[1]?.[0]).map((x) => x.tag).slice(0, 4);
243
+ issues.push({ level: 'error', line, tag, message: `Unknown element <${tag}>.${near.length ? ` Did you mean ${near.join(', ')}?` : ''}` });
244
+ continue;
245
+ }
246
+ for (const [name, value] of attrs) {
247
+ const lower = name.toLowerCase();
248
+ if (GLOBAL_ATTRS.has(lower) || lower.startsWith('aria-') || lower.startsWith('data-') || /^on[:\w-]/i.test(name) || /^(on|prop|attr|bind|use|class|style):/.test(name) || /^[@:#]/.test(name) || name === 'className' || name === 'v-model' || name.startsWith('v-'))
249
+ continue;
250
+ const kebab = name.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();
251
+ const a = c.attributes.find((x) => x.name === lower || x.name === kebab || x.property === name);
252
+ if (!a) {
253
+ issues.push({ level: 'warning', line, tag, message: `<${tag}> has no attribute "${name}". Known: ${c.attributes.filter((x) => !x.context).map((x) => x.name).join(', ') || '(context attributes only)'}.` });
254
+ continue;
255
+ }
256
+ if (typeof value !== 'string' || value.startsWith('{'))
257
+ continue;
258
+ if (a.type === 'enum' && a.values && !a.values.includes(value)) {
259
+ issues.push({ level: 'error', line, tag, message: `${a.name}="${value}" is not valid on <${tag}>. Use one of: ${a.values.join(', ')}.` });
260
+ }
261
+ if (a.type === 'boolean' && value === 'false') {
262
+ issues.push({ level: 'warning', line, tag, message: `${a.name}="false" still enables the boolean attribute in HTML. Remove the attribute instead.` });
263
+ }
264
+ if (a.type === 'json' && value.trimStart().startsWith('[')) {
265
+ try {
266
+ JSON.parse(value);
267
+ }
268
+ catch {
269
+ issues.push({ level: 'error', line, tag, message: `${a.name} on <${tag}> is not valid JSON. Set the ${a.property} property from JS, or fix the JSON (double-quoted keys and strings).` });
270
+ }
271
+ }
272
+ if (a.type === 'number' && value !== '' && Number.isNaN(Number(value))) {
273
+ issues.push({ level: 'error', line, tag, message: `${a.name} on <${tag}> expects a number, got "${value}".` });
274
+ }
275
+ }
276
+ const hasName = attrs.has('label') || attrs.has('aria-label') || attrs.has('aria-labelledby');
277
+ if (LABELLED.has(tag) && !hasName)
278
+ issues.push({ level: 'error', line, tag, message: `<${tag}> needs label="…" (use hide-label to hide it visually).` });
279
+ if (TEXT_LABELLED.has(tag) && !hasName && !selfClosing) {
280
+ const close = markup.indexOf(`</${raw}>`, index);
281
+ const inner = close > 0 ? markup.slice(end, close).replace(/<[^>]+>/g, '').trim() : '';
282
+ if (!inner)
283
+ issues.push({ level: 'error', line, tag, message: `<${tag}> needs a text label as its content or label="…".` });
284
+ }
285
+ if (tag === 'pm-button' && attrs.has('icon') && !hasName)
286
+ issues.push({ level: 'error', line, tag, message: 'Icon-only <pm-button icon> needs label="…" for its accessible name.' });
287
+ if (tag === 'pm-tooltip' && !attrs.has('for'))
288
+ issues.push({ level: 'error', line, tag, message: '<pm-tooltip> needs for="trigger-id".' });
289
+ }
290
+ const errors = issues.filter((i) => i.level === 'error').length;
291
+ return { valid: errors === 0, errors, warnings: issues.length - errors, issues };
292
+ }
293
+ /* ------------------------------------------------------------------ */
294
+ export function scaffoldPage(pattern, framework = 'html') {
295
+ const p = PATTERNS.find((x) => x.id === pattern);
296
+ if (!p)
297
+ throw new Error(`Unknown pattern "${pattern}". Available: ${PATTERNS.map((x) => x.id).join(', ')}.`);
298
+ const setup = {
299
+ html: "Run `npx prismora init` once, or load @prismora/css/dist/prismora.css and @prismora/elements/dist/prismora.standalone.js.",
300
+ react: "Run `npx prismora init` once, or import '@prismora/css/foundation.css' in your root (app/layout.tsx or main.tsx).",
301
+ vue: "Run `npx prismora init` once, or import '@prismora/css/foundation.css' in main.ts and set compilerOptions.isCustomElement: (t) => t.startsWith('pm-').",
302
+ svelte: "Run `npx prismora init` once, or import '@prismora/css/foundation.css' in src/routes/+layout.svelte.",
303
+ solid: "Run `npx prismora init` once, or import '@prismora/css/foundation.css' in index.tsx.",
304
+ angular: "Run `npx prismora init` once, or add @prismora/css/foundation.css to the styles in angular.json. For ngModel and reactive forms add imports: [FormsModule, ...PRISMORA_FORMS].",
305
+ };
306
+ const name = `${p.id.replace(/(^|-)(\w)/g, (_, __, c) => c.toUpperCase())}Page`;
307
+ return { id: p.id, title: p.title, description: p.description, framework, setup: setup[framework], code: snippet(p.html, framework, name) };
308
+ }
309
+ export const PATTERN_IDS = PATTERNS.map((p) => p.id);
310
+ export { FRAMEWORKS };
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "@prismora/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Model Context Protocol server for Prismora: component APIs, tokens, theme generation and markup validation for AI agents.",
5
+ "keywords": [
6
+ "prismora",
7
+ "design-system",
8
+ "mcp",
9
+ "model-context-protocol",
10
+ "ai"
11
+ ],
12
+ "homepage": "https://prismora.design",
13
+ "bugs": {
14
+ "url": "https://github.com/axxra/prismora/issues"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/axxra/prismora.git",
19
+ "directory": "packages/mcp"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Aravind Kumar",
23
+ "type": "module",
24
+ "main": "./dist/server.js",
25
+ "types": "./dist/server.d.ts",
26
+ "bin": {
27
+ "prismora-mcp": "./dist/bin.js"
28
+ },
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/server.d.ts",
32
+ "default": "./dist/server.js"
33
+ },
34
+ "./tools": {
35
+ "types": "./dist/tools.d.ts",
36
+ "default": "./dist/tools.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist"
41
+ ],
42
+ "dependencies": {
43
+ "@modelcontextprotocol/sdk": "^1.20.0",
44
+ "@prismora/color": "^0.1.0",
45
+ "@prismora/elements": "^0.1.0",
46
+ "@prismora/theme": "^0.1.0",
47
+ "zod": "^3.25.0"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ }
52
+ }