npm package: @scarlet-mesh/mcp-accessibility
Description: Accessibility checker MCP server that analyzes code for WCAG 2.1 AA compliance and provides improvement suggestions
Author: Red Hat
Latest version: 1.0.0

# Accessibility MCP Server

## Overview

This comprehensive MCP (Model Context Protocol) server provides advanced accessibility analysis capabilities for web development. It analyzes code for WCAG 2.1 AA compliance, identifies accessibility issues, and provides actionable improvement suggestions to help achieve near-perfect accessibility scores.

## Features

### Core Features

- **WCAG 2.1 AA Compliance Checking**: Comprehensive analysis against Web Content Accessibility Guidelines
- **Universal Framework Support**: Analyze code from 20+ frontend frameworks and template engines
- **Accessibility Scoring**: Get numerical scores (0-100) with detailed breakdowns
- **Violation Detection**: Identify critical, serious, moderate, and minor accessibility issues
- **Actionable Suggestions**: Receive specific, prioritized improvement recommendations

### Advanced Features

- **Focus Area Analysis**: Target specific accessibility concerns (keyboard, screen-reader, color-contrast, structure)
- **Quick Checks**: Fast pattern-based analysis for common accessibility issues
- **Detailed Reporting**: Comprehensive reports with WCAG references and fix instructions
- **Smart Code Preprocessing**: Intelligent conversion of 20+ file formats to analyzable HTML
- **Integration with axe-core**: Leverages industry-standard accessibility testing engine
- **Template Engine Support**: Handlebars, Mustache, EJS, Pug, Twig, Blade, Razor, ERB, PHP, and more

## Tools

The server provides the following MCP tools:

### Primary Analysis Tools

- `analyze-accessibility`: Comprehensive accessibility analysis with WCAG 2.1 AA compliance checking
- `quick-accessibility-check`: Fast pattern-based check for common accessibility issues
- `suggest-accessibility-improvements`: Get targeted suggestions based on focus areas
- `fix-accessibility-issues`: **NEW!** Automatically fix common accessibility issues and return improved code
- `analyze-file-accessibility`: Instructions for analyzing specific project files

## Accessibility Standards

This server checks compliance against:

- **WCAG 2.1 Level A**: Basic accessibility requirements
- **WCAG 2.1 Level AA**: Standard accessibility requirements (recommended for most websites)
- **WCAG 2.1 Level AAA**: Enhanced accessibility requirements
- **Best Practices**: Industry-standard accessibility patterns

### Scoring System

- **Score 95-100**: WCAG AAA compliance (excellent accessibility)
- **Score 85-94**: WCAG AA compliance (good accessibility)
- **Score 70-84**: WCAG A compliance (basic accessibility)
- **Score 0-69**: Non-compliant (significant accessibility barriers)

## Setup

### Prerequisites

- Node.js (v18 or higher)
- An MCP client (e.g., a compatible AI tool or application)

### Installation

1. Navigate to the accessibility package directory:

   ```bash
   cd packages/accessibility
   ```

2. Install the dependencies:

   ```bash
   npm install
   ```

3. Build the server:
   ```bash
   npm run build
   ```

### Running the Server

1. Start the server:

   ```bash
   npm start
   ```

   The server will listen for MCP requests via standard input/output.

## Usage Examples

### Comprehensive Accessibility Analysis

Analyze code from any frontend framework or template engine for WCAG compliance:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "<div onClick={handleClick}>Click me</div>",
    "fileType": "jsx",
    "includeDetails": true
  }
}
```

**Sample Output:**

```
# Accessibility Analysis Report

**Accessibility Score: 75/100**
**WCAG Compliance Level: A**

## Issue Summary
- Total Issues: 2
- Critical: 0
- Serious: 1
- Moderate: 1
- Minor: 0

## Improvement Suggestions
- ⌨️ Ensure all interactive elements are keyboard accessible with proper focus management
- ♿ Review ARIA attributes - ensure they're used correctly and don't conflict with semantic HTML
- 🧪 Test with screen readers (NVDA, JAWS, VoiceOver) and keyboard-only navigation

