Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/css-api-resolver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@anthropic/helixir-core': minor
---

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.
198 changes: 198 additions & 0 deletions packages/core/src/handlers/css-api-resolver.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
/**
* CSS API Resolver — 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 vs invalid
* - Closest valid alternatives for typos/hallucinations
* - The component's full style API surface
*
* This is the anti-hallucination tool: agents call it to verify that every
* CSS reference actually exists on the target component before shipping code.
*/

import type { ComponentMetadata } from './cem.js';

// ─── Types ───────────────────────────────────────────────────────────────────

export interface ResolvedReference {
name: string;
valid: boolean;
description?: string;
suggestion?: string;
}

export interface ResolvedSection {
resolved: ResolvedReference[];
available: string[];
}

export interface ComponentApiSummary {
tagName: string;
partCount: number;
tokenCount: number;
slotCount: number;
hasStyleApi: boolean;
}

export interface CssApiResolution {
valid: boolean;
invalidCount: number;
parts: ResolvedSection;
tokens: ResolvedSection;
slots: ResolvedSection;
componentApi: ComponentApiSummary;
}

// ─── Levenshtein distance ────────────────────────────────────────────────────

function levenshtein(a: string, b: string): number {
const m = a.length;
const n = b.length;
const dp: number[][] = Array.from({ length: m + 1 }, () =>
Array.from({ length: n + 1 }, () => 0),
);

for (let i = 0; i <= m; i++) {
const row = dp[i];
if (row) row[0] = i;
}
for (let j = 0; j <= n; j++) {
const row = dp[0];
if (row) row[j] = j;
}

for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
const prevRow = dp[i - 1];
const currRow = dp[i];
if (prevRow && currRow) {
currRow[j] = Math.min(
(prevRow[j] ?? 0) + 1,
(currRow[j - 1] ?? 0) + 1,
(prevRow[j - 1] ?? 0) + cost,
);
}
}
}

const lastRow = dp[m];
return lastRow ? (lastRow[n] ?? 0) : 0;
}

function findClosest(name: string, candidates: string[], maxDistance = 3): string | undefined {
let best: string | undefined;
let bestDist = maxDistance + 1;
for (const c of candidates) {
const d = levenshtein(name, c);
if (d < bestDist) {
bestDist = d;
best = c;
}
}
return best;
}

// ─── Extractors ──────────────────────────────────────────────────────────────

function extractPartNames(css: string): string[] {
const seen = new Set<string>();
const re = /::part\(([^)]+)\)/g;
let match;
while ((match = re.exec(css)) !== null) {
const name = match[1];
if (name) seen.add(name.trim());
}
return [...seen];
}

function extractComponentTokenDeclarations(css: string): string[] {
// Match CSS custom property declarations (--name: value) that are
// set ON the component host selector, not var() references to global tokens
const seen = new Set<string>();
const re = /\s(--[\w-]+)\s*:/g;
let match;
while ((match = re.exec(css)) !== null) {
const name = match[1];
if (name) seen.add(name);
}
return [...seen];
}

function extractSlotNames(html: string): string[] {
const seen = new Set<string>();
const re = /\bslot\s*=\s*["']([^"']+)["']/g;
let match;
while ((match = re.exec(html)) !== null) {
const name = match[1];
if (name) seen.add(name);
}
return [...seen];
}

// ─── Main Entry Point ───────────────────────────────────────────────────────

