Skip to content

Commit 09b9a98

Browse files
authored
Merge pull request #162: feat: add resolve_css_api anti-hallucination tool
feat: add resolve_css_api anti-hallucination tool
2 parents d294078 + 9b96f43 commit 09b9a98

File tree

4 files changed

+479
-0
lines changed

4 files changed

+479
-0
lines changed

.changeset/css-api-resolver.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@anthropic/helixir-core': minor
3+
---
4+
5+
Add `resolve_css_api` MCP tool — resolves every `::part()`, CSS custom property, and slot reference against actual component CEM data. Catches hallucinated part names, invalid token names, and unknown slot names with fuzzy match suggestions.
Lines changed: 198 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,198 @@
1+
/**
2+
* CSS API Resolver — resolves every ::part(), CSS custom property, and slot
3+
* reference in agent-generated code against the actual component CEM data.
4+
*
5+
* Returns a structured report showing:
6+
* - Which references are valid vs invalid
7+
* - Closest valid alternatives for typos/hallucinations
8+
* - The component's full style API surface
9+
*
10+
* This is the anti-hallucination tool: agents call it to verify that every
11+
* CSS reference actually exists on the target component before shipping code.
12+
*/
13+
14+
import type { ComponentMetadata } from './cem.js';
15+
16+
// ─── Types ───────────────────────────────────────────────────────────────────
17+
18+
export interface ResolvedReference {
19+
name: string;
20+
valid: boolean;
21+
description?: string;
22+
suggestion?: string;
23+
}
24+
25+
export interface ResolvedSection {
26+
resolved: ResolvedReference[];
27+
available: string[];
28+
}
29+
30+
export interface ComponentApiSummary {
31+
tagName: string;
32+
partCount: number;
33+
tokenCount: number;
34+
slotCount: number;
35+
hasStyleApi: boolean;
36+
}
37+
38+
export interface CssApiResolution {
39+
valid: boolean;
40+
invalidCount: number;
41+
parts: ResolvedSection;
42+
tokens: ResolvedSection;
43+
slots: ResolvedSection;
44+
componentApi: ComponentApiSummary;
45+
}
46+
47+
// ─── Levenshtein distance ────────────────────────────────────────────────────
48+
49+
function levenshtein(a: string, b: string): number {
50+
const m = a.length;
51+
const n = b.length;
52+
const dp: number[][] = Array.from({ length: m + 1 }, () =>
53+
Array.from({ length: n + 1 }, () => 0),
54+
);
55+
56+
for (let i = 0; i <= m; i++) {
57+
const row = dp[i];
58+
if (row) row[0] = i;
59+
}
60+
for (let j = 0; j <= n; j++) {
61+
const row = dp[0];
62+
if (row) row[j] = j;
63+
}
64+
65+
for (let i = 1; i <= m; i++) {
66+
for (let j = 1; j <= n; j++) {
67+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
68+
const prevRow = dp[i - 1];
69+
const currRow = dp[i];
70+
if (prevRow && currRow) {
71+
currRow[j] = Math.min(
72+
(prevRow[j] ?? 0) + 1,
73+
(currRow[j - 1] ?? 0) + 1,
74+
(prevRow[j - 1] ?? 0) + cost,
75+
);
76+
}
77+
}
78+
}
79+
80+
const lastRow = dp[m];
81+
return lastRow ? (lastRow[n] ?? 0) : 0;
82+
}
83+
84+
function findClosest(name: string, candidates: string[], maxDistance = 3): string | undefined {
85+
let best: string | undefined;
86+
let bestDist = maxDistance + 1;
87+
for (const c of candidates) {
88+
const d = levenshtein(name, c);
89+
if (d < bestDist) {
90+
bestDist = d;
91+
best = c;
92+
}
93+
}
94+
return best;
95+
}
96+
97+
// ─── Extractors ──────────────────────────────────────────────────────────────
98+
99+
function extractPartNames(css: string): string[] {
100+
const seen = new Set<string>();
101+
const re = /::part\(([^)]+)\)/g;
102+
let match;
103+
while ((match = re.exec(css)) !== null) {
104+
const name = match[1];
105+
if (name) seen.add(name.trim());
106+
}
107+
return [...seen];
108+
}
109+
110+
function extractComponentTokenDeclarations(css: string): string[] {
111+
// Match CSS custom property declarations (--name: value) that are
112+
// set ON the component host selector, not var() references to global tokens
113+
const seen = new Set<string>();
114+
const re = /\s(--[\w-]+)\s*:/g;
115+
let match;
116+
while ((match = re.exec(css)) !== null) {
117+
const name = match[1];
118+
if (name) seen.add(name);
119+
}
120+
return [...seen];
121+
}
122+
123+
function extractSlotNames(html: string): string[] {
124+
const seen = new Set<string>();
125+
const re = /\bslot\s*=\s*["']([^"']+)["']/g;
126+
let match;
127+
while ((match = re.exec(html)) !== null) {
128+
const name = match[1];
129+
if (name) seen.add(name);
130+
}
131+
return [...seen];
132+
}
133+
134+
// ─── Main Entry Point ───────────────────────────────────────────────────────
135+
136+
export function resolveCssApi(
137+
css: string,
138+
meta: ComponentMetadata,
139+
html?: string,
140+
): CssApiResolution {
141+
const availableParts = meta.cssParts.map((p) => p.name);
142+
const availableTokens = meta.cssProperties.map((p) => p.name);
143+
const availableSlots = meta.slots.map((s) => s.name);
144+
145+
// Resolve parts
146+
const usedParts = extractPartNames(css);
147+
const resolvedParts: ResolvedReference[] = usedParts.map((name) => {
148+
const part = meta.cssParts.find((p) => p.name === name);
149+
if (part) {
150+
return { name, valid: true, description: part.description };
151+
}
152+
const suggestion = findClosest(name, availableParts);
153+
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
154+
});
155+
156+
// Resolve tokens — only validate component-scoped custom properties
157+
const usedTokens = extractComponentTokenDeclarations(css);
158+
const resolvedTokens: ResolvedReference[] = usedTokens.map((name) => {
159+
const token = meta.cssProperties.find((p) => p.name === name);
160+
if (token) {
161+
return { name, valid: true, description: token.description };
162+
}
163+
const suggestion = findClosest(name, availableTokens);
164+
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
165+
});
166+
167+
// Resolve slots (from HTML if provided)
168+
const usedSlots = html ? extractSlotNames(html) : [];
169+
const resolvedSlots: ResolvedReference[] = usedSlots.map((name) => {
170+
const slot = meta.slots.find((s) => s.name === name);
171+
if (slot) {
172+
return { name, valid: true, description: slot.description };
173+
}
174+
const suggestion = findClosest(name, availableSlots);
175+
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
176+
});
177+
178+
const invalidCount =
179+
resolvedParts.filter((r) => !r.valid).length +
180+
resolvedTokens.filter((r) => !r.valid).length +
181+
resolvedSlots.filter((r) => !r.valid).length;
182+
183+
return {
184+
valid: invalidCount === 0,
185+
invalidCount,
186+
parts: { resolved: resolvedParts, available: availableParts },
187+
tokens: { resolved: resolvedTokens, available: availableTokens },
188+
slots: { resolved: resolvedSlots, available: availableSlots },
189+
componentApi: {
190+
tagName: meta.tagName,
191+
partCount: meta.cssParts.length,
192+
tokenCount: meta.cssProperties.length,
193+
slotCount: meta.slots.length,
194+
hasStyleApi:
195+
meta.cssParts.length > 0 || meta.cssProperties.length > 0 || meta.slots.length > 0,
196+
},
197+
};
198+
}