## Detailed Violations

### 1. Interactive div elements must have an accessible role
**Impact:** SERIOUS
**Help:** Add an appropriate role attribute to make the element's purpose clear to assistive technologies
**Learn more:** https://dequeuniversity.com/rules/axe/4.10/button-name
```

### Quick Accessibility Check

For rapid feedback on common issues:

```json
{
  "tool_name": "quick-accessibility-check",
  "input": {
    "code": "<img src='photo.jpg'><input type='text'>"
  }
}
```

**Sample Output:**

```
# Quick Accessibility Check

**Score: 65/100**

## Issues Found
- ❌ Missing alt attributes on images
- ❌ Form inputs may be missing associated labels

💡 **Tip:** Use "analyze-accessibility" for comprehensive WCAG compliance checking.
```

### Focused Accessibility Improvements

Target specific accessibility areas:

```json
{
  "tool_name": "suggest-accessibility-improvements",
  "input": {
    "code": "<button style='color: #ccc; background: #ddd;'>Submit</button>",
    "fileType": "html",
    "focusArea": "color-contrast"
  }
}
```

### React Component Analysis

Analyze React/JSX components:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "function LoginForm() {\n  return (\n    <form>\n      <input type='email' />\n      <input type='password' />\n      <button type='submit'>Login</button>\n    </form>\n  );\n}",
    "fileType": "jsx"
  }
}
```

### Vue Component Analysis

Analyze Vue single-file components:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "<template>\n  <div>\n    <h1>{{ title }}</h1>\n    <img :src='imageUrl' />\n  </div>\n</template>",
    "fileType": "vue"
  }
}
```

### Angular Component Analysis

Analyze Angular components with inline templates:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "@Component({\n  template: `<div>\n    <h1>{{title}}</h1>\n    <button (click)=\"submit()\">Submit</button>\n  </div>`\n})",
    "fileType": "angular"
  }
}
```

### Svelte Component Analysis

Analyze Svelte components:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "<script>\n  let name = 'world';\n</script>\n\n<main>\n  <h1>Hello {name}!</h1>\n  <button on:click={handleClick}>Click me</button>\n</main>",
    "fileType": "svelte"
  }
}
```

### Web Components / Lit Analysis

Analyze Lit web components:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "class MyElement extends LitElement {\n  render() {\n    return html`<div>\n      <h1>My Component</h1>\n      <button @click=${this.handleClick}>Action</button>\n    </div>`;\n  }\n}",
    "fileType": "lit"
  }
}
```

### Template Engine Analysis

Analyze Handlebars templates:

```json
{
  "tool_name": "analyze-accessibility",
  "input": {
    "code": "<div>\n  <h1>{{title}}</h1>\n  {{#each items}}\n    <p>{{this}}</p>\n  {{/each}}\n</div>",
    "fileType": "handlebars"
  }
}
```

## 🔧 **NEW! Auto-Fix Functionality**

### Automatic Code Fixes

Get your code automatically fixed for common accessibility issues:

```json
{
  "tool_name": "fix-accessibility-issues",
  "input": {
    "code": "<div onClick={handleClick}>\n  <img src='logo.png'>\n  <input type='email'>\n  Submit\n</div>",
    "fileType": "jsx"
  }
}
```

**Sample Auto-Fix Output:**
```
# 🔧 Accessibility Auto-Fix Results

**Improvement Score: +45 points**

## ✅ Applied Fixes (4)
1. Added alt attributes to images
2. Converted interactive div to semantic button
3. Added keyboard event handler for accessibility
4. Added aria-label to email input

## 📝 Fixed Code

```jsx
<button onClick={handleClick} onKeyDown={(e) => e.key === 'Enter' && (handleClick)(e)}>
  <img src='logo.png' alt="Image description needed">
  <input type='email' aria-label="Email input">
  Submit
</button>
```