export function resolveCssApi(
css: string,
meta: ComponentMetadata,
html?: string,
): CssApiResolution {
const availableParts = meta.cssParts.map((p) => p.name);
const availableTokens = meta.cssProperties.map((p) => p.name);
const availableSlots = meta.slots.map((s) => s.name);

// Resolve parts
const usedParts = extractPartNames(css);
const resolvedParts: ResolvedReference[] = usedParts.map((name) => {
const part = meta.cssParts.find((p) => p.name === name);
if (part) {
return { name, valid: true, description: part.description };
}
const suggestion = findClosest(name, availableParts);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});

// Resolve tokens — only validate component-scoped custom properties
const usedTokens = extractComponentTokenDeclarations(css);
const resolvedTokens: ResolvedReference[] = usedTokens.map((name) => {
const token = meta.cssProperties.find((p) => p.name === name);
if (token) {
return { name, valid: true, description: token.description };
}
const suggestion = findClosest(name, availableTokens);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});

// Resolve slots (from HTML if provided)
const usedSlots = html ? extractSlotNames(html) : [];
const resolvedSlots: ResolvedReference[] = usedSlots.map((name) => {
const slot = meta.slots.find((s) => s.name === name);
if (slot) {
return { name, valid: true, description: slot.description };
}
const suggestion = findClosest(name, availableSlots);
return { name, valid: false, ...(suggestion ? { suggestion } : {}) };
});

const invalidCount =
resolvedParts.filter((r) => !r.valid).length +
resolvedTokens.filter((r) => !r.valid).length +
resolvedSlots.filter((r) => !r.valid).length;

return {
valid: invalidCount === 0,
invalidCount,
parts: { resolved: resolvedParts, available: availableParts },
tokens: { resolved: resolvedTokens, available: availableTokens },
slots: { resolved: resolvedSlots, available: availableSlots },
componentApi: {
tagName: meta.tagName,
partCount: meta.cssParts.length,
tokenCount: meta.cssProperties.length,
slotCount: meta.slots.length,
hasStyleApi:
meta.cssParts.length > 0 || meta.cssProperties.length > 0 || meta.slots.length > 0,
},
};
}
43 changes: 43 additions & 0 deletions packages/core/src/tools/styling.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { checkCssShorthand } from '../handlers/shorthand-checker.js';
import { checkColorContrast } from '../handlers/color-contrast-checker.js';
import { checkTransitionAnimation } from '../handlers/transition-checker.js';
import { checkShadowDomJs } from '../handlers/shadow-dom-js-checker.js';
import { resolveCssApi } from '../handlers/css-api-resolver.js';
import { createErrorResponse, createSuccessResponse } from '../shared/mcp-helpers.js';
import type { MCPToolResult } from '../shared/mcp-helpers.js';
import { handleToolError } from '../shared/error-handling.js';
Expand Down Expand Up @@ -159,6 +160,12 @@ const ValidateComponentCodeArgsSchema = z.object({
framework: z.enum(['react', 'vue', 'angular', 'html']).optional(),
});

const ResolveCssApiArgsSchema = z.object({
cssText: z.string(),
tagName: z.string(),
htmlText: z.string().optional(),
});

export const STYLING_TOOL_DEFINITIONS = [
{
name: 'diagnose_styling',
Expand Down Expand Up @@ -752,6 +759,35 @@ export const STYLING_TOOL_DEFINITIONS = [
required: ['codeText'],
},
},
{
name: 'resolve_css_api',
description:
'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.',
inputSchema: {
type: 'object' as const,
properties: {
libraryId: {
type: 'string',
description:
'Optional library ID to target a specific loaded library instead of the default.',
},
cssText: {
type: 'string',
description: 'The CSS code to resolve against the component API.',
},
tagName: {
type: 'string',
description: 'The custom element tag name (e.g. "sl-dialog").',
},
htmlText: {
type: 'string',
description:
'Optional HTML code to validate slot attribute references against the component API.',
},
},
required: ['cssText', 'tagName'],
},
},
];

/**
Expand Down Expand Up @@ -931,6 +967,13 @@ export function handleStylingCall(
return createSuccessResponse(JSON.stringify(result, null, 2));
}

if (name === 'resolve_css_api') {
const { cssText, tagName, htmlText } = ResolveCssApiArgsSchema.parse(args);
const meta = parseCem(tagName, cem);
const result = resolveCssApi(cssText, meta, htmlText);
return createSuccessResponse(JSON.stringify(result, null, 2));
}

return createErrorResponse(`Unknown styling tool: ${name}`);
} catch (err) {
const mcpErr = handleToolError(err);
Expand Down
Loading
Loading