AI Best Practices
Learn best practices for integrating AI agents with Matrix UI components to build reliable, maintainable, and efficient applications.
AI-First Development
These practices are specifically designed for AI agents working with Matrix UI's MCP tools, but they also apply to human developers building AI-powered applications.
Core Principles
Validate Early and OftenCritical
Always validate before proceeding to the next step
Validation prevents cascading errors and ensures quality:
// Good: Validate at each step
const component = await matrix_get_component({ name: "Button" })
if (!component.success) return handleError(component.error)
const validation = await matrix_validate_usage({
component: "Button",
props: { variant: "primary" }
})
if (!validation.data.valid) return handleValidationErrors(validation.data.errors)
// Bad: Skip validation
const code = await matrix_generate_component({
component: "NonExistentComponent" // Will fail
})
Start Simple, Add ComplexityEssential
Begin with basic configurations and enhance incrementally
Build complexity gradually to avoid overwhelming configurations:
// Good: Start simple
const basicButton = await matrix_generate_component({
component: "Button",
config: { children: "Click me" }
})
// Then enhance
const enhancedButton = await matrix_generate_component({
component: "Button",
config: {
variant: "primary",
size: "lg",
children: "Click me",
onClick: "handleClick"
}
})
// Bad: Complex from the start
const overlyComplexButton = await matrix_generate_component({
component: "Button",
config: {
variant: "primary",
size: "lg",
className: "custom-btn hover:bg-blue-600 focus:ring-2",
onClick: "handleClick",
onHover: "handleHover",
// ... 20 more properties
}
})
Use Composition Over ConfigurationRecommended
Prefer combining simple components over complex configurations
Compound components are more maintainable than monolithic ones:
// Good: Use compound components
const userCard = await matrix_compose_layout({
layout: "flex",
components: [
{
component: "Card",
config: { className: "p-4" },
position: "container"
},
{
component: "Avatar",
config: { src: "user.avatar", size: "md" },
position: "start"
},
{
component: "CardContent",
config: { children: "userInfo" },
position: "center"
}
]
})
// Bad: Try to configure everything in one component
const monolithicCard = await matrix_generate_component({
component: "ComplexUserCard",
config: {
showAvatar: true,
avatarSize: "md",
avatarSrc: "user.avatar",
userName: "John Doe",
userRole: "Developer",
showActions: true,
primaryAction: "View Profile",
secondaryAction: "Send Message"
// ... many more props
}
})
Discovery Best Practices
Effective Component Search
// Good: Use descriptive, specific queries
const searchResults = await matrix_search_components({
query: "form input with validation and error display",
filters: {
category: "forms",
hasAccessibility: true,
isInteractive: true
}
})
// Good: Try multiple search strategies
const strategies = [
{ query: "data table with sorting", category: "data-display" },
{ query: "sortable table component", category: "layout" },
{ query: "table with column sorting", category: "ui" }
]
for (const strategy of strategies) {
const results = await matrix_search_components(strategy)
if (results.data.components.length > 0) {
return results.data.components[0] // Use first good result
}
}
// Bad: Vague search terms
const vague = await matrix_search_components({
query: "component" // Too generic
})
Component Selection Logic
// Prioritize components by criteria
function selectBestComponent(components, requirements) {
return components
.filter(c => meetsRequirements(c, requirements))
.sort((a, b) => {
// Prioritize by accessibility compliance
if (a.accessibility?.wcagLevel !== b.accessibility?.wcagLevel) {
const levels = { 'AAA': 3, 'AA': 2, 'A': 1 }
return levels[b.accessibility?.wcagLevel] - levels[a.accessibility?.wcagLevel]
}
// Then by component maturity (based on examples count)
return (b.examples?.length || 0) - (a.examples?.length || 0)
})[0]
}
// Use capability-based discovery for specific needs
const interactiveComponents = await matrix_find_by_capability({
capability: "interactive",
value: true,
category: "forms"
})
const responsiveComponents = await matrix_find_by_capability({
capability: "responsive",
value: true
})
Implementation Best Practices
Error State Handling
// Always include error states in component generation
const formWithErrors = await matrix_generate_component({
component: "Form",
config: {
fields: [
{
type: "email",
label: "Email",
required: true,
validation: {
pattern: "email",
errorMessage: "Please enter a valid email address"
}
}
],
errorDisplay: {
position: "below-field",
showIcon: true,
variant: "destructive"
},
submitErrorHandling: {
showAlert: true,
retryButton: true
}
}
})
// Include loading states for async operations
const dataTableWithLoading = await matrix_generate_component({
component: "DataTable",
config: {
columns: tableColumns,
loadingState: {
skeleton: true,
rowCount: 5,
showHeaders: true
},
emptyState: {
message: "No data available",
action: "Refresh",
icon: "Database"
}
}
})
Responsive Design
// Always consider responsive behavior
const responsiveLayout = await matrix_compose_layout({
layout: "grid",
components: [
{
component: "Card",
config: {
className: "col-span-1 md:col-span-2 lg:col-span-3",
title: "Main Content"
}
},
{
component: "Card",
config: {
className: "col-span-1",
title: "Sidebar"
}
}
],
responsive: true, // Enable responsive classes
breakpoints: {
sm: "grid-cols-1",
md: "grid-cols-3",
lg: "grid-cols-4"
}
})
// Use responsive component variants
const responsiveButton = await matrix_generate_component({
component: "Button",
config: {
size: "sm md:size-default lg:size-lg", // Responsive sizes
className: "w-full sm:w-auto" // Full width on mobile
}
})
Validation Best Practices
Comprehensive Validation Strategy
// Multi-layer validation approach
async function comprehensiveValidation(component, props, children, code) {
const results = {
usage: null,
accessibility: null,
theme: null,
suggestions: null
}
// 1. Basic usage validation
results.usage = await matrix_validate_usage({
component,
props,
children,
context: "production"
})
if (!results.usage.data.valid) {
return { valid: false, stage: "usage", ...results }
}
// 2. Accessibility validation
results.accessibility = await matrix_check_accessibility({
code,
level: "AA",
checks: ["aria-labels", "keyboard-nav", "color-contrast", "focus-visible"]
})
// 3. Theme compliance (non-blocking)
results.theme = await matrix_check_theme_compliance({
code,
strict: false // Warnings only
})
// 4. Get improvement suggestions
results.suggestions = await matrix_suggest_improvements({
code,
focus: ["accessibility", "performance", "best-practices"]
})
return {
valid: results.usage.data.valid && results.accessibility.data.compliant,
...results
}
}
Accessibility Validation Priorities
Critical (Must Fix)
missing-aria-labels
keyboard-inaccessible
color-contrast-fail
missing-alt-text
Important (Should Fix)
focus-not-visible
missing-descriptions
semantic-html-issues
aria-role-missing
Optional (Nice to Have)
redundant-aria
landmark-order
heading-structure
Performance Best Practices
Efficient MCP Tool Usage
// Good: Batch related operations
const [component, examples, props] = await Promise.all([
matrix_get_component({ name: "Button" }),
matrix_get_examples({ component: "Button", type: "advanced" }),
matrix_get_props({ component: "Button" })
])
// Good: Cache frequently used data
const componentCache = new Map()
async function getCachedComponent(name) {
if (componentCache.has(name)) {
return componentCache.get(name)
}
const component = await matrix_get_component({ name })
componentCache.set(name, component)
return component
}
// Bad: Sequential operations
const component = await matrix_get_component({ name: "Button" })
const examples = await matrix_get_examples({ component: "Button" })
const props = await matrix_get_props({ component: "Button" })
// Bad: Redundant requests
const buttonDetails1 = await matrix_get_component({ name: "Button" })
const buttonDetails2 = await matrix_get_component({ name: "Button" }) // Duplicate!
Request Optimization
// Use specific queries to reduce response size
const lightweightComponent = await matrix_get_component({
name: "Button",
includeExamples: false, // Skip if not needed
includeProps: true,
includeAccessibility: false
})
// Limit search results appropriately
const searchResults = await matrix_search_components({
query: "form components",
filters: { category: "forms" },
limit: 5 // Only get top 5 results
})
// Use appropriate validation levels
const quickValidation = await matrix_check_accessibility({
code: componentCode,
level: "A", // Use A instead of AAA for initial checks
checks: ["aria-labels", "keyboard-nav"] // Focus on critical checks
})
Error Handling Best Practices
Graceful Degradation
// Implement fallback strategies
async function robustComponentGeneration(componentName, config) {
try {
// Primary attempt
return await matrix_generate_component({
component: componentName,
config
})
} catch (primaryError) {
console.warn(`Primary generation failed: ${primaryError.message}`)
try {
// Fallback 1: Search for alternatives
const alternatives = await matrix_search_components({
query: componentName,
limit: 1
})
if (alternatives.data.components.length > 0) {
return await matrix_generate_component({
component: alternatives.data.components[0].name,
config
})
}
} catch (fallbackError) {
console.warn(`Fallback generation failed: ${fallbackError.message}`)
}
// Fallback 2: Basic HTML element
return {
success: true,
data: {
code: `<div className="fallback-component">${config.children || 'Component'}</div>`,
props: config,
warnings: [`Used fallback for ${componentName}`]
}
}
}
}
Validation Error Recovery
// Auto-fix common validation errors
async function autoFixValidationErrors(component, props, children) {
const validation = await matrix_validate_usage({ component, props, children })
if (!validation.data.valid) {
const fixedProps = { ...props }
// Auto-fix missing required props
validation.data.errors.forEach(error => {
if (error.type === 'missing-required-prop') {
switch (error.field) {
case 'children':
fixedProps.children = children || 'Default content'
break
case 'label':
fixedProps.label = `${component} label`
break
case 'id':
fixedProps.id = `${component.toLowerCase()}-${Date.now()}`
break
default:
fixedProps[error.field] = getDefaultValue(component, error.field)
}
}
})
// Re-validate with fixes
return await matrix_validate_usage({
component,
props: fixedProps,
children
})
}
return validation
}
Testing and Quality Assurance
Validation Test Suite
// Create comprehensive test scenarios
const testScenarios = [
{
name: "Basic Button",
component: "Button",
props: { children: "Click me" },
expectedValid: true
},
{
name: "Button with Invalid Variant",
component: "Button",
props: { variant: "invalid-variant", children: "Click me" },
expectedValid: false,
expectedErrors: ["invalid-prop-value"]
},
{
name: "Form without Required Props",
component: "Form",
props: {},
expectedValid: false,
expectedErrors: ["missing-required-prop"]
}
]
// Run validation tests
for (const scenario of testScenarios) {
const result = await matrix_validate_usage({
component: scenario.component,
props: scenario.props,
children: scenario.children
})
console.assert(
result.data.valid === scenario.expectedValid,
`Test "${scenario.name}" failed`
)
}
Security Considerations
Input Sanitization
- Always validate user input before passing to MCP tools
- Sanitize dynamic content in component children
- Avoid passing unsanitized HTML to component props
- Use TypeScript for compile-time prop validation
Generated Code Review
// Always review generated code for security issues
async function secureGeneration(component, config) {
const result = await matrix_generate_component({ component, config })
if (result.success) {
// Check for potential security issues
const securityIssues = [
/dangerouslySetInnerHTML/g,
/eval(/g,
/innerHTMLs*=/g,
/document.write/g
]
const hasSecurityIssues = securityIssues.some(pattern =>
pattern.test(result.data.code)
)
if (hasSecurityIssues) {
console.warn("Generated code contains potential security issues")
// Request safer alternative or apply fixes
}
}
return result
}
Development Checklist
✓ Validate components before generation
✓ Test with different configurations
✓ Check accessibility compliance
✓ Handle error cases gracefully
✓ Include loading and empty states
✓ Test responsive behavior
✓ Review generated code for security
Resources
MCP Tools Reference
Complete reference for all available MCP tools
AI Workflows
Learn structured workflows for AI development