💡 **Next Steps:**
1. Review the fixed code above
2. Copy and replace your original code
3. Address any remaining manual issues
4. Test with screen readers and keyboard navigation
5. Run a full accessibility analysis to verify improvements
```

### What Gets Auto-Fixed

The tool automatically fixes these common accessibility issues:

#### ✅ **Automatically Fixed Issues**
- **Missing alt attributes** → Adds placeholder alt text to images
- **Interactive divs** → Converts to semantic `<button>` elements  
- **Missing ARIA roles** → Adds `role="button"` to interactive elements
- **Keyboard accessibility** → Adds `onKeyDown` handlers to interactive elements
- **Form labels** → Adds `aria-label` to unlabeled inputs
- **Heading hierarchy** → Fixes skipped heading levels (h1→h3 becomes h1→h2)
- **Focus indicators** → Adds outline styles for keyboard focus
- **Color contrast** → Improves low-contrast text colors
- **Semantic structure** → Converts layout divs to `<main>` elements
- **Language declaration** → Adds `lang="en"` to HTML elements

#### ⚠️ **Manual Fixes Required**
- Complex color contrast calculations
- Custom component accessibility patterns
- Content-specific alt text descriptions
- Form validation and error messages
- Table headers and captions
- iframe titles and descriptions
- Video captions and transcripts
- Custom ARIA implementations

### Auto-Fix Examples by Framework

**React Component Fix:**
```jsx
// Before (Score: 45/100)
function LoginForm() {
  return (
    <div onClick={handleSubmit}>
      <img src="/logo.png">
      <input type="email">
      <input type="password">
      Submit
    </div>
  );
}

// After Auto-Fix (Score: 90/100)
function LoginForm() {
  return (
    <button onClick={handleSubmit} onKeyDown={(e) => e.key === 'Enter' && (handleSubmit)(e)}>
      <img src="/logo.png" alt="Company logo">
      <input type="email" aria-label="Email input">
      <input type="password" aria-label="Password input">
      Submit
    </button>
  );
}
```

**Angular Template Fix:**
```typescript
// Before
@Component({
  template: `
    <div (click)="submit()">
      <img src="/icon.png">
      <input type="text">
    </div>
  `
})

// After Auto-Fix
@Component({
  template: `
    <button (click)="submit()">
      <img src="/icon.png" alt="Image description needed">
      <input type="text" aria-label="Text input">
    </button>
  `
})
```

**Vue Component Fix:**
```vue
<!-- Before -->
<template>
  <div @click="navigate">
    <img :src="imageUrl">
    <input type="search">
  </div>
</template>

<!-- After Auto-Fix -->
<template>
  <button @click="navigate">
    <img :src="imageUrl" alt="Image description needed">
    <input type="search" aria-label="Search input">
  </button>
</template>
```

## Focus Areas

### Available Focus Areas

- **all** (default): Check all accessibility aspects
- **keyboard**: Focus on keyboard navigation and interaction
- **screen-reader**: Focus on screen reader compatibility
- **color-contrast**: Focus on color contrast requirements
- **structure**: Focus on semantic structure and landmarks

### Focus Area Examples

**Keyboard Focus:**

```json
{
  "focusArea": "keyboard"
}
```

Checks for: tab order, focus management, keyboard event handlers, focusable elements

**Screen Reader Focus:**

```json
{
  "focusArea": "screen-reader"
}
```

Checks for: ARIA labels, headings, landmarks, alternative text

**Color Contrast Focus:**

```json
{
  "focusArea": "color-contrast"
}
```

Checks for: text contrast ratios, background/foreground combinations

**Structure Focus:**

```json
{
  "focusArea": "structure"
}
```

Checks for: heading hierarchy, semantic elements, page landmarks

## Common Accessibility Issues Detected

### Critical Issues

- Missing alternative text for images
- Insufficient color contrast ratios
- Keyboard inaccessible interactive elements
- Missing form labels

### Serious Issues

- Improper heading hierarchy
- Missing page landmarks
- Inaccessible custom components
- Missing focus indicators

### Moderate Issues

- Redundant alternative text
- Missing skip links
- Improper ARIA usage
- Non-semantic markup

### Minor Issues

- Missing language declarations
- Suboptimal tab order
- Missing descriptive text

## Integration Examples

### CI/CD Integration

Use this tool in continuous integration:

```bash
# Example CI script
npm run build
echo "$FILE_CONTENT" | node build/index.js analyze-accessibility
```

### Development Workflow

1. **Write Code**: Develop your component or page
2. **Quick Check**: Use `quick-accessibility-check` during development
3. **Comprehensive Analysis**: Use `analyze-accessibility` before commit
4. **Focus Review**: Use `suggest-accessibility-improvements` for specific issues
5. **Iterate**: Fix issues and re-analyze until score reaches target (85+ for WCAG AA)

## Best Practices

### Code Quality

- Aim for WCAG AA compliance (score 85+)
- Address critical and serious issues first
- Test with actual assistive technologies
- Validate fixes with users who have disabilities

### Development Process

- Run accessibility checks during development
- Include accessibility requirements in design process
- Create accessibility-focused code reviews
- Maintain accessibility documentation

### Testing Strategy

- Automated testing (this tool)
- Manual testing with screen readers
- Keyboard-only navigation testing
- User testing with people with disabilities

## Supported File Types

### HTML Files

```html
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Example</title>
  </head>
  <body>
    <main>
      <h1>Welcome</h1>
    </main>
  </body>