packages/core/src/tools/styling.ts

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { checkCssShorthand } from '../handlers/shorthand-checker.js';
2727
import { checkColorContrast } from '../handlers/color-contrast-checker.js';
2828
import { checkTransitionAnimation } from '../handlers/transition-checker.js';
2929
import { checkShadowDomJs } from '../handlers/shadow-dom-js-checker.js';
30+
import { resolveCssApi } from '../handlers/css-api-resolver.js';
3031
import { createErrorResponse, createSuccessResponse } from '../shared/mcp-helpers.js';
3132
import type { MCPToolResult } from '../shared/mcp-helpers.js';
3233
import { handleToolError } from '../shared/error-handling.js';
@@ -159,6 +160,12 @@ const ValidateComponentCodeArgsSchema = z.object({
159160
framework: z.enum(['react', 'vue', 'angular', 'html']).optional(),
160161
});
161162

163+
const ResolveCssApiArgsSchema = z.object({
164+
cssText: z.string(),
165+
tagName: z.string(),
166+
htmlText: z.string().optional(),
167+
});
168+
162169
export const STYLING_TOOL_DEFINITIONS = [
163170
{
164171
name: 'diagnose_styling',
@@ -752,6 +759,35 @@ export const STYLING_TOOL_DEFINITIONS = [
752759
required: ['codeText'],
753760
},
754761
},
762+
{
763+
name: 'resolve_css_api',
764+
description:
765+
'Resolves every ::part(), CSS custom property, and slot reference in agent-generated code against the actual component CEM data. Returns a structured report showing which references are valid, which are hallucinated, and suggests the closest valid alternatives. Call this BEFORE shipping any CSS to verify that every part name, token name, and slot name actually exists on the target component.',
766+
inputSchema: {
767+
type: 'object' as const,
768+
properties: {
769+
libraryId: {
770+
type: 'string',
771+
description:
772+
'Optional library ID to target a specific loaded library instead of the default.',
773+
},
774+
cssText: {
775+
type: 'string',
776+
description: 'The CSS code to resolve against the component API.',
777+
},
778+
tagName: {
779+
type: 'string',
780+
description: 'The custom element tag name (e.g. "sl-dialog").',
781+
},
782+
htmlText: {
783+
type: 'string',
784+
description:
785+
'Optional HTML code to validate slot attribute references against the component API.',
786+
},
787+
},
788+
required: ['cssText', 'tagName'],
789+
},
790+
},
755791
];
756792

757793
/**
@@ -931,6 +967,13 @@ export function handleStylingCall(
931967
return createSuccessResponse(JSON.stringify(result, null, 2));
932968
}
933969

970+
if (name === 'resolve_css_api') {
971+
const { cssText, tagName, htmlText } = ResolveCssApiArgsSchema.parse(args);
972+
const meta = parseCem(tagName, cem);
973+
const result = resolveCssApi(cssText, meta, htmlText);
974+
return createSuccessResponse(JSON.stringify(result, null, 2));
975+
}
976+
934977
return createErrorResponse(`Unknown styling tool: ${name}`);
935978
} catch (err) {
936979
const mcpErr = handleToolError(err);

0 commit comments

Comments
 (0)