</html>
```

### React/JSX Components

```jsx
function MyComponent() {
  return (
    <div>
      <h1>Title</h1>
      <button onClick={handleClick}>Action</button>
    </div>
  );
}
```

### TypeScript React Components

```tsx
interface Props {
  title: string;
}

const MyComponent: React.FC<Props> = ({ title }) => (
  <div>
    <h1>{title}</h1>
  </div>
);
```

### Vue Components

```vue
<template>
  <div>
    <h1>{{ title }}</h1>
    <button @click="handleClick">Action</button>
  </div>
</template>
```

## Technical Details

### Dependencies

- **@modelcontextprotocol/sdk**: MCP framework integration
- **axe-core**: Industry-standard accessibility testing engine
- **jsdom**: DOM environment for analysis
- **zod**: Schema validation for tool parameters

### Architecture

1. **Code Preprocessing**: Converts JSX/TSX/Vue to analyzable HTML
2. **DOM Creation**: Creates virtual DOM environment using JSDOM
3. **Accessibility Analysis**: Runs axe-core analysis engine
4. **Report Generation**: Creates comprehensive accessibility reports
5. **Suggestion Engine**: Generates actionable improvement recommendations

### Performance

- Analysis typically completes in under 2 seconds
- Memory usage scales with code complexity
- Supports files up to 1MB in size
- Concurrent analysis supported

## Troubleshooting

### Common Issues

**Error: "Unsupported file type"**

- Ensure fileType parameter matches your code (html, jsx, tsx, vue)
- For mixed content, try fileType: "html"

**Error: "No template found in Vue component"**

- Ensure Vue file has `<template>` section
- Check template syntax for validity

**Low scores despite good practices**

- Review specific violations in detailed report
- Focus on critical and serious issues first
- Consider color contrast requirements

### Getting Help

1. Check the detailed violation reports for specific guidance
2. Review WCAG guidelines linked in violation descriptions
3. Test with actual screen readers for validation
4. Consider professional accessibility audit for complex applications

## Contributing

This tool is part of the scarlet-mesh MCP server collection. To contribute:

1. Follow existing code patterns
2. Add tests for new functionality
3. Update documentation
4. Ensure compatibility with latest WCAG guidelines

## License

MIT License - see the main project license for details.

## Complete Framework & Template Engine Support

This accessibility checker supports an extensive range of frontend frameworks, template engines, and file formats:

### 🌟 Frontend Frameworks

- **React**: JSX, TSX files with full component analysis
- **Angular**: Component templates (inline and external .component.html)
- **Vue.js**: Single-file components (.vue) with template extraction
- **Svelte**: Component files with reactive syntax support
- **Web Components**: Native web components and Lit elements
- **Vanilla JS/TS**: JavaScript files with DOM manipulation

### 🎨 Template Engines

- **Handlebars/Mustache**: Logic-based templating with helper support
- **EJS**: Embedded JavaScript templates
- **Pug (Jade)**: Indentation-based templating
- **Twig**: Symfony's flexible template engine
- **Blade**: Laravel's powerful templating engine
- **Razor**: ASP.NET's server-side templating
- **ERB**: Ruby on Rails embedded Ruby templates

### 🌐 Server-Side Templates

- **PHP**: Mixed HTML/PHP files with embedded logic
- **JSP**: Java Server Pages (basic HTML extraction)
- **ASP**: Classic ASP with server-side code

### 📄 Static Files

- **HTML/HTM**: Standard markup files
- **XML**: Structured markup with accessibility analysis

### 🔧 Usage for Each Framework

**React Component (.jsx/.tsx)**

```javascript
// Component with accessibility issues
function LoginForm() {
  return (
    <div onClick={handleSubmit}>
      {' '}
      {/* Issue: div used as button */}
      <input type="email" /> {/* Issue: missing label */}
      <input type="password" />
      <div>Submit</div> {/* Issue: non-semantic button */}
    </div>
  );
}
```

**Angular Component (.component.ts)**

```typescript
@Component({
  template: `
    <form>
      <input type="email" placeholder="Email" />
      <!-- Issue: placeholder not accessible -->
      <button type="submit" style="color: #ccc; background: #ddd;">
        Submit
        <!-- Issue: poor contrast -->
      </button>
    </form>
  `,
})
export class LoginComponent {}
```

**Vue Component (.vue)**

```vue
<template>
  <div>
    <img src="/logo.png" />
    <!-- Issue: missing alt text -->
    <div @click="navigate">Click here</div>
    <!-- Issue: non-semantic link -->
  </div>
</template>
```

**Svelte Component (.svelte)**

```svelte
<main>
  <h3>Welcome</h3> <!-- Issue: skipped heading level -->
  <div class="button" on:click={submit}>
    Submit Form <!-- Issue: div used as button -->
  </div>
</main>
```

**Handlebars Template (.hbs)**

```handlebars
<div>
  {{#each products}}
    <img src='{{image}}' />
    <!-- Issue: missing alt text -->
    <div onclick='buy({{id}})'>Buy Now</div>
    <!-- Issue: non-semantic button -->
  {{/each}}
</div>
```

**Laravel Blade Template (.blade.php)**

```blade
<form>
  <input type="text" name="search"> <!-- Issue: missing label -->
  @foreach($items as $item)
    <a href="#" onclick="select({{$item->id}})">
      {{$item->name}} <!-- Issue: button functionality in link -->
    </a>
  @endforeach
</form>
```

### ⚡ Quick Framework Detection

The tool automatically detects framework patterns:

- **React**: JSX syntax, component patterns, className attributes
- **Angular**: Component decorators, Angular-specific directives
- **Vue**: Template blocks, Vue directives (v-if, @click, etc.)
- **Svelte**: Svelte syntax (on:click, bind:value, {#if})
- **Template Engines**: Framework-specific delimiters ({{, <%, {%, etc.)

### 🎯 Framework-Specific Accessibility Patterns

**React/JSX Patterns Checked:**

- className vs class attributes
- onClick without onKeyDown
- Custom components without proper ARIA
- Fragment accessibility

**Angular Patterns Checked:**

- Template reference variables accessibility
- Structural directives (*ngFor, *ngIf) impact
- Angular Material component usage
- Component input/output accessibility

**Vue Patterns Checked:**

- v-if/v-show content visibility
- Event modifier accessibility
- Slot content accessibility
- Vue directive compatibility

**Svelte Patterns Checked:**

- Reactive statement accessibility impact
- Component binding accessibility
- Transition accessibility
- Store subscription patterns

### 🚀 Getting Started with Any Framework

1. **Identify your framework**: Use the appropriate fileType parameter
2. **Paste your code**: Copy the template/component code
3. **Run analysis**: Use `analyze-accessibility` tool
4. **Review suggestions**: Get framework-specific improvement recommendations
5. **Apply fixes**: Implement accessibility improvements
6. **Re-test**: Verify improvements with follow-up analysis

This comprehensive support ensures that regardless of your tech stack, you can achieve excellent accessibility compliance across your entire application.